From 0acbf8d9d315c21ef5f0dfc15d601dae4ea818d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 06:20:59 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20feat:=20MVP=20decode=20pipeline?= =?UTF-8?q?=20=E2=80=94=20mp4=20=E2=86=92=20H.264=20=E2=86=92=20gpui=20pre?= =?UTF-8?q?view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - engine: mp4 demux → Annex-B, rusty_h264 software decode, BT.601 I420→BGRA; decode on worker thread behind a bounded channel - engine-hw: optional VA-API decode plugin (cros-codecs) behind a C ABI, dlopen'd at runtime with silent software fallback; the app binary keeps zero libva/gbm/drm linkage so it runs on any distro - app: gpui window, per-frame RenderImage swap + drop_image - vendor/: cros-libva + cros-codecs with 3 LOCAL PATCH fixes (libva 1.23 struct init, radeonsi 64x64 min context, pub surface()) — upstream is dormant, so vendor/ is adopted code, not a temp fork - fixtures are gitignored; scripts/gen_fixtures.sh regenerates them --- .gitignore | 2 + Cargo.lock | 7399 +++++++++++++++++ Cargo.toml | 18 + crates/app/Cargo.toml | 13 + crates/app/src/main.rs | 102 + crates/engine-hw/Cargo.toml | 16 + crates/engine-hw/src/lib.rs | 374 + crates/engine/Cargo.toml | 10 + crates/engine/examples/dump_frame.rs | 34 + crates/engine/src/convert.rs | 56 + crates/engine/src/decode.rs | 130 + crates/engine/src/demux.rs | 132 + crates/engine/src/hw.rs | 180 + crates/engine/src/lib.rs | 14 + crates/engine/tests/decode_baseline.rs | 39 + crates/engine/tests/hw_decode.rs | 110 + scripts/gen_fixtures.sh | 11 + vendor/cros-codecs/.cargo/config.toml | 6 + vendor/cros-codecs/.cargo_vcs_info.json | 6 + vendor/cros-codecs/.clippy.toml | 2 + vendor/cros-codecs/.gitignore | 2 + vendor/cros-codecs/Android.bp | 156 + vendor/cros-codecs/CONTRIBUTING.md | 33 + vendor/cros-codecs/Cargo.lock | 847 ++ vendor/cros-codecs/Cargo.toml | 123 + vendor/cros-codecs/DIR_METADATA | 13 + vendor/cros-codecs/LICENSE | 26 + vendor/cros-codecs/METADATA | 16 + vendor/cros-codecs/MODULE_LICENSE_BSD | 0 vendor/cros-codecs/OWNERS | 10 + vendor/cros-codecs/README.md | 71 + vendor/cros-codecs/cargo_embargo.json | 10 + vendor/cros-codecs/rustfmt.toml | 3 + vendor/cros-codecs/simple_test.py | 46 + vendor/cros-codecs/src/backend.rs | 16 + vendor/cros-codecs/src/backend/dummy.rs | 8 + .../cros-codecs/src/backend/dummy/decoder.rs | 149 + vendor/cros-codecs/src/backend/v4l2.rs | 20 + .../cros-codecs/src/backend/v4l2/decoder.rs | 21 + .../src/backend/v4l2/decoder/stateless.rs | 154 + .../cros-codecs/src/backend/v4l2/encoder.rs | 1368 +++ vendor/cros-codecs/src/backend/vaapi.rs | 270 + .../cros-codecs/src/backend/vaapi/decoder.rs | 339 + .../cros-codecs/src/backend/vaapi/encoder.rs | 651 ++ .../src/backend/vaapi/surface_pool.rs | 225 + vendor/cros-codecs/src/bitstream_utils.rs | 768 ++ vendor/cros-codecs/src/c2_wrapper.rs | 381 + .../cros-codecs/src/c2_wrapper/c2_decoder.rs | 338 + .../cros-codecs/src/c2_wrapper/c2_encoder.rs | 272 + .../src/c2_wrapper/c2_v4l2_decoder.rs | 60 + .../src/c2_wrapper/c2_v4l2_encoder.rs | 131 + .../src/c2_wrapper/c2_vaapi_decoder.rs | 86 + .../src/c2_wrapper/c2_vaapi_encoder.rs | 112 + vendor/cros-codecs/src/codec.rs | 18 + vendor/cros-codecs/src/codec/av1.rs | 9 + vendor/cros-codecs/src/codec/av1/helpers.rs | 178 + vendor/cros-codecs/src/codec/av1/parser.rs | 4216 ++++++++++ vendor/cros-codecs/src/codec/av1/reader.rs | 249 + .../cros-codecs/src/codec/av1/synthesizer.rs | 1796 ++++ vendor/cros-codecs/src/codec/av1/writer.rs | 199 + vendor/cros-codecs/src/codec/h264.rs | 10 + vendor/cros-codecs/src/codec/h264/dpb.rs | 1243 +++ vendor/cros-codecs/src/codec/h264/nalu.rs | 118 + .../cros-codecs/src/codec/h264/nalu_writer.rs | 299 + vendor/cros-codecs/src/codec/h264/parser.rs | 3023 +++++++ vendor/cros-codecs/src/codec/h264/picture.rs | 415 + .../cros-codecs/src/codec/h264/synthesizer.rs | 582 ++ vendor/cros-codecs/src/codec/h265.rs | 7 + vendor/cros-codecs/src/codec/h265/dpb.rs | 276 + vendor/cros-codecs/src/codec/h265/parser.rs | 4784 +++++++++++ vendor/cros-codecs/src/codec/h265/picture.rs | 154 + vendor/cros-codecs/src/codec/vp8.rs | 11 + .../cros-codecs/src/codec/vp8/bool_decoder.rs | 309 + vendor/cros-codecs/src/codec/vp8/parser.rs | 811 ++ vendor/cros-codecs/src/codec/vp8/probs.rs | 365 + vendor/cros-codecs/src/codec/vp9.rs | 10 + vendor/cros-codecs/src/codec/vp9/lookups.rs | 116 + vendor/cros-codecs/src/codec/vp9/parser.rs | 1478 ++++ vendor/cros-codecs/src/decoder.rs | 266 + vendor/cros-codecs/src/decoder/stateless.rs | 495 ++ .../cros-codecs/src/decoder/stateless/av1.rs | 565 ++ .../src/decoder/stateless/av1/dummy.rs | 69 + .../src/decoder/stateless/av1/v4l2.rs | 169 + .../src/decoder/stateless/av1/vaapi.rs | 625 ++ .../cros-codecs/src/decoder/stateless/h264.rs | 1501 ++++ .../src/decoder/stateless/h264/dummy.rs | 75 + .../src/decoder/stateless/h264/v4l2.rs | 180 + .../src/decoder/stateless/h264/vaapi.rs | 733 ++ .../cros-codecs/src/decoder/stateless/h265.rs | 1365 +++ .../src/decoder/stateless/h265/dummy.rs | 74 + .../src/decoder/stateless/h265/vaapi.rs | 980 +++ .../cros-codecs/src/decoder/stateless/vp8.rs | 364 + .../src/decoder/stateless/vp8/dummy.rs | 53 + .../src/decoder/stateless/vp8/v4l2.rs | 151 + .../src/decoder/stateless/vp8/vaapi.rs | 707 ++ .../cros-codecs/src/decoder/stateless/vp9.rs | 461 + .../src/decoder/stateless/vp9/dummy.rs | 51 + .../src/decoder/stateless/vp9/v4l2.rs | 154 + .../src/decoder/stateless/vp9/vaapi.rs | 651 ++ vendor/cros-codecs/src/device.rs | 6 + vendor/cros-codecs/src/device/v4l2.rs | 6 + .../cros-codecs/src/device/v4l2/stateless.rs | 8 + .../src/device/v4l2/stateless/controls.rs | 8 + .../src/device/v4l2/stateless/controls/av1.rs | 689 ++ .../device/v4l2/stateless/controls/h264.rs | 294 + .../src/device/v4l2/stateless/controls/vp8.rs | 183 + .../src/device/v4l2/stateless/controls/vp9.rs | 212 + .../src/device/v4l2/stateless/device.rs | 227 + .../src/device/v4l2/stateless/queue.rs | 447 + .../src/device/v4l2/stateless/request.rs | 249 + vendor/cros-codecs/src/device/v4l2/utils.rs | 130 + vendor/cros-codecs/src/encoder.rs | 418 + vendor/cros-codecs/src/encoder/av1.rs | 34 + vendor/cros-codecs/src/encoder/h264.rs | 34 + vendor/cros-codecs/src/encoder/h265.rs | 30 + vendor/cros-codecs/src/encoder/stateful.rs | 257 + .../cros-codecs/src/encoder/stateful/h264.rs | 6 + .../src/encoder/stateful/h264/v4l2.rs | 313 + .../cros-codecs/src/encoder/stateful/h265.rs | 6 + .../src/encoder/stateful/h265/v4l2.rs | 305 + .../cros-codecs/src/encoder/stateful/vp8.rs | 6 + .../src/encoder/stateful/vp8/v4l2.rs | 332 + .../cros-codecs/src/encoder/stateful/vp9.rs | 6 + .../src/encoder/stateful/vp9/v4l2.rs | 337 + vendor/cros-codecs/src/encoder/stateless.rs | 398 + .../cros-codecs/src/encoder/stateless/av1.rs | 133 + .../src/encoder/stateless/av1/predictor.rs | 326 + .../src/encoder/stateless/av1/vaapi.rs | 1009 +++ .../cros-codecs/src/encoder/stateless/h264.rs | 197 + .../src/encoder/stateless/h264/predictor.rs | 269 + .../src/encoder/stateless/h264/vaapi.rs | 695 ++ .../src/encoder/stateless/predictor.rs | 346 + .../cros-codecs/src/encoder/stateless/vp9.rs | 122 + .../src/encoder/stateless/vp9/predictor.rs | 138 + .../src/encoder/stateless/vp9/vaapi.rs | 602 ++ vendor/cros-codecs/src/encoder/vp8.rs | 24 + vendor/cros-codecs/src/encoder/vp9.rs | 31 + vendor/cros-codecs/src/image_processing.rs | 551 ++ vendor/cros-codecs/src/lib.rs | 463 ++ vendor/cros-codecs/src/utils.rs | 117 + vendor/cros-codecs/src/video_frame.rs | 311 + .../cros-codecs/src/video_frame/frame_pool.rs | 115 + .../src/video_frame/gbm_video_frame.rs | 784 ++ .../video_frame/generic_dma_video_frame.rs | 548 ++ .../src/video_frame/v4l2_mmap_video_frame.rs | 158 + vendor/cros-libva/.cargo_vcs_info.json | 6 + vendor/cros-libva/Android.bp | 76 + vendor/cros-libva/Cargo.toml | 42 + vendor/cros-libva/README.md | 83 + vendor/cros-libva/bindgen_gen.rs | 18 + vendor/cros-libva/build.rs | 141 + vendor/cros-libva/libva-wrapper.h | 7 + vendor/cros-libva/src/bindings.rs | 15 + vendor/cros-libva/src/buffer.rs | 553 ++ vendor/cros-libva/src/buffer/av1.rs | 1156 +++ vendor/cros-libva/src/buffer/enc_misc.rs | 337 + vendor/cros-libva/src/buffer/h264.rs | 807 ++ vendor/cros-libva/src/buffer/hevc.rs | 1154 +++ vendor/cros-libva/src/buffer/mpeg2.rs | 172 + vendor/cros-libva/src/buffer/vp8.rs | 397 + vendor/cros-libva/src/buffer/vp9.rs | 448 + vendor/cros-libva/src/config.rs | 137 + vendor/cros-libva/src/context.rs | 102 + vendor/cros-libva/src/display.rs | 362 + vendor/cros-libva/src/generic_value.rs | 50 + vendor/cros-libva/src/image.rs | 235 + vendor/cros-libva/src/lib.rs | 540 ++ vendor/cros-libva/src/picture.rs | 307 + vendor/cros-libva/src/surface.rs | 452 + vendor/cros-libva/src/test_frame.nv12 | Bin 0 -> 6144 bytes vendor/cros-libva/src/usage_hint.rs | 26 + 171 files changed, 65247 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/app/Cargo.toml create mode 100644 crates/app/src/main.rs create mode 100644 crates/engine-hw/Cargo.toml create mode 100644 crates/engine-hw/src/lib.rs create mode 100644 crates/engine/Cargo.toml create mode 100644 crates/engine/examples/dump_frame.rs create mode 100644 crates/engine/src/convert.rs create mode 100644 crates/engine/src/decode.rs create mode 100644 crates/engine/src/demux.rs create mode 100644 crates/engine/src/hw.rs create mode 100644 crates/engine/src/lib.rs create mode 100644 crates/engine/tests/decode_baseline.rs create mode 100644 crates/engine/tests/hw_decode.rs create mode 100755 scripts/gen_fixtures.sh create mode 100644 vendor/cros-codecs/.cargo/config.toml create mode 100644 vendor/cros-codecs/.cargo_vcs_info.json create mode 100644 vendor/cros-codecs/.clippy.toml create mode 100644 vendor/cros-codecs/.gitignore create mode 100644 vendor/cros-codecs/Android.bp create mode 100644 vendor/cros-codecs/CONTRIBUTING.md create mode 100644 vendor/cros-codecs/Cargo.lock create mode 100644 vendor/cros-codecs/Cargo.toml create mode 100644 vendor/cros-codecs/DIR_METADATA create mode 100644 vendor/cros-codecs/LICENSE create mode 100644 vendor/cros-codecs/METADATA create mode 100644 vendor/cros-codecs/MODULE_LICENSE_BSD create mode 100644 vendor/cros-codecs/OWNERS create mode 100644 vendor/cros-codecs/README.md create mode 100644 vendor/cros-codecs/cargo_embargo.json create mode 100644 vendor/cros-codecs/rustfmt.toml create mode 100644 vendor/cros-codecs/simple_test.py create mode 100644 vendor/cros-codecs/src/backend.rs create mode 100644 vendor/cros-codecs/src/backend/dummy.rs create mode 100644 vendor/cros-codecs/src/backend/dummy/decoder.rs create mode 100644 vendor/cros-codecs/src/backend/v4l2.rs create mode 100644 vendor/cros-codecs/src/backend/v4l2/decoder.rs create mode 100644 vendor/cros-codecs/src/backend/v4l2/decoder/stateless.rs create mode 100644 vendor/cros-codecs/src/backend/v4l2/encoder.rs create mode 100644 vendor/cros-codecs/src/backend/vaapi.rs create mode 100644 vendor/cros-codecs/src/backend/vaapi/decoder.rs create mode 100644 vendor/cros-codecs/src/backend/vaapi/encoder.rs create mode 100644 vendor/cros-codecs/src/backend/vaapi/surface_pool.rs create mode 100644 vendor/cros-codecs/src/bitstream_utils.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_decoder.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_encoder.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_v4l2_decoder.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_v4l2_encoder.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_vaapi_decoder.rs create mode 100644 vendor/cros-codecs/src/c2_wrapper/c2_vaapi_encoder.rs create mode 100644 vendor/cros-codecs/src/codec.rs create mode 100644 vendor/cros-codecs/src/codec/av1.rs create mode 100644 vendor/cros-codecs/src/codec/av1/helpers.rs create mode 100644 vendor/cros-codecs/src/codec/av1/parser.rs create mode 100644 vendor/cros-codecs/src/codec/av1/reader.rs create mode 100644 vendor/cros-codecs/src/codec/av1/synthesizer.rs create mode 100644 vendor/cros-codecs/src/codec/av1/writer.rs create mode 100644 vendor/cros-codecs/src/codec/h264.rs create mode 100644 vendor/cros-codecs/src/codec/h264/dpb.rs create mode 100644 vendor/cros-codecs/src/codec/h264/nalu.rs create mode 100644 vendor/cros-codecs/src/codec/h264/nalu_writer.rs create mode 100644 vendor/cros-codecs/src/codec/h264/parser.rs create mode 100644 vendor/cros-codecs/src/codec/h264/picture.rs create mode 100644 vendor/cros-codecs/src/codec/h264/synthesizer.rs create mode 100644 vendor/cros-codecs/src/codec/h265.rs create mode 100644 vendor/cros-codecs/src/codec/h265/dpb.rs create mode 100644 vendor/cros-codecs/src/codec/h265/parser.rs create mode 100644 vendor/cros-codecs/src/codec/h265/picture.rs create mode 100644 vendor/cros-codecs/src/codec/vp8.rs create mode 100644 vendor/cros-codecs/src/codec/vp8/bool_decoder.rs create mode 100644 vendor/cros-codecs/src/codec/vp8/parser.rs create mode 100644 vendor/cros-codecs/src/codec/vp8/probs.rs create mode 100644 vendor/cros-codecs/src/codec/vp9.rs create mode 100644 vendor/cros-codecs/src/codec/vp9/lookups.rs create mode 100644 vendor/cros-codecs/src/codec/vp9/parser.rs create mode 100644 vendor/cros-codecs/src/decoder.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/av1.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/av1/dummy.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/av1/v4l2.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h264.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h264/dummy.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h264/v4l2.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h264/vaapi.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h265.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h265/dummy.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/h265/vaapi.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp8.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp8/dummy.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp8/v4l2.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp8/vaapi.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp9.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp9/dummy.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp9/v4l2.rs create mode 100644 vendor/cros-codecs/src/decoder/stateless/vp9/vaapi.rs create mode 100644 vendor/cros-codecs/src/device.rs create mode 100644 vendor/cros-codecs/src/device/v4l2.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/controls.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/controls/av1.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/controls/h264.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/controls/vp8.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/controls/vp9.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/device.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/queue.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/stateless/request.rs create mode 100644 vendor/cros-codecs/src/device/v4l2/utils.rs create mode 100644 vendor/cros-codecs/src/encoder.rs create mode 100644 vendor/cros-codecs/src/encoder/av1.rs create mode 100644 vendor/cros-codecs/src/encoder/h264.rs create mode 100644 vendor/cros-codecs/src/encoder/h265.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/h264.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/h264/v4l2.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/h265.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/h265/v4l2.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/vp8.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/vp8/v4l2.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/vp9.rs create mode 100644 vendor/cros-codecs/src/encoder/stateful/vp9/v4l2.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/av1.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/av1/predictor.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/av1/vaapi.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/h264.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/h264/predictor.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/h264/vaapi.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/predictor.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/vp9.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/vp9/predictor.rs create mode 100644 vendor/cros-codecs/src/encoder/stateless/vp9/vaapi.rs create mode 100644 vendor/cros-codecs/src/encoder/vp8.rs create mode 100644 vendor/cros-codecs/src/encoder/vp9.rs create mode 100644 vendor/cros-codecs/src/image_processing.rs create mode 100644 vendor/cros-codecs/src/lib.rs create mode 100644 vendor/cros-codecs/src/utils.rs create mode 100644 vendor/cros-codecs/src/video_frame.rs create mode 100644 vendor/cros-codecs/src/video_frame/frame_pool.rs create mode 100644 vendor/cros-codecs/src/video_frame/gbm_video_frame.rs create mode 100644 vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs create mode 100644 vendor/cros-codecs/src/video_frame/v4l2_mmap_video_frame.rs create mode 100644 vendor/cros-libva/.cargo_vcs_info.json create mode 100644 vendor/cros-libva/Android.bp create mode 100644 vendor/cros-libva/Cargo.toml create mode 100644 vendor/cros-libva/README.md create mode 100644 vendor/cros-libva/bindgen_gen.rs create mode 100644 vendor/cros-libva/build.rs create mode 100644 vendor/cros-libva/libva-wrapper.h create mode 100644 vendor/cros-libva/src/bindings.rs create mode 100644 vendor/cros-libva/src/buffer.rs create mode 100644 vendor/cros-libva/src/buffer/av1.rs create mode 100644 vendor/cros-libva/src/buffer/enc_misc.rs create mode 100644 vendor/cros-libva/src/buffer/h264.rs create mode 100644 vendor/cros-libva/src/buffer/hevc.rs create mode 100644 vendor/cros-libva/src/buffer/mpeg2.rs create mode 100644 vendor/cros-libva/src/buffer/vp8.rs create mode 100644 vendor/cros-libva/src/buffer/vp9.rs create mode 100644 vendor/cros-libva/src/config.rs create mode 100644 vendor/cros-libva/src/context.rs create mode 100644 vendor/cros-libva/src/display.rs create mode 100644 vendor/cros-libva/src/generic_value.rs create mode 100644 vendor/cros-libva/src/image.rs create mode 100644 vendor/cros-libva/src/lib.rs create mode 100644 vendor/cros-libva/src/picture.rs create mode 100644 vendor/cros-libva/src/surface.rs create mode 100644 vendor/cros-libva/src/test_frame.nv12 create mode 100644 vendor/cros-libva/src/usage_hint.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85ef3d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/assets diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..50d8715 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7399 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", + "zeroize", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "app" +version = "0.1.0" +dependencies = [ + "engine", + "gpui", + "image", +] + +[[package]] +name = "ar_archive_writer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +dependencies = [ + "object", +] + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "ash-window" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52bca67b61cb81e5553babde81b8211f713cb6db79766f80168f3e5f40ea6c82" +dependencies = [ + "ash", + "raw-window-handle", + "raw-window-metal", +] + +[[package]] +name = "ashpd" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39" +dependencies = [ + "async-fs", + "async-net", + "enumflags2", + "futures-channel", + "futures-util", + "rand 0.9.5", + "serde", + "serde_repr", + "url", + "wayland-backend", + "wayland-client", + "wayland-protocols 0.32.13", + "zbus", +] + +[[package]] +name = "ashpd" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33a3c86f3fd70c0ffa500ed189abfa90b5a52398a45d5dc372fcc38ebeb7a645" +dependencies = [ + "async-fs", + "async-net", + "enumflags2", + "futures-channel", + "futures-util", + "rand 0.9.5", + "serde", + "serde_repr", + "url", + "zbus", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener 5.4.2", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-compression" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8" +dependencies = [ + "compression-codecs", + "compression-core", + "futures-io", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand 2.5.0", + "futures-lite 2.6.1", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" +dependencies = [ + "async-lock", + "blocking", + "futures-lite 2.6.1", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite 2.6.1", + "once_cell", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.6.1", + "parking", + "polling", + "rustix 1.1.4", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener 5.4.2", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-net" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" +dependencies = [ + "async-io", + "blocking", + "futures-lite 2.6.1", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel 2.5.0", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener 5.4.2", + "futures-lite 2.6.1", + "rustix 1.1.4", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.4", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-std" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" +dependencies = [ + "async-channel 1.9.0", + "async-global-executor", + "async-io", + "async-lock", + "async-process", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 2.6.1", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "async_zip" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b9f7252833d5ed4b00aa9604b563529dd5e11de9c23615de2dcdf91eb87b52" +dependencies = [ + "async-compression", + "crc32fast", + "futures-lite 2.6.1", + "pin-project", + "thiserror 1.0.69", +] + +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.20", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bindgen" +version = "0.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +dependencies = [ + "bitflags 2.13.1", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bindgen" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +dependencies = [ + "bitflags 2.13.1", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "blade-graphics" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e71cfb73b98eb9f58ee84048aa1bdf4e7497fd20c141b57523499fa066b48fed" +dependencies = [ + "ash", + "ash-window", + "bitflags 2.13.1", + "bytemuck", + "codespan-reporting", + "glow", + "gpu-alloc", + "gpu-alloc-ash", + "hidden-trait", + "js-sys", + "khronos-egl", + "libloading", + "log", + "mint", + "naga", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-metal", + "objc2-quartz-core", + "objc2-ui-kit", + "once_cell", + "raw-window-handle", + "slab", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "blade-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27142319e2f4c264581067eaccb9f80acccdde60d8b4bf57cc50cd3152f109ca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "blade-util" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a6be3a82c001ba7a17b6f8e413ede5d1004e6047213f8efaf0ffc15b5c4904c" +dependencies = [ + "blade-graphics", + "bytemuck", + "log", + "profiling", +] + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel 2.5.0", + "async-task", + "futures-io", + "futures-lite 2.6.1", + "piper", +] + +[[package]] +name = "bstr" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" +dependencies = [ + "memchr", + "serde_core", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.1", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cbindgen" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" +dependencies = [ + "heck 0.4.1", + "indexmap", + "log", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "tempfile", + "toml 0.8.23", +] + +[[package]] +name = "cc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cocoa" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" +dependencies = [ + "bitflags 1.3.2", + "block", + "cocoa-foundation 0.1.2", + "core-foundation 0.9.4", + "core-graphics 0.23.2", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2" +dependencies = [ + "bitflags 2.13.1", + "block", + "cocoa-foundation 0.2.0", + "core-foundation 0.10.0", + "core-graphics 0.24.0", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c6234cbb2e4c785b456c0644748b1ac416dd045799740356f8363dfe00c93f7" +dependencies = [ + "bitflags 1.3.2", + "block", + "core-foundation 0.9.4", + "core-graphics-types 0.1.3", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d" +dependencies = [ + "bitflags 2.13.1", + "block", + "core-foundation 0.10.0", + "core-graphics-types 0.2.0", + "libc", + "objc", +] + +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "command-fds" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b60b5124979fccd9addd89d8b97a1d6eebb4950694520c75ddd722535ea443f" +dependencies = [ + "nix 0.31.3", + "thiserror 2.0.20", +] + +[[package]] +name = "compression-codecs" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf" +dependencies = [ + "compression-core", + "deflate64", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "core-graphics-types 0.1.3", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.10.0", + "core-graphics-types 0.2.0", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-helmer-fork" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.9.4", + "core-graphics-types 0.1.3", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.10.0", + "libc", +] + +[[package]] +name = "core-graphics2" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e4583956b9806b69f73fcb23aee05eb3620efc282972f08f6a6db7504f8334d" +dependencies = [ + "bitflags 2.13.1", + "block", + "cfg-if", + "core-foundation 0.10.0", + "libc", +] + +[[package]] +name = "core-text" +version = "21.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a593227b66cbd4007b2a050dfdd9e1d1318311409c8d600dc82ba1b15ca9c130" +dependencies = [ + "core-foundation 0.10.0", + "core-graphics 0.24.0", + "foreign-types", + "libc", +] + +[[package]] +name = "core-video" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45e71d5be22206bed53c3c3cb99315fc4c3d31b8963808c6bc4538168c4f8ef" +dependencies = [ + "block", + "core-foundation 0.10.0", + "core-graphics2", + "io-surface", + "libc", + "metal", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cosmic-text" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da46a9d5a8905cc538a4a5bceb6a4510de7a51049c5588c0114efce102bcbbe8" +dependencies = [ + "bitflags 2.13.1", + "fontdb 0.16.2", + "log", + "rangemap", + "rustc-hash 1.1.0", + "rustybuzz 0.14.1", + "self_cell", + "smol_str", + "swash", + "sys-locale", + "ttf-parser 0.21.1", + "unicode-bidi", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cros-codecs" +version = "0.0.6" +dependencies = [ + "anyhow", + "byteorder", + "crc32fast", + "cros-libva", + "drm", + "drm-fourcc", + "gbm", + "gbm-sys", + "log", + "nix 0.28.0", + "thiserror 1.0.69", + "zerocopy", +] + +[[package]] +name = "cros-libva" +version = "0.0.12" +dependencies = [ + "bindgen 0.70.1", + "bitflags 2.13.1", + "log", + "pkg-config", + "regex", + "thiserror 1.0.69", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctor" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec09e802f5081de6157da9a75701d6c713d8dc3ba52571fd4bd25f412644e8a6" +dependencies = [ + "ctor-proc-macro", + "dtor", +] + +[[package]] +name = "ctor-proc-macro" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2" + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys 0.3.7", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.1", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "drm" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98888c4bbd601524c11a7ed63f814b8825f420514f78e96f752c437ae9cbb5d1" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "rustix 0.38.44", +] + +[[package]] +name = "drm-ffi" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97c98727e48b7ccb4f4aea8cfe881e5b07f702d17b7875991881b41af7278d53" +dependencies = [ + "drm-sys", + "rustix 0.38.44", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd39dde40b6e196c2e8763f23d119ddb1a8714534bf7d77fa97a65b0feda3986" +dependencies = [ + "libc", + "linux-raw-sys 0.6.5", +] + +[[package]] +name = "dtor" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97cbdf2ad6846025e8e25df05171abfb30e3ababa12ee0a0e44b9bbe570633a8" +dependencies = [ + "dtor-proc-macro", +] + +[[package]] +name = "dtor-proc-macro" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dwrote" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02" +dependencies = [ + "lazy_static", + "libc", + "winapi", + "wio", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "embed-resource" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.1.4+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "engine" +version = "0.1.0" +dependencies = [ + "libloading", + "mp4", + "rusty_h264", +] + +[[package]] +name = "engine-hw" +version = "0.1.0" +dependencies = [ + "cros-codecs", + "engine", + "gbm", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased-serde" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etagere" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342" +dependencies = [ + "euclid", + "svg_fmt", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener 5.4.2", + "pin-project-lite", +] + +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide", + "num-complex", + "pulp", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "float-ord" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" + +[[package]] +name = "float_next_after" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "font-types" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a7299a780854a6d391be2ae1c8521c9368471b559dbfd6a8dbd9f407eaff100" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree", +] + +[[package]] +name = "fontdb" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser 0.25.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "freetype-sys" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand 2.5.0", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gbm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45bf55ba6dd53ad0ac115046ff999c5324c283444ee6e0be82454c4e8eb2f36a" +dependencies = [ + "bitflags 2.13.1", + "drm", + "drm-fourcc", + "gbm-sys", + "libc", +] + +[[package]] +name = "gbm-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cc2f64de9fa707b5c6b2d2f10d7a7e49e845018a9f5685891eb40d3bab2538" +dependencies = [ + "libc", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.4", + "windows-link 0.2.1", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "gpu-alloc" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9" +dependencies = [ + "bitflags 2.13.1", + "gpu-alloc-types", +] + +[[package]] +name = "gpu-alloc-ash" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643756f08ef6def813c776199e4766596395a4c6530373c9a4374a64de2f53a1" +dependencies = [ + "ash", + "gpu-alloc-types", + "tinyvec", +] + +[[package]] +name = "gpu-alloc-types" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "gpui" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "979b45cfa6ec723b6f42330915a1b3769b930d02b2d505f9697f8ca602bee707" +dependencies = [ + "anyhow", + "as-raw-xcb-connection", + "ashpd 0.11.1", + "async-task", + "bindgen 0.71.1", + "blade-graphics", + "blade-macros", + "blade-util", + "block", + "bytemuck", + "calloop", + "calloop-wayland-source", + "cbindgen", + "cocoa 0.26.0", + "cocoa-foundation 0.2.0", + "core-foundation 0.10.0", + "core-foundation-sys", + "core-graphics 0.24.0", + "core-text", + "core-video", + "cosmic-text", + "ctor", + "derive_more", + "embed-resource", + "etagere", + "filedescriptor", + "flume", + "foreign-types", + "futures", + "gpui-macros", + "gpui_collections", + "gpui_http_client", + "gpui_media", + "gpui_refineable", + "gpui_semantic_version", + "gpui_sum_tree", + "gpui_util", + "gpui_util_macros", + "image", + "inventory", + "itertools 0.14.0", + "libc", + "log", + "lyon", + "metal", + "naga", + "num_cpus", + "objc", + "oo7", + "open", + "parking", + "parking_lot", + "pathfinder_geometry", + "pin-project", + "postage", + "profiling", + "rand 0.9.5", + "raw-window-handle", + "resvg", + "schemars", + "seahash", + "serde", + "serde_json", + "slotmap", + "smallvec", + "smol", + "stacksafe", + "strum 0.27.2", + "taffy", + "thiserror 2.0.20", + "usvg", + "uuid", + "waker-fn", + "wayland-backend", + "wayland-client", + "wayland-cursor", + "wayland-protocols 0.31.2", + "wayland-protocols-plasma", + "windows 0.61.3", + "windows-core 0.61.2", + "windows-numerics", + "windows-registry 0.5.3", + "x11-clipboard", + "x11rb", + "xkbcommon", + "zed-font-kit", + "zed-scap", + "zed-xim", +] + +[[package]] +name = "gpui-macros" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcb02dd63a2859714ac7b6b476937617c3c744157af1b49f7c904023a79039be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gpui_collections" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae39dc6d3d201be97e4bc08d96dbef2bc5b5c3d5734e05786e8cc3043342351c" +dependencies = [ + "indexmap", + "rustc-hash 2.1.3", +] + +[[package]] +name = "gpui_derive_refineable" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "644de174341a87b3478bd65b66bca38af868bcf2b2e865700523734f83cfc664" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gpui_http_client" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23822b0a6d2c5e6a42507980a0ab3848610ea908942c8ef98187f646f690335e" +dependencies = [ + "anyhow", + "async-compression", + "async-fs", + "bytes", + "derive_more", + "futures", + "gpui_util", + "http", + "http-body", + "log", + "parking_lot", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "url", + "zed-async-tar", + "zed-reqwest", +] + +[[package]] +name = "gpui_media" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05cb8912ae17371725132d2b7eec6797a255accc95d58ee5c1134b529810f14b" +dependencies = [ + "anyhow", + "bindgen 0.71.1", + "core-foundation 0.10.0", + "core-video", + "ctor", + "foreign-types", + "metal", + "objc", +] + +[[package]] +name = "gpui_perf" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40a0961dcf598955130e867f4b731150a20546427b41b1a63767c1037a86d77" +dependencies = [ + "gpui_collections", + "serde", + "serde_json", +] + +[[package]] +name = "gpui_refineable" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "258cb099254e9468181aee5614410fba61db4ae115fc1d51b4a0b985f60d6641" +dependencies = [ + "gpui_derive_refineable", +] + +[[package]] +name = "gpui_semantic_version" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "201e45eff7b695528fb3af6560a534943fbc2db5323d755b9d198bd743948e35" +dependencies = [ + "anyhow", + "serde", +] + +[[package]] +name = "gpui_sum_tree" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4f3bedd573fafafa13d1200b356c588cf094fb2786e3684bb3f5ea59b549fa9" +dependencies = [ + "arrayvec", + "log", + "rayon", +] + +[[package]] +name = "gpui_util" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68faea25903ae524de9af83990b9aa51bcbc8dd085929ac0aea7fd41905e05c3" +dependencies = [ + "anyhow", + "async-fs", + "async_zip", + "command-fds", + "dirs 4.0.0", + "dunce", + "futures", + "futures-lite 1.13.0", + "globset", + "gpui_collections", + "itertools 0.14.0", + "libc", + "log", + "nix 0.29.0", + "regex", + "rust-embed", + "schemars", + "serde", + "serde_json", + "serde_json_lenient", + "shlex 1.3.0", + "smol", + "take-until", + "tempfile", + "tendril", + "unicase", + "walkdir", + "which", +] + +[[package]] +name = "gpui_util_macros" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c28f65ef47fb97e21e82fd4dd75ccc2506eda010c846dc8054015ea234f1a22" +dependencies = [ + "gpui_perf", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "grid" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12101ecc8225ea6d675bc70263074eab6169079621c2186fe0c66590b2df9681" + +[[package]] +name = "h2" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + +[[package]] +name = "hidden-trait" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ed9e850438ac849bec07e7d09fbe9309cbd396a5988c30b010580ce08860df" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-native-certs", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png 0.18.1", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "imgref" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89194689a993ab15268672e99e7b0e19da2da3268ac682e8f02d29d4d1434cd7" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "inventory" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-surface" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "554b8c5d64ec09a3a520fe58e4d48a73e00ff32899cdcbe32a4877afd4968b8e" +dependencies = [ + "cgl", + "core-foundation 0.10.0", + "core-foundation-sys", + "leaky-cow", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", +] + +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "leak" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd100e01f1154f2908dfa7d02219aeab25d0b9c7fa955164192e3245255a0c73" + +[[package]] +name = "leaky-cow" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a8225d44241fd324a8af2806ba635fc7c8a7e9a7de4d5cf3ef54e71f5926fc" +dependencies = [ + "leak", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link 0.2.1", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2026a5056764a10b2bf5d56488cba40da507f5493a6a429340e2004d9ed085fa" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a385b1be4e5c3e362ad2ffa73c392e53f031eaa5b7d648e64cd87f27f6063d7" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +dependencies = [ + "serde_core", + "value-bag", +] + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "lyon" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7" +dependencies = [ + "lyon_algorithms", + "lyon_tessellation", +] + +[[package]] +name = "lyon_algorithms" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8575c0d003ae459399623c4def180c63b77f343b1a7fee64f249b349e7699a31" +dependencies = [ + "lyon_path", + "num-traits", +] + +[[package]] +name = "lyon_geom" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92" +dependencies = [ + "arrayvec", + "euclid", + "num-traits", +] + +[[package]] +name = "lyon_path" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" +dependencies = [ + "lyon_geom", + "num-traits", +] + +[[package]] +name = "lyon_tessellation" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e43b7e44161571868f5c931d12583592c223c5583eef86b08aa02b7048a3552" +dependencies = [ + "float_next_after", + "lyon_path", + "num-traits", +] + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "metal" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21" +dependencies = [ + "bitflags 2.13.1", + "block", + "core-graphics-types 0.1.3", + "foreign-types", + "log", + "objc", + "paste", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mint" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "mp4" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9ef834d5ed55e494a2ae350220314dc4aacd1c43a9498b00e320e0ea352a5c3" +dependencies = [ + "byteorder", + "bytes", + "num-rational", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "naga" +version = "25.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.1", + "cfg_aliases 0.2.2", + "codespan-reporting", + "half", + "hashbrown 0.15.5", + "hexf-parse", + "indexmap", + "log", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "strum 0.26.3", + "thiserror 2.0.20", + "unicode-ident", +] + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.1", + "cfg-if", + "cfg_aliases 0.1.1", + "libc", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.1", + "cfg-if", + "cfg_aliases 0.2.2", + "libc", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.1", + "cfg-if", + "cfg_aliases 0.2.2", + "libc", +] + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.7", + "serde", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", + "objc_exception", +] + +[[package]] +name = "objc-foundation" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" +dependencies = [ + "block", + "objc", + "objc_id", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.1", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.1", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc_exception" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" +dependencies = [ + "cc", +] + +[[package]] +name = "objc_id" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" +dependencies = [ + "objc", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "oo7" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3299dd401feaf1d45afd8fd1c0586f10fcfb22f244bb9afa942cec73503b89d" +dependencies = [ + "aes", + "ashpd 0.12.3", + "async-fs", + "async-io", + "async-lock", + "blocking", + "cbc", + "cipher", + "digest 0.10.7", + "endi", + "futures-lite 2.6.1", + "futures-util", + "getrandom 0.3.4", + "hkdf", + "hmac", + "md-5", + "num", + "num-bigint-dig", + "pbkdf2", + "rand 0.9.5", + "serde", + "sha2 0.10.9", + "subtle", + "zbus", + "zbus_macros", + "zeroize", + "zvariant", +] + +[[package]] +name = "open" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9cfef937e9c486488c7e3d949ae31c0f1d06bdacd75b99c086cb35356e30408" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pathfinder_geometry" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" +dependencies = [ + "log", + "pathfinder_simd", +] + +[[package]] +name = "pathfinder_simd" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand 2.5.0", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" + +[[package]] +name = "postage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" +dependencies = [ + "atomic", + "crossbeam-queue", + "futures", + "log", + "parking_lot", + "pin-project", + "pollster", + "static_assertions", + "thiserror 1.0.69", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.13+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff6510e86862b57b210fd8cbe8ed3f0d7d600b9c2863cd4549a2e033c66e956" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases 0.2.2", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.20", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.20", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases 0.2.2", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rangemap" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68" + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.20", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76e8caa82e31bb98fee12fa8f051c94a6aa36b07cddb03f0d4fc558988360ff1" +dependencies = [ + "cocoa 0.25.0", + "core-graphics 0.23.2", + "objc", + "raw-window-handle", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "ref-cast" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "rust-embed" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9e7760e252aaba7b09f4be00e36476cf585bdb68a53552ac954cdf504ab4bc9" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcfc4d6f53af43755f7a723e4b6b8794fcce052a178dd8c6c1dadc5f5343097" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0" +dependencies = [ + "globset", + "sha2 0.11.0", + "walkdir", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty_h264" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fbafa4757ced9c5c1d1185aa936bb040b00c456098874f209e04ed1c1c2d73b" +dependencies = [ + "rusty_h264-common", + "rusty_h264-decoder", + "rusty_h264-encoder", +] + +[[package]] +name = "rusty_h264-common" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421e458fcfcb2580232f212f99451f9075a03d00752a934ee27be6148a6765e3" +dependencies = [ + "bytemuck", + "wide", +] + +[[package]] +name = "rusty_h264-decoder" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6316ecba57a77d530fff4fab7be9cc3e0e107e381360ac9d2ffa0895b5b0947a" +dependencies = [ + "rusty_h264-common", +] + +[[package]] +name = "rusty_h264-encoder" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fb69d8977d1d067d6d603df0614678c4a35ac1201fff38783c8847e429c879" +dependencies = [ + "rusty_h264-common", +] + +[[package]] +name = "rustybuzz" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "libm", + "smallvec", + "ttf-parser 0.21.1", + "unicode-bidi-mirroring 0.2.0", + "unicode-ccc 0.2.0", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser 0.25.1", + "unicode-bidi-mirroring 0.4.0", + "unicode-ccc 0.4.0", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +dependencies = [ + "dyn-clone", + "indexmap", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.3", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "screencapturekit" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5eeeb57ac94960cfe5ff4c402be6585ae4c8d29a2cf41b276048c2e849d64e" +dependencies = [ + "screencapturekit-sys", +] + +[[package]] +name = "screencapturekit-sys" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22411b57f7d49e7fe08025198813ee6fd65e1ee5eff4ebc7880c12c82bde4c60" +dependencies = [ + "block", + "dispatch", + "objc", + "objc-foundation", + "objc_id", + "once_cell", +] + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.10.0", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_fmt" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e497af288b3b95d067a23a4f749f2861121ffcb2f6d8379310dcda040c345ed" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_json_lenient" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "smol" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-net", + "async-process", + "blocking", + "futures-lite 2.6.1", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spirv" +version = "0.3.0+sdk-1.3.268.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "stacksafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9c1172965d317e87ddb6d364a040d958b40a1db82b6ef97da26253a8b3d090" +dependencies = [ + "stacker", + "stacksafe-macro", +] + +[[package]] +name = "stacksafe-macro" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "172175341049678163e979d9107ca3508046d4d2a7c6682bee46ac541b17db69" +dependencies = [ + "proc-macro-error2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros 0.26.4", +] + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros 0.27.2", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "sval" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4a2a7d92fa86fcc6222e4c3845f8486cff899d9db32480b26c91a5dbf2e22d" + +[[package]] +name = "sval_buffer" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4324db9ac500c609d659b752edf9c8abbf2233f8afd61a503fd6f88ed625032" +dependencies = [ + "sval", + "sval_ref", + "zerocopy", +] + +[[package]] +name = "sval_dynamic" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4046add0eecf55e680b9e207edf5fc7737b18a1d950db363d97e7f1b2d7c629c" +dependencies = [ + "sval", +] + +[[package]] +name = "sval_fmt" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "911a3486b5984a0a4f25edefcf2c2dba23654c29f63e75493b671d338bf24243" +dependencies = [ + "itoa", + "ryu", + "sval", +] + +[[package]] +name = "sval_json" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da53aae7c737b5b5f1be4bcb0ff20e057bf6b2ee4e9d025560075c5830d09f95" +dependencies = [ + "itoa", + "ryu", + "sval", +] + +[[package]] +name = "sval_nested" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df24df43cbdc4bb8c9f5ed19d0d57dc8f60a1a4259cdce52d597fe774ad3a71f" +dependencies = [ + "sval", + "sval_buffer", + "sval_ref", +] + +[[package]] +name = "sval_ref" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bebc17f0f1fad060e57b778728d41ef87627e9111a6365d7463472cb58fc1b3" +dependencies = [ + "sval", +] + +[[package]] +name = "sval_serde" +version = "2.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f26fe3f6a68b40e6c8d654ea48c00e4316272fddf68c80493714c1b034ae70b" +dependencies = [ + "serde_core", + "sval", + "sval_nested", +] + +[[package]] +name = "svg_fmt" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" + +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa", + "yazi", + "zeno", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + +[[package]] +name = "sysinfo" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "355dbe4f8799b304b05e1b0f05fc59b2a18d36645cf169607da45bde2f69a1be" +dependencies = [ + "core-foundation-sys", + "libc", + "memchr", + "ntapi", + "rayon", + "windows 0.57.0", +] + +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "taffy" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13e5d13f79d558b5d353a98072ca8ca0e99da429467804de959aa8c83c9a004" +dependencies = [ + "arrayvec", + "grid", + "serde", + "slotmap", +] + +[[package]] +name = "take-until" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bdb6fa0dfa67b38c1e66b7041ba9dcf23b99d8121907cd31c807a332f7a0bbb" + +[[package]] +name = "tao-core-video-sys" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271450eb289cb4d8d0720c6ce70c72c8c858c93dd61fc625881616752e6b98f6" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "libc", + "objc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand 2.5.0", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-socks" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7e2948f60dbe26b35f2c7fb74ac2854c1fddded0fe9d7548fcc674a246f7615" +dependencies = [ + "either", + "futures-util", + "thiserror 1.0.69", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "1.1.4+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aace63f4bbcdfc2c965b059de67119c89c4017a70d633be6c104910f67056f5" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.4", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" + +[[package]] +name = "ttf-parser" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + +[[package]] +name = "unicode-ccc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656" + +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "unicode-script" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "fontdb 0.23.0", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "rustybuzz 0.20.1", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "value-bag" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "068e763e8279de7ab94b6afebded2cb701678af094feb1c12ccb061b4783c1be" +dependencies = [ + "value-bag-serde1", + "value-bag-sval2", +] + +[[package]] +name = "value-bag-serde1" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417d6197dd0ee696783d6be4276ac6ea74b985e00024c85ccfb37aff4f2bed82" +dependencies = [ + "erased-serde", + "serde_core", + "serde_fmt", +] + +[[package]] +name = "value-bag-sval2" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61f7251ecde2c9ed431bbe0659853e7991753447447bbf1ae59d8b31c578d4e" +dependencies = [ + "sval", + "sval_buffer", + "sval_dynamic", + "sval_fmt", + "sval_json", + "sval_ref", + "sval_serde", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wayland-backend" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "016ccf01d1c58b6f8999612813e17c9b2390f7d70671428869913310f83f54b8" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.4", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.1", + "rustix 1.1.4", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.4", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.31.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23803551115ff9ea9bce586860c5c5a971e360825a0309264102a9495a5ff479" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols 0.31.2", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-capture" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a4df73e95feddb9ec1a7e9c2ca6323b8c97d5eeeff78d28f1eccdf19c882b24" +dependencies = [ + "parking_lot", + "rayon", + "thiserror 2.0.20", + "windows 0.61.3", + "windows-future", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement 0.57.0", + "windows-interface 0.57.0", + "windows-result 0.1.2", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-registry" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3" +dependencies = [ + "windows-result 0.3.4", + "windows-strings 0.3.1", + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-registry" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +dependencies = [ + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "wio" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" +dependencies = [ + "winapi", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-clipboard" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "662d74b3d77e396b8e5beb00b9cad6a9eccf40b2ef68cc858784b14c41d535a3" +dependencies = [ + "libc", + "x11rb", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "rustix 1.1.4", + "x11rb-protocol", + "xcursor", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc" +dependencies = [ + "libc", +] + +[[package]] +name = "xcb" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4c580d8205abb0a5cf4eb7e927bd664e425b6c3263f9c5310583da96970cf6" +dependencies = [ + "bitflags 1.3.2", + "libc", + "quick-xml 0.30.0", + "x11", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xim-ctext" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac61a7062c40f3c37b6e82eeeef835d5cc7824b632a72784a89b3963c33284c" +dependencies = [ + "encoding_rs", +] + +[[package]] +name = "xim-parser" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dcee45f89572d5a65180af3a84e7ddb24f5ea690a6d3aa9de231281544dd7b7" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "xkbcommon" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" +dependencies = [ + "as-raw-xcb-connection", + "libc", + "memmap2", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yazi" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe18fb60dc696039e738717b76eaea21e7a4489bbb1885020b43c94236d7e98a" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener 5.4.2", + "futures-core", + "futures-lite 2.6.1", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.4", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe96480bed92df2b442a1a30df364e12d08eed03aeb061f2b8dc6afb2be91119" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +dependencies = [ + "serde", + "winnow 1.0.4", + "zvariant", +] + +[[package]] +name = "zed-async-tar" +version = "0.5.0-zed" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cf4b5f655e29700e473cb1acd914ab112b37b62f96f7e642d5fc6a0c02eb881" +dependencies = [ + "async-std", + "filetime", + "libc", + "pin-project", + "redox_syscall 0.2.16", + "xattr", +] + +[[package]] +name = "zed-font-kit" +version = "0.14.1-zed" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3898e450f36f852edda72e3f985c34426042c4951790b23b107f93394f9bff5" +dependencies = [ + "bitflags 2.13.1", + "byteorder", + "core-foundation 0.10.0", + "core-graphics 0.24.0", + "core-text", + "dirs 5.0.1", + "dwrote", + "float-ord", + "freetype-sys", + "lazy_static", + "libc", + "log", + "pathfinder_geometry", + "pathfinder_simd", + "walkdir", + "winapi", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "zed-reqwest" +version = "0.12.15-zed" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac2d05756ff48539950c3282ad7acf3817ad3f08797c205ad1c34a2ce03b9970" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "mime_guess", + "once_cell", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-native-certs", + "rustls-pemfile", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "system-configuration", + "tokio", + "tokio-rustls", + "tokio-socks", + "tokio-util", + "tower", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "windows-registry 0.4.0", +] + +[[package]] +name = "zed-scap" +version = "0.0.8-zed" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b338d705ae33a43ca00287c11129303a7a0aa57b101b72a1c08c863f698ac8" +dependencies = [ + "anyhow", + "cocoa 0.25.0", + "core-graphics-helmer-fork", + "log", + "objc", + "rand 0.8.7", + "screencapturekit", + "screencapturekit-sys", + "sysinfo", + "tao-core-video-sys", + "windows 0.61.3", + "windows-capture", + "x11", + "xcb", +] + +[[package]] +name = "zed-xim" +version = "0.4.0-zed" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0b46ed118eba34d9ba53d94ddc0b665e0e06a2cf874cfa2dd5dec278148642" +dependencies = [ + "ahash", + "hashbrown 0.14.5", + "log", + "x11rb", + "xim-ctext", + "xim-parser", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee2a0bcd2a907786a456fff45aaaaf54c9ba5f50b71ae9ec1a4edd200c94911" +dependencies = [ + "endi", + "enumflags2", + "serde", + "url", + "winnow 1.0.4", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a708216a18780796770bfe3f4739c7c83a3e8f789b755534bbbc06e4e23e12" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "winnow 1.0.4", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e5cd5b2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,18 @@ +[workspace] +resolver = "3" +members = ["crates/engine", "crates/engine-hw", "crates/app"] +# Vendored third-party (see [patch.crates-io]); not ours to build or test. +exclude = ["vendor/cros-libva", "vendor/cros-codecs"] + +[workspace.package] +version = "0.1.0" +edition = "2024" + +# Two upstream crates vendored verbatim except for one clearly marked fix each, +# both blockers on this machine and both still unfixed upstream as of 0.0.6/0.0.13: +# cros-libva - fails to build against libva >= 1.23 headers +# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses +# Drop `vendor/` entirely once released versions handle both. +[patch.crates-io] +cros-libva = { path = "vendor/cros-libva" } +cros-codecs = { path = "vendor/cros-codecs" } diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml new file mode 100644 index 0000000..4449c3d --- /dev/null +++ b/crates/app/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "app" +version.workspace = true +edition.workspace = true + +[[bin]] +name = "app" +path = "src/main.rs" + +[dependencies] +engine = { path = "../engine" } +gpui = "0.2.2" +image = "0.25" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs new file mode 100644 index 0000000..ab27aec --- /dev/null +++ b/crates/app/src/main.rs @@ -0,0 +1,102 @@ +use std::sync::Arc; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use engine::{DecodeSession, Frame}; +use gpui::{ + App, Application, Bounds, Context, RenderImage, TitlebarOptions, Window, WindowBounds, + WindowOptions, div, img, prelude::*, px, rgb, size, +}; + +struct Player { + rx: Receiver, + image: Option>, + finished: bool, +} + +impl Player { + /// Takes at most one frame per rendered frame; the decoder's channel is + /// bounded so it simply waits for us. + fn pump(&mut self, window: &mut Window) { + match self.rx.try_recv() { + Ok(frame) => { + let buf = + image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra) + .expect("frame buffer sized width*height*4"); + let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); + if let Some(old) = self.image.replace(next) { + // Every RenderImage gets a fresh id and its own atlas tile: + // without this the sprite atlas grows for the whole video. + let _ = window.drop_image(old); + } + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => self.finished = true, + } + } +} + +impl Render for Player { + fn render(&mut self, window: &mut Window, _cx: &mut Context) -> impl IntoElement { + self.pump(window); + if !self.finished { + window.request_animation_frame(); + } + + div() + .size_full() + .bg(rgb(0x101010)) + .flex() + .justify_center() + .items_center() + .children( + self.image + .clone() + .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)), + ) + } +} + +fn main() { + let Some(path) = std::env::args().nth(1) else { + eprintln!("usage: app "); + std::process::exit(2); + }; + let (meta, rx) = match DecodeSession::open(&path) { + Ok(v) => v, + Err(e) => { + eprintln!("cannot open {path}: {e}"); + std::process::exit(1); + } + }; + println!( + "{path}: {}x{} @ {:.2} fps, {} samples", + meta.width, meta.height, meta.frame_rate, meta.frame_count + ); + + Application::new().run(move |cx: &mut App| { + let bounds = Bounds::centered( + None, + size(px(meta.width as f32), px(meta.height as f32)), + cx, + ); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + titlebar: Some(TitlebarOptions { + title: Some("video_editor".into()), + ..Default::default() + }), + ..Default::default() + }, + |_, cx| { + cx.new(|_| Player { + rx, + image: None, + finished: false, + }) + }, + ) + .unwrap(); + cx.activate(true); + }); +} diff --git a/crates/engine-hw/Cargo.toml b/crates/engine-hw/Cargo.toml new file mode 100644 index 0000000..2c680d4 --- /dev/null +++ b/crates/engine-hw/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "engine-hw" +version.workspace = true +edition.workspace = true + +# cdylib only: this is the one artifact allowed to link libva/gbm/drm. The app +# dlopens it and keeps working when it is missing. +[lib] +name = "engine_hw" +crate-type = ["cdylib"] + +[dependencies] +engine = { path = "../engine" } +cros-codecs = { version = "0.0.6", features = ["vaapi"] } +# Same version cros-codecs already pulls in; we allocate output frames ourselves. +gbm = { version = "0.15", default-features = false, features = ["drm-support"] } diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs new file mode 100644 index 0000000..da84896 --- /dev/null +++ b/crates/engine-hw/src/lib.rs @@ -0,0 +1,374 @@ +//! VA-API H.264 decode, shipped as a `dlopen`-able plugin so the main binary +//! never gets a DT_NEEDED on libva/gbm/drm. Every entry point is `extern "C"`, +//! catches unwinds and reports failure as a null pointer or a negative code: +//! the caller's contract is "any failure means use the software decoder". +//! +//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with +//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path +//! is running the decoder in a child process instead of in-process. + +use std::collections::VecDeque; +use std::ffi::{CStr, c_char, c_void}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use cros_codecs::backend::vaapi::decoder::VaapiBackend; +use cros_codecs::decoder::stateless::h264::H264; +use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder}; +use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; +use cros_codecs::image_processing::nv12_to_i420; +use cros_codecs::libva::{Display, Image, VA_FOURCC_NV12, VAImageFormat}; +use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame}; +use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame; +use cros_codecs::video_frame::{UV_PLANE, Y_PLANE}; +use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; +use gbm::{BufferObjectFlags, Format as GbmFormat}; + +use engine::demux::Demuxer; +use engine::hw::{VhFrame, VhMeta}; + +type PooledFrame = PooledVideoFrame; +type Decoder = StatelessDecoder>; +type Handle = ::Handle; + +/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking +/// mode should always either hand back an event or accept input; this only +/// exists so a misbehaving driver returns an error instead of hanging the app. +const STALL_LIMIT: u32 = 10_000; + +struct Session { + decoder: Decoder, + /// NV12 descriptor for `vaGetImage`, queried once at open. + nv12_format: VAImageFormat, + pool: FramePool, + demuxer: Demuxer, + meta: VhMeta, + ready: VecDeque, + /// Remaining bytes of the access unit currently being fed, if any. + pending: Vec, + timestamp: u64, + flushed: bool, + /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame, + /// which is exactly why the pointers are only valid until the next call. + out: Vec, + luma: usize, + chroma: usize, +} + +/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on +/// radeonsi: every flag/modifier combination returns NULL), so we allocate one +/// linear single-plane R8 buffer big enough for luma + chroma and describe the +/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object +/// with two planes at known offsets, which is exactly what the descriptor in +/// `GenericDmaVideoFrame` emits. +fn alloc_nv12( + gbm: &gbm::Device, + coded: Resolution, +) -> Result { + let rows = coded.height + coded.height.div_ceil(2); + let bo = gbm + .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR) + .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?; + let pitch = bo.stride().map_err(|e| e.to_string())? as usize; + let fd = bo.fd().map_err(|e| e.to_string())?; + GenericDmaVideoFrame::new( + vec![std::fs::File::from(fd)], + FrameLayout { + format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */), + size: coded, + planes: vec![ + PlaneLayout { + buffer_index: 0, + offset: 0, + stride: pitch, + }, + PlaneLayout { + buffer_index: 0, + offset: pitch * coded.height as usize, + stride: pitch, + }, + ], + }, + ) +} + +/// First render node that gives us both a VA display and a GBM device. Which +/// node is the right one is a per-machine question, so we probe rather than +/// hardcode renderD128. +fn open_devices() -> Option<(Rc, gbm::Device)> { + let mut nodes: Vec = std::fs::read_dir("/dev/dri") + .ok()? + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("renderD")) + }) + .collect(); + nodes.sort(); + nodes.into_iter().find_map(|node| { + let display = Display::open_drm_display(&node).ok()?; + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&node) + .ok()?; + let gbm = gbm::Device::new(file).ok()?; + Some((display, gbm)) + }) +} + +impl Session { + fn open(path: &Path) -> Option { + let (meta, demuxer) = Demuxer::open(path).ok()?; + let (display, gbm) = open_devices()?; + let nv12_format = display + .query_image_formats() + .ok()? + .into_iter() + .find(|f| f.fourcc == VA_FOURCC_NV12)?; + let decoder = Decoder::new_vaapi(display, BlockingMode::Blocking).ok()?; + let pool = FramePool::new(move |info: &StreamInfo| { + alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed") + }); + Some(Self { + decoder, + nv12_format, + pool, + demuxer, + meta: VhMeta { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + frame_count: meta.frame_count, + }, + ready: VecDeque::new(), + pending: Vec::new(), + timestamp: 0, + flushed: false, + out: Vec::new(), + luma: 0, + chroma: 0, + }) + } + + /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. + fn pump(&mut self) -> Result { + let mut stalls = 0u32; + loop { + // Stop draining as soon as we have a picture: every handle we hold + // keeps a pool buffer out of circulation. + while self.ready.is_empty() { + match self.decoder.next_event() { + Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), + Some(DecoderEvent::FormatChanged) => { + let info = self + .decoder + .stream_info() + .ok_or("format changed without stream info")? + .clone(); + self.pool.resize(&info); + } + None => break, + } + } + if let Some(handle) = self.ready.pop_front() { + self.emit(handle); + return Ok(true); + } + if self.flushed { + return Ok(false); + } + + if self.pending.is_empty() { + match self.demuxer.next_access_unit() { + Ok(Some(au)) => self.pending = au, + Ok(None) => { + self.decoder.flush().map_err(|e| e.to_string())?; + self.flushed = true; + continue; + } + Err(e) => return Err(e.to_string()), + } + } + + let Self { + decoder, + pool, + pending, + timestamp, + .. + } = self; + match decoder.decode(*timestamp, pending, &mut || pool.alloc()) { + Ok(0) => return Err("decoder consumed no input".into()), + Ok(n) => { + pending.drain(..n.min(pending.len())); + if pending.is_empty() { + *timestamp += 1; + } + stalls = 0; + } + // Both mean "handle pending events, then resubmit the same data". + Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => { + stalls += 1; + if stalls > STALL_LIMIT { + return Err("decoder stalled waiting for output buffers".into()); + } + } + Err(e) => return Err(e.to_string()), + } + } + } + + /// Copies a decoded NV12 surface into `self.out` as packed I420. + fn emit(&mut self, handle: Handle) { + let res = handle.display_resolution(); + let (w, h) = (res.width as usize, res.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if self.luma != w * h || self.chroma != cw * ch { + self.luma = w * h; + self.chroma = cw * ch; + self.out = vec![0u8; self.luma + 2 * self.chroma]; + } + self.meta.width = res.width; + self.meta.height = res.height; + + // Read back with vaGetImage rather than mapping our own DMA-BUF: on a + // discrete GPU that buffer lives in VRAM and a CPU read of it runs at + // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The + // driver copies into host-visible memory for us instead. + // Cheap no-op in blocking mode, but pixels must never be read early. + let _ = DecodedHandle::sync(&handle); + let borrowed = handle.borrow(); + let size = (w as u32, h as u32); + let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size) + .expect("vaGetImage failed"); + let va = *image.image(); + let data: &[u8] = image.as_ref(); + + let (dst_y, rest) = self.out.split_at_mut(self.luma); + let (dst_u, dst_v) = rest.split_at_mut(self.chroma); + nv12_to_i420( + &data[va.offsets[Y_PLANE] as usize..], + va.pitches[Y_PLANE] as usize, + dst_y, + w, + &data[va.offsets[UV_PLANE] as usize..], + va.pitches[UV_PLANE] as usize, + dst_u, + cw, + dst_v, + cw, + w, + h, + ); + } + + fn fill(&self, out: &mut VhFrame) { + let w = self.meta.width as usize; + let cw = w.div_ceil(2); + out.y = self.out.as_ptr(); + // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`. + unsafe { + out.u = self.out.as_ptr().add(self.luma); + out.v = self.out.as_ptr().add(self.luma + self.chroma); + } + out.y_stride = w; + out.u_stride = cw; + out.v_stride = cw; + out.width = self.meta.width; + out.height = self.meta.height; + } +} + +/// Opens `path` for hardware decode. Returns null on any failure at all: no +/// libva runtime, no render node, unsupported profile, unreadable file. +/// +/// # Safety +/// `path` must be a valid NUL-terminated C string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { + catch_unwind(AssertUnwindSafe(|| { + if path.is_null() { + return std::ptr::null_mut(); + } + // SAFETY: caller-guaranteed NUL-terminated string, read before return. + let path = unsafe { CStr::from_ptr(path) }; + let Ok(path) = path.to_str() else { + return std::ptr::null_mut(); + }; + match Session::open(Path::new(path)) { + Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, + None => std::ptr::null_mut(), + } + })) + .unwrap_or(std::ptr::null_mut()) +} + +/// Fills `out` with stream metadata. 0 on success, negative on failure. +/// +/// # Safety +/// `session` must come from [`vh_open`] and `out` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || out.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and writable destination. + unsafe { + let session = &*(session as *const Session); + (*out).width = session.meta.width; + (*out).height = session.meta.height; + (*out).frame_rate = session.meta.frame_rate; + (*out).frame_count = session.meta.frame_count; + } + 0 + })) + .unwrap_or(-1) +} + +/// 1 when `out` holds the next picture in display order, 0 at clean end of +/// stream, negative on error. Plane pointers stay valid until the next call. +/// +/// # Safety +/// `session` must come from [`vh_open`] and `out` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || out.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and writable destination. + let session = unsafe { &mut *(session as *mut Session) }; + match session.pump() { + Ok(true) => { + // SAFETY: `out` is non-null and writable per the contract. + session.fill(unsafe { &mut *out }); + 1 + } + Ok(false) => 0, + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + +/// Releases a session. Safe to call with null. +/// +/// # Safety +/// `session` must come from [`vh_open`] and must not be used afterwards. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_close(session: *mut c_void) { + let _ = catch_unwind(AssertUnwindSafe(|| { + if !session.is_null() { + // SAFETY: pointer came from `Box::into_raw` in `vh_open`. + drop(unsafe { Box::from_raw(session as *mut Session) }); + } + })); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml new file mode 100644 index 0000000..b11a936 --- /dev/null +++ b/crates/engine/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "engine" +version.workspace = true +edition.workspace = true + +# No UI dependency here, ever: the engine must stay reusable across front-ends. +[dependencies] +libloading = "0.8" +mp4 = "0.14" +rusty_h264 = { version = "0.8", default-features = false } diff --git a/crates/engine/examples/dump_frame.rs b/crates/engine/examples/dump_frame.rs new file mode 100644 index 0000000..b41d677 --- /dev/null +++ b/crates/engine/examples/dump_frame.rs @@ -0,0 +1,34 @@ +//! Dump decoded frames as PPM for visual inspection. +//! Usage: cargo run -p engine --release --example dump_frame -- + +use std::env; +use std::fs::File; +use std::io::{BufWriter, Write}; + +fn main() -> engine::Result<()> { + let mut args = env::args().skip(1); + let path = args + .next() + .ok_or("usage: dump_frame ")?; + let target: u32 = args.next().ok_or("missing frame index")?.parse()?; + let out = args.next().ok_or("missing output path")?; + + let (meta, rx) = engine::DecodeSession::open(&path)?; + eprintln!( + "{}x{} @ {:.2} fps", + meta.width, meta.height, meta.frame_rate + ); + + for frame in rx { + if frame.index == target { + let mut w = BufWriter::new(File::create(&out)?); + writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?; + for px in frame.bgra.chunks_exact(4) { + w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB + } + eprintln!("wrote frame {target} to {out}"); + return Ok(()); + } + } + Err(format!("stream ended before frame {target}").into()) +} diff --git a/crates/engine/src/convert.rs b/crates/engine/src/convert.rs new file mode 100644 index 0000000..739120c --- /dev/null +++ b/crates/engine/src/convert.rs @@ -0,0 +1,56 @@ +//! I420 -> BGRA8 (straight alpha), BT.601 limited range. + +/// Converts a planar I420 frame (stride == width, chroma at half resolution) +/// into tightly packed BGRA8. Returns `width * height * 4` bytes. +pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -> Vec { + let cw = width.div_ceil(2); + let mut out = vec![0u8; width * height * 4]; + + for row in 0..height { + let y_row = row * width; + let c_row = (row / 2) * cw; + for col in 0..width { + let c = y[y_row + col] as i32 - 16; + let ci = c_row + col / 2; + let d = u[ci] as i32 - 128; + let e = v[ci] as i32 - 128; + + let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8; + let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8; + let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8; + + let o = (y_row + col) * 4; + out[o] = b; + out[o + 1] = g; + out[o + 2] = r; + out[o + 3] = 255; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_colors() { + // 2x2 blocks so each shares one chroma sample. + // Black (limited range Y=16), white (Y=235), and a saturated red. + let cases: [([u8; 3], [u8; 3]); 3] = [ + ([16, 128, 128], [0, 0, 0]), + ([235, 128, 128], [255, 255, 255]), + ([82, 90, 240], [255, 0, 0]), // BT.601 red primary -> R=255,G~0,B~0 + ]; + for ([yv, uv, vv], [r, g, b]) in cases { + let out = i420_to_bgra(&[yv; 4], &[uv], &[vv], 2, 2); + assert_eq!(out.len(), 2 * 2 * 4); + for px in out.chunks_exact(4) { + assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b); + assert!(px[1].abs_diff(g) <= 2, "G {} vs {}", px[1], g); + assert!(px[2].abs_diff(r) <= 2, "R {} vs {}", px[2], r); + assert_eq!(px[3], 255); + } + } + } +} diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs new file mode 100644 index 0000000..45d4b55 --- /dev/null +++ b/crates/engine/src/decode.rs @@ -0,0 +1,130 @@ +//! Background decode worker. Frames leave over a bounded channel so the caller's +//! thread (the UI thread) never blocks on decode and memory stays capped. + +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; +use std::thread; + +use rusty_h264::Decoder; + +use crate::convert::i420_to_bgra; +use crate::demux::{Demuxer, VideoMeta}; +use crate::hw::HwSession; + +/// One decoded picture, ready to hand to a renderer. +pub struct Frame { + /// Position in decode order, starting at 0. + pub index: u32, + pub width: u32, + pub height: u32, + /// BGRA8, straight alpha, tightly packed. + pub bgra: Vec, +} + +pub struct DecodeSession; + +impl DecodeSession { + /// Opens `path`, returning stream metadata immediately and a receiver that + /// yields frames as the worker decodes them. The worker stops when the + /// receiver is dropped, at end of stream, or on the first decode error. + pub fn open(path: impl AsRef) -> crate::Result<(VideoMeta, Receiver)> { + let path = path.as_ref().to_path_buf(); + let (meta, demuxer) = Demuxer::open(&path)?; + // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the + // decoder run ahead of the display without limit. + let (tx, rx) = sync_channel(2); + thread::Builder::new() + .name("decode".into()) + .spawn(move || { + // The plugin has to be opened on the thread that uses it: its + // VA-API state is not `Send`-safe across a later hand-off. + if let Some(hw) = open_hw(&path) { + eprintln!("decode backend: hardware (VA-API plugin)"); + if run_hw(hw, &tx) { + return; + } + // A driver that opens but cannot decode a single frame is + // still a fallback case, not a dead session. + eprintln!("hardware decode failed before any frame, falling back to software"); + } + eprintln!("decode backend: software (rusty_h264)"); + run(demuxer, tx) + })?; + Ok((meta, rx)) + } +} + +/// `None` when the software path must be used: forced by `VE_SW=1`, or the +/// plugin is absent/broken/unable to open this particular file. +fn open_hw(path: &PathBuf) -> Option { + if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { + return None; + } + HwSession::open(path) +} + +/// Returns whether the session was handled; `false` only when hardware decode +/// failed without emitting a single frame, so software can still take over. +fn run_hw(mut hw: HwSession, tx: &SyncSender) -> bool { + let mut index = 0u32; + loop { + match hw.next_frame() { + Ok(Some((y, u, v, width, height))) => { + let frame = Frame { + index, + width, + height, + bgra: i420_to_bgra(y, u, v, width as usize, height as usize), + }; + index += 1; + if tx.send(frame).is_err() { + return true; // consumer went away + } + } + Ok(None) => return true, + Err(e) => { + if index == 0 { + return false; + } + eprintln!("hardware decode error at frame {index}: {e}"); + return true; + } + } + } +} + +fn run(mut demuxer: Demuxer, tx: SyncSender) { + let mut decoder = Decoder::new(); + let mut index = 0u32; + + // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); + // reordering streams need POC-sorted output before display. + loop { + let au = match demuxer.next_access_unit() { + Ok(Some(au)) => au, + Ok(None) => break, + Err(e) => { + eprintln!("demux error: {e}"); + break; + } + }; + let yuv = match decoder.decode(&au) { + Ok(Some(yuv)) => yuv, + Ok(None) => continue, + Err(e) => { + eprintln!("decode error at access unit {index}: {e}"); + break; + } + }; + let frame = Frame { + index, + width: yuv.width as u32, + height: yuv.height as u32, + bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height), + }; + index += 1; + if tx.send(frame).is_err() { + break; // consumer went away + } + } +} diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs new file mode 100644 index 0000000..d1d2c5f --- /dev/null +++ b/crates/engine/src/demux.rs @@ -0,0 +1,132 @@ +//! MP4 demux: pulls the H.264 track out as Annex-B access units. + +use std::fs::File; +use std::io::BufReader; +use std::path::Path; + +use mp4::{MediaType, Mp4Reader}; + +const START_CODE: [u8; 4] = [0, 0, 0, 1]; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct VideoMeta { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub frame_count: u32, +} + +pub struct Demuxer { + reader: Mp4Reader>, + track_id: u32, + sample_count: u32, + /// Annex-B SPS+PPS, re-injected ahead of every sync sample. + parameter_sets: Vec, + next_sample: u32, +} + +impl Demuxer { + pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> { + let file = File::open(path)?; + let size = file.metadata()?.len(); + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; + + let track = reader + .tracks() + .values() + .find(|t| matches!(t.media_type(), Ok(MediaType::H264))) + .ok_or("no H.264 video track in file")?; + + let track_id = track.track_id(); + let meta = VideoMeta { + width: track.width() as u32, + height: track.height() as u32, + frame_rate: track.frame_rate(), + frame_count: 0, + }; + let mut parameter_sets = Vec::new(); + parameter_sets.extend_from_slice(&START_CODE); + parameter_sets.extend_from_slice(track.sequence_parameter_set()?); + parameter_sets.extend_from_slice(&START_CODE); + parameter_sets.extend_from_slice(track.picture_parameter_set()?); + + let sample_count = reader.sample_count(track_id)?; + Ok(( + VideoMeta { + frame_count: sample_count, + ..meta + }, + Self { + reader, + track_id, + sample_count, + parameter_sets, + next_sample: 1, // sample ids are 1-based + }, + )) + } + + /// Next access unit in decode order, Annex-B framed. `None` at end of track. + pub fn next_access_unit(&mut self) -> crate::Result>> { + if self.next_sample > self.sample_count { + return Ok(None); + } + let sample = self.reader.read_sample(self.track_id, self.next_sample)?; + self.next_sample += 1; + let Some(sample) = sample else { + return Ok(None); + }; + + let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); + if sample.is_sync { + au.extend_from_slice(&self.parameter_sets); + } + append_annex_b(&sample.bytes, &mut au)?; + Ok(Some(au)) + } +} + +/// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which +/// mp4 0.14 does not expose; a wrong guess misparses immediately, hence the check. +/// +/// ponytail: hardcoded 4-byte NAL length prefix (lengthSizeMinusOne == 3). 1/2-byte +/// prefixes exist in the wild; upgrade path is parsing the avcC box from +/// `track.trak` instead of assuming. +fn append_annex_b(mut src: &[u8], out: &mut Vec) -> crate::Result<()> { + while !src.is_empty() { + if src.len() < 4 { + return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into()); + } + let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize; + if len == 0 || len > src.len() - 4 { + return Err(format!( + "bad NAL length {len} with {} bytes remaining (not a 4-byte-prefixed avcC sample?)", + src.len() - 4 + ) + .into()); + } + out.extend_from_slice(&START_CODE); + out.extend_from_slice(&src[4..4 + len]); + src = &src[4 + len..]; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn splits_two_nals() { + let mut out = Vec::new(); + append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], &mut out).unwrap(); + assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]); + } + + #[test] + fn rejects_misparse() { + assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); + assert!(append_annex_b(&[0, 0, 0], &mut Vec::new()).is_err()); + assert!(append_annex_b(&[0, 0, 0, 0], &mut Vec::new()).is_err()); + } +} diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs new file mode 100644 index 0000000..7a737f0 --- /dev/null +++ b/crates/engine/src/hw.rs @@ -0,0 +1,180 @@ +//! Runtime-optional hardware decode plugin (`libengine_hw.so`). +//! +//! The plugin links libva/gbm/drm; this crate and the app binary must not, so +//! the only coupling is this C ABI plus a `dlopen`. Anything that goes wrong -- +//! plugin missing, no VA-API runtime, no render node, unsupported stream -- +//! leaves us with `None` and the caller falls back to the software decoder. + +use std::ffi::{CString, c_char, c_void}; +use std::path::Path; +use std::sync::OnceLock; + +use libloading::Library; + +const LIB_NAME: &str = "libengine_hw.so"; + +/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]. +#[repr(C)] +#[derive(Default)] +pub struct VhMeta { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub frame_count: u32, +} + +/// One decoded picture as planar I420. Pointers belong to the plugin and stay +/// valid only until the next `vh_next_frame`/`vh_close` on the same session. +#[repr(C)] +pub struct VhFrame { + pub y: *const u8, + pub u: *const u8, + pub v: *const u8, + pub y_stride: usize, + pub u_stride: usize, + pub v_stride: usize, + pub width: u32, + pub height: u32, +} + +impl Default for VhFrame { + fn default() -> Self { + Self { + y: std::ptr::null(), + u: std::ptr::null(), + v: std::ptr::null(), + y_stride: 0, + u_stride: 0, + v_stride: 0, + width: 0, + height: 0, + } + } +} + +struct Plugin { + open: unsafe extern "C" fn(*const c_char) -> *mut c_void, + meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, + next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, + close: unsafe extern "C" fn(*mut c_void), + // Never dropped (lives in a static), so the fn pointers above stay valid. + _lib: Library, +} + +fn plugin() -> Option<&'static Plugin> { + static PLUGIN: OnceLock> = OnceLock::new(); + PLUGIN.get_or_init(load).as_ref() +} + +fn load() -> Option { + // Next to the executable first (cargo puts both in target/), then + // whatever the dynamic linker's search path turns up. + let beside_exe = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME))); + let candidates = beside_exe + .as_deref() + .into_iter() + .chain(std::iter::once(Path::new(LIB_NAME))); + + for candidate in candidates { + // SAFETY: loading a shared object runs its initialisers; we only ever + // name our own plugin, and every symbol below is type-checked against + // the definitions this crate shares with it. + let lib = match unsafe { Library::new(candidate) } { + Ok(lib) => lib, + Err(_) => continue, + }; + let plugin = unsafe { + (|| { + Some(Plugin { + open: *lib.get(b"vh_open\0").ok()?, + meta: *lib.get(b"vh_meta\0").ok()?, + next_frame: *lib.get(b"vh_next_frame\0").ok()?, + close: *lib.get(b"vh_close\0").ok()?, + _lib: lib, + }) + })() + }; + if plugin.is_some() { + return plugin; + } + } + None +} + +/// An open hardware decode session. Dropping it closes the plugin session. +pub struct HwSession { + plugin: &'static Plugin, + handle: *mut c_void, +} + +impl HwSession { + /// Probes the plugin against this very file: success means the driver, + /// the render node and the stream's profile are all usable. + pub fn open(path: &Path) -> Option { + let plugin = plugin()?; + let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?; + // SAFETY: `c_path` is a valid NUL-terminated string alive for the call. + let handle = unsafe { (plugin.open)(c_path.as_ptr()) }; + if handle.is_null() { + return None; + } + Some(Self { plugin, handle }) + } + + pub fn meta(&self) -> Option { + let mut meta = VhMeta::default(); + // SAFETY: `handle` came from `vh_open` and is still open. + if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 { + return None; + } + Some(meta) + } + + /// Next picture in display order as tightly packed I420 `(y, u, v)`. + /// `Ok(None)` is clean end of stream. + pub fn next_frame(&mut self) -> crate::Result> { + let mut frame = VhFrame::default(); + // SAFETY: `handle` is live; the plugin fills `frame` with pointers that + // stay valid until the next call, which `&mut self` prevents overlapping. + match unsafe { (self.plugin.next_frame)(self.handle, &mut frame) } { + 0 => return Ok(None), + 1 => {} + code => return Err(format!("hardware decode failed (code {code})").into()), + } + let (w, h) = (frame.width as usize, frame.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if frame.y.is_null() + || frame.u.is_null() + || frame.v.is_null() + || frame.y_stride != w + || frame.u_stride != cw + || frame.v_stride != cw + { + return Err("hardware plugin returned a non-packed I420 frame".into()); + } + // SAFETY: plane pointers are non-null and the strides just checked above + // pin each plane's length; the borrow ends before the next call. + unsafe { + Ok(Some(( + std::slice::from_raw_parts(frame.y, w * h), + std::slice::from_raw_parts(frame.u, cw * ch), + std::slice::from_raw_parts(frame.v, cw * ch), + frame.width, + frame.height, + ))) + } + } +} + +impl Drop for HwSession { + fn drop(&mut self) { + // SAFETY: `handle` came from `vh_open` and is closed exactly once. + unsafe { (self.plugin.close)(self.handle) } + } +} + +// The plugin session is used from one thread at a time (the decode worker) and +// never shared; VA-API state inside it is not `Sync`. +unsafe impl Send for HwSession {} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs new file mode 100644 index 0000000..7469199 --- /dev/null +++ b/crates/engine/src/lib.rs @@ -0,0 +1,14 @@ +//! Video engine: demux -> decode -> pixel convert. No UI dependencies. + +pub mod convert; +pub mod decode; +pub mod demux; +pub mod hw; + +pub use decode::{DecodeSession, Frame}; +pub use demux::VideoMeta; + +/// Boxed error; the engine has few failure modes and every one of them is fatal +/// to the session, so a message is all a caller can act on. +pub type Error = Box; +pub type Result = std::result::Result; diff --git a/crates/engine/tests/decode_baseline.rs b/crates/engine/tests/decode_baseline.rs new file mode 100644 index 0000000..c748ca4 --- /dev/null +++ b/crates/engine/tests/decode_baseline.rs @@ -0,0 +1,39 @@ +use std::path::PathBuf; +use std::time::Instant; + +use engine::DecodeSession; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +#[test] +fn decodes_baseline_mp4() { + let path = asset("test_baseline.mp4"); + let (meta, rx) = DecodeSession::open(&path).expect("open"); + assert_eq!((meta.width, meta.height), (1280, 720), "container dims"); + assert!(meta.frame_count > 0); + + // Capped: pure-Rust 720p decode is slow in a debug test build. + // Set DECODE_FRAMES to drain the whole stream (checks clean EOF). + let want: usize = std::env::var("DECODE_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10); + let start = Instant::now(); + let mut frames = 0usize; + for frame in rx.iter().take(want) { + assert_eq!((frame.width, frame.height), (1280, 720)); + assert_eq!(frame.bgra.len(), 1280 * 720 * 4); + assert_eq!(frame.index as usize, frames); + frames += 1; + } + assert!(frames > 0, "no frames decoded"); + eprintln!( + "{frames} frames in {:?} ({:?}/frame)", + start.elapsed(), + start.elapsed() / frames as u32 + ); +} diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs new file mode 100644 index 0000000..1a3d697 --- /dev/null +++ b/crates/engine/tests/hw_decode.rs @@ -0,0 +1,110 @@ +//! Hardware path checks. These need a built `libengine_hw.so` plus a working +//! VA-API driver, so they are `#[ignore]`d by default. Run them with: +//! +//! ```text +//! cargo build --workspace --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test hw_decode -- --ignored --nocapture --test-threads=1 +//! ``` +//! +//! The comparison test pins [`DecodeSession`] to the software decoder itself +//! (it sets `VE_SW=1` in-process, hence the required `--test-threads=1`); the +//! hardware side goes through [`HwSession`] directly and can never silently be +//! a fallback. + +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use engine::DecodeSession; +use engine::convert::i420_to_bgra; +use engine::hw::HwSession; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn open_hw(path: &Path) -> HwSession { + HwSession::open(path).expect("no hardware decode plugin/driver available") +} + +/// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA). +fn decode_all_hw(name: &str) -> (usize, Vec) { + let path = asset(name); + let mut hw = open_hw(&path); + let meta = hw.meta().expect("meta"); + assert_eq!( + (meta.width, meta.height), + (1280, 720), + "{name} container dims" + ); + + let mut count = 0usize; + let mut frame_30 = Vec::new(); + let start = Instant::now(); + while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") { + assert_eq!((w, h), (1280, 720), "{name} frame {count} dims"); + if count == 30 { + frame_30 = i420_to_bgra(y, u, v, w as usize, h as usize); + } + count += 1; + } + eprintln!( + "{name}: {count} hardware frames in {:?} ({:?}/frame)", + start.elapsed(), + start.elapsed() / count.max(1) as u32 + ); + (count, frame_30) +} + +/// The plugin must refuse junk by returning null, never by unwinding into us. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn rejects_unopenable_files() { + assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none()); + assert!(HwSession::open(Path::new("/etc/hostname")).is_none(), "not an mp4"); +} + +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn hardware_decodes_baseline() { + let (count, _) = decode_all_hw("test_baseline.mp4"); + assert_eq!(count, 150); +} + +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn hardware_decodes_high_profile() { + // B-frames: the plugin emits display order (DPB bumping happens inside + // cros-codecs), so a clean run to EOF is the check we can make headlessly. + let (count, _) = decode_all_hw("test_high.mp4"); + assert_eq!(count, 150); +} + +/// H.264 8-bit decode is bit-exact by conformance, so the two backends must +/// agree. A mismatch means a driver deviation and is reported, not swallowed. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn hardware_matches_software_on_frame_30() { + let (_, hw) = decode_all_hw("test_baseline.mp4"); + + // Pin the comparison side to software ourselves: without this, running the + // suite without VE_SW=1 would compare hardware against hardware and pass + // vacuously. SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + + let start = Instant::now(); + let (_, rx) = DecodeSession::open(asset("test_baseline.mp4")).expect("software open"); + let sw = rx + .into_iter() + .find(|f| f.index == 30) + .expect("software frame 30") + .bgra; + eprintln!("software reached frame 30 in {:?}", start.elapsed()); + + assert_eq!(hw.len(), sw.len(), "frame size"); + let diff = hw.iter().zip(&sw).filter(|(a, b)| a != b).count(); + eprintln!("frame 30 differing bytes: {diff} / {}", hw.len()); + assert_eq!(diff, 0, "hardware and software decode disagree"); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh new file mode 100755 index 0000000..87ca78e --- /dev/null +++ b/scripts/gen_fixtures.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Regenerates the gitignored test fixtures under assets/. +# Needs the ffmpeg CLI (dev tool only — the app itself never uses ffmpeg). +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p assets +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=5 \ + -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_baseline.mp4 +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=5 \ + -c:v libx264 -profile:v high -pix_fmt yuv420p assets/test_high.mp4 +echo "fixtures written to assets/" diff --git a/vendor/cros-codecs/.cargo/config.toml b/vendor/cros-codecs/.cargo/config.toml new file mode 100644 index 0000000..7980ab9 --- /dev/null +++ b/vendor/cros-codecs/.cargo/config.toml @@ -0,0 +1,6 @@ +# When cross compiling outside of the chroot +# with --target aarch64-unknown-linux-gnu the +# linker needs to explicity defined for the +# examples to link. +[target.aarch64-unknown-linux-gnu] +linker = "aarch64-linux-gnu-gcc" diff --git a/vendor/cros-codecs/.cargo_vcs_info.json b/vendor/cros-codecs/.cargo_vcs_info.json new file mode 100644 index 0000000..d997fd7 --- /dev/null +++ b/vendor/cros-codecs/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "7a4211c57ac2e791412f40df2c22fd2cf81104f6" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/vendor/cros-codecs/.clippy.toml b/vendor/cros-codecs/.clippy.toml new file mode 100644 index 0000000..0358cdb --- /dev/null +++ b/vendor/cros-codecs/.clippy.toml @@ -0,0 +1,2 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true diff --git a/vendor/cros-codecs/.gitignore b/vendor/cros-codecs/.gitignore new file mode 100644 index 0000000..3a64a60 --- /dev/null +++ b/vendor/cros-codecs/.gitignore @@ -0,0 +1,2 @@ +/target +.nlsp-settings diff --git a/vendor/cros-codecs/Android.bp b/vendor/cros-codecs/Android.bp new file mode 100644 index 0000000..14b5b68 --- /dev/null +++ b/vendor/cros-codecs/Android.bp @@ -0,0 +1,156 @@ +package { + default_applicable_licenses: ["system_cros-codecs_license"], + // TODO(b/374841646): This is a temporary assignment. + default_team: "trendy_team_arc_next", +} + +license { + name: "system_cros-codecs_license", + visibility: [":__subpackages__"], + license_kinds: ["SPDX-license-identifier-BSD-3-Clause"], + license_text: ["LICENSE"], +} + +rust_defaults { + name: "libcros_codecs_defaults", + crate_name: "cros_codecs", + cargo_env_compat: true, + cargo_pkg_version: "0.0.5", + crate_root: "src/lib.rs", + edition: "2021", + rustlibs: [ + "libanyhow", + "libcrc32fast", + "libbyteorder", + "libthiserror", + "liblog_rust", + "libgbm_rust", + "libdrm_rust", + "libdrm_fourcc", + "libgbm_sys", + "libnix", + "libzerocopy", + ], + aliases: ["cros_libva:libva"], + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], + // TODO(b/382119688): Remove this. + lints: "none", + + product_available: true, + vendor_available: true, +} + +rust_library { + name: "libcros_codecs", + defaults: ["libcros_codecs_defaults"], + enabled: false, + arch: { + x86_64: { + enabled: true, + features: [ + "vaapi", + "backend", + ], + rustlibs: ["libcros_libva"], + }, + arm64: { + enabled: true, + features: [ + "v4l2", + "backend", + ], + rustlibs: ["libv4l2r"], + }, + }, +} + +rust_test_host { + name: "libcros_codecs_test", + defaults: ["libcros_codecs_defaults"], + rustlibs: ["libenv_logger"], +} + +rust_test { + name: "ccdec_test", + srcs: ["test/ccdec_test.rs"], + test_suites: ["general-tests"], + test_config: "test/AndroidTest.xml", + rustlibs: [ + "libargh", + "libcros_codecs", + "libenv_logger", + "liblog_rust", + "libserde_json", + ], + data: [ + ":test_data", + ], + data_bins: ["ccdec"], + // TODO(b/394365384): Group shared dependencies with rust_defaults + enabled: false, + arch: { + x86_64: { + enabled: true, + features: [ + "vaapi", + "backend", + ], + }, + arm64: { + enabled: true, + features: [ + "v4l2", + "backend", + ], + }, + }, +} + +rust_test { + name: "ccdec", + srcs: ["examples/ccdec/main.rs"], + test_suites: ["general-tests"], + rustlibs: [ + "libenv_logger", + "libcros_codecs", + "libargh", + "libserde_json", + ], + // TODO(b/394365384): Group shared dependencies with rust_defaults + enabled: false, + arch: { + x86_64: { + enabled: true, + features: [ + "vaapi", + "backend", + ], + }, + arm64: { + enabled: true, + features: [ + "v4l2", + "backend", + ], + }, + }, + test_harness: false, +} + +filegroup { + name: "test_data", + srcs: [ + "src/codec/av1/test_data/*", + "src/codec/h264/test_data/*", + "src/codec/h265/test_data/*", + "src/codec/vp8/test_data/*", + "src/codec/vp9/test_data/*", + ], + exclude_srcs: [ + "src/codec/**/gen_crcs.sh", + "src/codec/**/README.md", + ], +} diff --git a/vendor/cros-codecs/CONTRIBUTING.md b/vendor/cros-codecs/CONTRIBUTING.md new file mode 100644 index 0000000..37ae0a4 --- /dev/null +++ b/vendor/cros-codecs/CONTRIBUTING.md @@ -0,0 +1,33 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. + +## Before you begin + +### Sign our Contributor License Agreement + +Contributions to this project must be accompanied by a +[Contributor License Agreement](https://cla.developers.google.com/about) (CLA). +You (or your employer) retain the copyright to your contribution; this simply +gives us permission to use and redistribute your contributions as part of the +project. + +If you or your current employer have already signed the Google CLA (even if it +was for a different project), you probably don't need to do it again. + +Visit to see your current agreements or to +sign a new one. + +### Review our Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google/conduct/). + +## Contribution process + +### Code Reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. diff --git a/vendor/cros-codecs/Cargo.lock b/vendor/cros-codecs/Cargo.lock new file mode 100644 index 0000000..5537478 --- /dev/null +++ b/vendor/cros-codecs/Cargo.lock @@ -0,0 +1,847 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" + +[[package]] +name = "argh" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ff18325c8a36b82f992e533ece1ec9f9a9db446bd1c14d4f936bac88fcd240" +dependencies = [ + "argh_derive", + "argh_shared", + "rust-fuzzy-search", +] + +[[package]] +name = "argh_derive" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b2b83a50d329d5d8ccc620f5c7064028828538bdf5646acd60dc1f767803" +dependencies = [ + "argh_shared", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "argh_shared" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a464143cc82dedcdc3928737445362466b7674b5db4e2eb8e869846d6d84f4f6" +dependencies = [ + "serde", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.12.1", + "lazy_static", + "lazycell", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", + "which", +] + +[[package]] +name = "bindgen" +version = "0.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" + +[[package]] +name = "bytemuck" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cros-codecs" +version = "0.0.6" +dependencies = [ + "anyhow", + "argh", + "byteorder", + "crc32fast", + "cros-libva", + "drm", + "drm-fourcc", + "env_logger", + "gbm", + "gbm-sys", + "log", + "nix", + "serde_json", + "thiserror", + "v4l2r", + "zerocopy", +] + +[[package]] +name = "cros-libva" +version = "0.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "902c9726e953b678595456bd38f95f31aaf1947c56dd9f4a2290f3f1eca4d228" +dependencies = [ + "bindgen 0.70.1", + "bitflags", + "log", + "pkg-config", + "regex", + "thiserror", +] + +[[package]] +name = "drm" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98888c4bbd601524c11a7ed63f814b8825f420514f78e96f752c437ae9cbb5d1" +dependencies = [ + "bitflags", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "rustix", +] + +[[package]] +name = "drm-ffi" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97c98727e48b7ccb4f4aea8cfe881e5b07f702d17b7875991881b41af7278d53" +dependencies = [ + "drm-sys", + "rustix", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd39dde40b6e196c2e8763f23d119ddb1a8714534bf7d77fa97a65b0feda3986" +dependencies = [ + "libc", + "linux-raw-sys 0.6.5", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "env_logger" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "errno" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "gbm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45bf55ba6dd53ad0ac115046ff999c5324c283444ee6e0be82454c4e8eb2f36a" +dependencies = [ + "bitflags", + "drm", + "drm-fourcc", + "gbm-sys", + "libc", +] + +[[package]] +name = "gbm-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cc2f64de9fa707b5c6b2d2f10d7a7e49e845018a9f5685891eb40d3bab2538" +dependencies = [ + "libc", +] + +[[package]] +name = "glob" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "humantime" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b112acc8b3adf4b107a8ec20977da0273a8c386765a3ec0229bd500a1443f9f" + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "libc" +version = "0.2.174" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" + +[[package]] +name = "libloading" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" +dependencies = [ + "cfg-if", + "windows-targets 0.53.2", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a385b1be4e5c3e362ad2ffa73c392e53f031eaa5b7d648e64cd87f27f6063d7" + +[[package]] +name = "log" +version = "0.4.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" + +[[package]] +name = "memchr" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "prettyplease" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "rust-fuzzy-search" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys", +] + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "serde" +version = "1.0.219" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.219" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.140" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "syn" +version = "2.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" + +[[package]] +name = "v4l2r" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe1d612d2df2a0802020c49a1b029282c45991cdfff1731b5fc61ed3dce4168a" +dependencies = [ + "anyhow", + "bindgen 0.69.5", + "bitflags", + "enumn", + "log", + "nix", + "thiserror", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "zerocopy" +version = "0.8.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/vendor/cros-codecs/Cargo.toml b/vendor/cros-codecs/Cargo.toml new file mode 100644 index 0000000..1795e37 --- /dev/null +++ b/vendor/cros-codecs/Cargo.toml @@ -0,0 +1,123 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "cros-codecs" +version = "0.0.6" +authors = ["The ChromiumOS Authors"] +description = "Hardware-accelerated codecs for Linux" +readme = "README.md" +license = "BSD-3-Clause" +repository = "https://github.com/chromeos/cros-codecs" + + + + +[dependencies.anyhow] +version = "1.0.75" +optional = true + +[dependencies.byteorder] +version = "1.4.3" +optional = true + +[dependencies.crc32fast] +version = "1.3.2" +optional = true + +[dependencies.drm] +version = "0.12.0" +optional = true + +[dependencies.drm-fourcc] +version = "2.2.0" +optional = true + +[dependencies.gbm] +version = "0.15" +features = ["drm-support"] +optional = true +default-features = false + +[dependencies.gbm-sys] +version = "0.3.1" +optional = true + +[dependencies.libva] +version = "0.0.12" +optional = true +package = "cros-libva" + +[dependencies.log] +version = "0" +features = ["release_max_level_debug"] + +[dependencies.nix] +version = "0.28" +features = [ + "fs", + "event", + "poll", + "mman", + "ioctl", +] +optional = true + +[dependencies.thiserror] +version = "1.0.58" +optional = true + +[dependencies.v4l2r] +version = "0.0.5" +optional = true +package = "v4l2r" + +[dependencies.zerocopy] +version = "0.8.14" +features = ["derive"] +optional = true + +[dev-dependencies.argh] +version = "0.1.12" + +[dev-dependencies.env_logger] +version = "0.9.3" + +[dev-dependencies.serde_json] +version = "1.0.96" + +[features] +backend = [ + "anyhow", + "byteorder", + "thiserror", + "crc32fast", + "nix", + "gbm", + "gbm-sys", + "drm", + "drm-fourcc", + "zerocopy", +] +default = [] +v4l2 = [ + "v4l2r", + "backend", +] +vaapi = [ + "libva", + "backend", +] + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 diff --git a/vendor/cros-codecs/DIR_METADATA b/vendor/cros-codecs/DIR_METADATA new file mode 100644 index 0000000..f181efa --- /dev/null +++ b/vendor/cros-codecs/DIR_METADATA @@ -0,0 +1,13 @@ +# Metadata information for this directory. +# +# For more information on DIR_METADATA files, see: +# https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/README.md +# +# For the schema of this file, see Metadata message: +# https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/proto/dir_metadata.proto + +buganizer { + component_id: 168352 # ChromeOS > Platform > Graphics > Video +} + +team_email: "chromeos-gfx-video@google.com" diff --git a/vendor/cros-codecs/LICENSE b/vendor/cros-codecs/LICENSE new file mode 100644 index 0000000..9c1f839 --- /dev/null +++ b/vendor/cros-codecs/LICENSE @@ -0,0 +1,26 @@ +Copyright 2022 The ChromiumOS Authors + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/cros-codecs/METADATA b/vendor/cros-codecs/METADATA new file mode 100644 index 0000000..10732f0 --- /dev/null +++ b/vendor/cros-codecs/METADATA @@ -0,0 +1,16 @@ +name: "cros-codecs" +description: + "A lightweight, simple, low-dependency, and hopefully safe crate for " + "hardware-accelerated video decoding and encoding on Linux." + +third_party { +homepage: "https://github.com/chromeos/cros-codecs" + identifier { + type: "Git" + value: "https://github.com/chromeos/cros-codecs" + primary_source: false + } + + last_upgrade_date { year: 2024 month: 12 day: 3 } + license_type: NOTICE +} diff --git a/vendor/cros-codecs/MODULE_LICENSE_BSD b/vendor/cros-codecs/MODULE_LICENSE_BSD new file mode 100644 index 0000000..e69de29 diff --git a/vendor/cros-codecs/OWNERS b/vendor/cros-codecs/OWNERS new file mode 100644 index 0000000..d297045 --- /dev/null +++ b/vendor/cros-codecs/OWNERS @@ -0,0 +1,10 @@ +abodenha@google.com +bselma@google.com +hiroh@google.com +andrescj@google.com +greenjustin@google.com +nhebert@google.com +frkoenig@google.com +bchoobineh@google.com +pmolinalopez@google.com +hnt@google.com diff --git a/vendor/cros-codecs/README.md b/vendor/cros-codecs/README.md new file mode 100644 index 0000000..4da41fc --- /dev/null +++ b/vendor/cros-codecs/README.md @@ -0,0 +1,71 @@ +# Cros-codecs + +[crates.io](https://crates.io/crates/cros-codecs) +[docs.rs](https://docs.rs/cros-codecs/latest/cros_codecs/) + +A lightweight, simple, low-dependency, and hopefully safe crate for +hardware-accelerated video decoding and encoding on Linux. + +It is developed for use in ChromeOS (particularly +[crosvm](https://github.com/google/crosvm)), but has no dependency to ChromeOS +and should be usable anywhere. + +## Current features + +- Simple decoder API, +- VAAPI decoder support (using + [cros-libva](https://github.com/chromeos/cros-libva)) for H.264, H.265, VP8, + VP9 and AV1, +- VAAPI encoder support for H.264, VP9 and AV1, +- Stateful V4L2 encoder support. + +## Planned features + +- Stateful V4L2 decoder support, +- Stateless V4L2 decoder support, +- Support for more encoder codecs, +- C API to be used in non-Rust projects. + +## Non-goals + +- Support for systems other than Linux. + +## Example programs + +The `ccdec` example program can decode an encoded stream and write the decoded +frames to a file. As such it can be used for testing purposes. + +```shell +$ cargo build --examples +$ ./target/debug/examples/ccdec --help +Usage: ccdec [--output ] --input-format [--output-format ] [--compute-md5 ] + +Simple player using cros-codecs + +Positional Arguments: + input input file + +Options: + --output output file to write the decoded frames to + --input-format input format to decode from. + --output-format pixel format to decode into. Default: i420 + --compute-md5 whether to display the MD5 of the decoded stream, and at + which granularity (stream or frame) + --help display usage information +``` + +## Testing + +Fluster can be used for testing, using the `ccdec` example program described +above. [This branch](https://github.com/Gnurou/fluster/tree/cros-codecs) +contains support for cros-codecs testing. Just make sure the `ccdec` binary is +in your `PATH`, and run Fluster using one of the `ccdec` decoders, e.g. + +```shell +python fluster.py run -d ccdec-H.264 -ts JVT-AVC_V1 +``` + +## Credits + +The majority of the code in the initial commit has been written by Daniel +Almeida as a VAAPI backend for crosvm, before being split into this crate. diff --git a/vendor/cros-codecs/cargo_embargo.json b/vendor/cros-codecs/cargo_embargo.json new file mode 100644 index 0000000..95c4655 --- /dev/null +++ b/vendor/cros-codecs/cargo_embargo.json @@ -0,0 +1,10 @@ +{ + "package": { + "cros-codecs": { + "host_supported": false + } + }, + "product_available": true, + "vendor_available": true, + "run_cargo": false +} diff --git a/vendor/cros-codecs/rustfmt.toml b/vendor/cros-codecs/rustfmt.toml new file mode 100644 index 0000000..a70acca --- /dev/null +++ b/vendor/cros-codecs/rustfmt.toml @@ -0,0 +1,3 @@ +edition = "2021" +use_small_heuristics = "Max" +newline_style = "Unix" diff --git a/vendor/cros-codecs/simple_test.py b/vendor/cros-codecs/simple_test.py new file mode 100644 index 0000000..7ed741f --- /dev/null +++ b/vendor/cros-codecs/simple_test.py @@ -0,0 +1,46 @@ +import glob +import os +import subprocess + +CCDEC_BINARY_PATH = 'target/debug/examples/ccdec' + +def validate_decode(bitstream_path, codec): + if not os.path.isfile(bitstream_path + '.md5'): # Missing golden, skip this vector + return + + with open(bitstream_path + '.md5', 'r') as golden_file: + golden = golden_file.read() + + ccdec_process = subprocess.run([CCDEC_BINARY_PATH, bitstream_path, '--frame-memory', 'prime', '--input-format', codec, '--output-format', 'nv12', '--compute-md5', 'frame'], capture_output=True) + if ccdec_process.returncode != 0: + print('Error running ccdec for bitstream ' + bitstream_path) + print(ccdec_process.stderr.decode('utf-8')) + return + + test_output = ccdec_process.stdout.decode('utf-8') + if test_output != golden: + print('MD5 mistmatch on bitstream ' + bitstream_path) + test_lines = test_output.split('\n') + golden_lines = golden.split('\n') + if len(test_lines) > len(golden_lines): + print('Found more frames in ccdec output than expected') + elif len(test_lines) < len(golden_lines): + print('Found fewer frames in ccdec output than expected') + else: + for i in range(0, len(test_lines)): + if test_lines[i] != golden_lines[i]: + print('First mismatch on frame ' + str(i)) + print('Expected: ' + golden_lines[i]) + print('Got: ' + test_lines[i]) + break + + +if not os.path.isfile(CCDEC_BINARY_PATH): + print('Error! ccdec not found. Have you compiled examples yet?') + +extensions = ['.h264', '.h265', '.av1', '.vp8', '.vp9', '.ivf'] +for extension in extensions: + for bitstream_path in glob.glob('src/codec/*/test_data/*' + extension): + codec = bitstream_path[len('src/codec/'):] + codec = codec[:codec.find('/')] + validate_decode(bitstream_path, codec) diff --git a/vendor/cros-codecs/src/backend.rs b/vendor/cros-codecs/src/backend.rs new file mode 100644 index 0000000..d54fb92 --- /dev/null +++ b/vendor/cros-codecs/src/backend.rs @@ -0,0 +1,16 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Shared code for codec backends. +//! +//! A backend is a provider of codec decoding or encoding, most likely hardware-accelerated like +//! VAAPI. This module contains backend-related code that is not tied to any particular codec and +//! can be shared between various parts of this crate. + +#[cfg(any(test, fuzzing))] +pub(crate) mod dummy; +#[cfg(feature = "v4l2")] +pub mod v4l2; +#[cfg(feature = "vaapi")] +pub mod vaapi; diff --git a/vendor/cros-codecs/src/backend/dummy.rs b/vendor/cros-codecs/src/backend/dummy.rs new file mode 100644 index 0000000..da6fd98 --- /dev/null +++ b/vendor/cros-codecs/src/backend/dummy.rs @@ -0,0 +1,8 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backends whose only purpose is to let the codec +//! run so we can test it in isolation. + +pub(crate) mod decoder; diff --git a/vendor/cros-codecs/src/backend/dummy/decoder.rs b/vendor/cros-codecs/src/backend/dummy/decoder.rs new file mode 100644 index 0000000..00b3610 --- /dev/null +++ b/vendor/cros-codecs/src/backend/dummy/decoder.rs @@ -0,0 +1,149 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backend whose only purpose is to let the decoder +//! run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::decoder::stateless::PoolLayer; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::TryFormat; +use crate::decoder::DecodedHandle; +use crate::decoder::DynHandle; +use crate::decoder::FramePool; +use crate::decoder::MappableHandle; +use crate::decoder::StreamInfo; +use crate::DecodedFormat; +use crate::Resolution; + +#[derive(Default)] +pub struct BackendHandle(()); + +impl MappableHandle for BackendHandle { + fn read(&mut self, _: &mut [u8]) -> anyhow::Result<()> { + Ok(()) + } + + fn image_size(&mut self) -> usize { + 1 + } +} + +impl<'a> DynHandle for std::cell::RefMut<'a, BackendHandle> { + fn dyn_mappable_handle<'b>(&'b mut self) -> anyhow::Result> { + Ok(Box::::default()) + } +} + +pub struct Handle { + pub handle: Rc>, +} + +impl Clone for Handle { + fn clone(&self) -> Self { + Self { handle: Rc::clone(&self.handle) } + } +} + +impl DecodedHandle for Handle { + type Descriptor = (); + + fn coded_resolution(&self) -> Resolution { + Default::default() + } + + fn display_resolution(&self) -> Resolution { + Default::default() + } + + fn timestamp(&self) -> u64 { + 0 + } + + fn dyn_picture<'a>(&'a self) -> Box { + Box::new(self.handle.borrow()) + } + + fn sync(&self) -> anyhow::Result<()> { + Ok(()) + } + + fn is_ready(&self) -> bool { + true + } + + fn resource(&self) -> std::cell::Ref<()> { + std::cell::Ref::map(self.handle.borrow(), |h| &h.0) + } +} + +/// Dummy backend that can be used for any codec. +pub struct Backend { + stream_info: StreamInfo, +} + +impl Backend { + pub(crate) fn new() -> Self { + Self { + stream_info: StreamInfo { + format: DecodedFormat::I420, + min_num_frames: 4, + coded_resolution: Resolution::from((320, 200)), + display_resolution: Resolution::from((320, 200)), + }, + } + } +} + +impl FramePool for Backend { + type Descriptor = (); + + fn coded_resolution(&self) -> Resolution { + Resolution::from((320, 200)) + } + + fn set_coded_resolution(&mut self, _resolution: Resolution) {} + + fn add_frames(&mut self, _descriptors: Vec) -> Result<(), anyhow::Error> { + Ok(()) + } + + fn num_free_frames(&self) -> usize { + 4 + } + + fn num_managed_frames(&self) -> usize { + 4 + } + + fn clear(&mut self) {} +} + +impl StatelessDecoderBackendPicture for Backend { + type Picture = (); +} + +impl TryFormat for Backend { + fn try_format(&mut self, _: &Codec::FormatInfo, _: DecodedFormat) -> anyhow::Result<()> { + Ok(()) + } +} + +impl StatelessDecoderBackend for Backend { + type Handle = Handle; + + type FramePool = Self; + + fn stream_info(&self) -> Option<&StreamInfo> { + Some(&self.stream_info) + } + + fn frame_pool(&mut self, _: PoolLayer) -> Vec<&mut Self::FramePool> { + vec![self] + } +} diff --git a/vendor/cros-codecs/src/backend/v4l2.rs b/vendor/cros-codecs/src/backend/v4l2.rs new file mode 100644 index 0000000..9227ee7 --- /dev/null +++ b/vendor/cros-codecs/src/backend/v4l2.rs @@ -0,0 +1,20 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! V4L2 backend + +pub mod decoder; +pub mod encoder; + +impl From for crate::Fourcc { + fn from(value: v4l2r::PixelFormat) -> Self { + crate::Fourcc(value.to_u32()) + } +} + +impl From for v4l2r::PixelFormat { + fn from(value: crate::Fourcc) -> Self { + v4l2r::PixelFormat::from_u32(value.0) + } +} diff --git a/vendor/cros-codecs/src/backend/v4l2/decoder.rs b/vendor/cros-codecs/src/backend/v4l2/decoder.rs new file mode 100644 index 0000000..9adafbc --- /dev/null +++ b/vendor/cros-codecs/src/backend/v4l2/decoder.rs @@ -0,0 +1,21 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +use crate::Rect; +use crate::Resolution; + +pub const ADDITIONAL_REFERENCE_FRAME_BUFFER: usize = 4; + +pub mod stateless; + +pub trait V4l2StreamInfo { + /// Returns the minimum number of surfaces required to decode the stream. + // name was chosen to match vaapi + fn min_num_frames(&self) -> usize; + /// Returns the coded size of the surfaces required to decode the stream. + fn coded_size(&self) -> Resolution; + /// Returns the visible rectangle within the coded size for the stream. + fn visible_rect(&self) -> Rect; +} diff --git a/vendor/cros-codecs/src/backend/v4l2/decoder/stateless.rs b/vendor/cros-codecs/src/backend/v4l2/decoder/stateless.rs new file mode 100644 index 0000000..d3307d2 --- /dev/null +++ b/vendor/cros-codecs/src/backend/v4l2/decoder/stateless.rs @@ -0,0 +1,154 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use crate::backend::v4l2::decoder::V4l2StreamInfo; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::DecodedHandle; +use crate::decoder::StreamInfo; +use crate::device::v4l2::stateless::device::V4l2Device; +use crate::device::v4l2::stateless::request::V4l2Request; +use crate::video_frame::VideoFrame; +use crate::DecodedFormat; +use crate::Fourcc; +use crate::Resolution; + +pub struct V4l2Picture { + request: Rc>>, + // To properly decode stream while output and capture queues + // are processed independently it's required for v4l2 backend + // to maintain DPB buffer recycling. The following vector + // is used to prevent reference pictures to be reused while + // current picture is still being decoded. + ref_pictures: Option>>>>, +} + +impl V4l2Picture { + pub fn new(request: Rc>>) -> Self { + Self { request, ref_pictures: None } + } + pub fn video_frame(&self) -> Arc { + self.request.as_ref().borrow().result().capture_buffer.borrow().frame.clone() + } + pub fn timestamp(&self) -> u64 { + self.request.as_ref().borrow().timestamp() + } + pub fn set_ref_pictures( + &mut self, + ref_pictures: Vec>>>, + ) -> &mut Self { + self.ref_pictures = Some(ref_pictures); + self + } + pub fn sync(&mut self) -> &mut Self { + self.request.as_ref().borrow_mut().sync(); + self.ref_pictures = None; + self + } + pub fn request(&mut self) -> Rc>> { + self.request.clone() + } + pub fn drop_references(&mut self) { + self.ref_pictures = None; + } +} + +pub struct V4l2StatelessDecoderHandle { + pub picture: Rc>>, + pub stream_info: StreamInfo, +} + +impl Clone for V4l2StatelessDecoderHandle { + fn clone(&self) -> Self { + Self { picture: Rc::clone(&self.picture), stream_info: self.stream_info.clone() } + } +} + +impl DecodedHandle for V4l2StatelessDecoderHandle { + type Frame = V; + + fn video_frame(&self) -> Arc { + self.picture.borrow().video_frame() + } + + fn coded_resolution(&self) -> Resolution { + self.stream_info.coded_resolution.clone() + } + + fn display_resolution(&self) -> Resolution { + self.stream_info.display_resolution.clone() + } + + fn timestamp(&self) -> u64 { + self.picture.borrow().timestamp() + } + + fn sync(&self) -> anyhow::Result<()> { + self.picture.borrow_mut().sync(); + Ok(()) + } + + fn is_ready(&self) -> bool { + todo!(); + } +} + +pub struct V4l2StatelessDecoderBackend { + pub device: V4l2Device, + pub stream_info: StreamInfo, + pub frame_counter: u64, +} + +impl V4l2StatelessDecoderBackend { + pub fn new() -> Result { + Ok(Self { + device: V4l2Device::new()?, + stream_info: StreamInfo { + format: DecodedFormat::I420, + min_num_frames: 0, + coded_resolution: Resolution::from((0, 0)), + display_resolution: Resolution::from((0, 0)), + }, + frame_counter: 0, + }) + } + + pub(crate) fn new_sequence( + &mut self, + stream_params: &StreamData, + fourcc: Fourcc, + ) -> StatelessBackendResult<()> + where + for<'a> &'a StreamData: V4l2StreamInfo, + { + let coded_resolution = stream_params.coded_size().clone(); + let min_num_frames = stream_params.min_num_frames(); + + // TODO: Query the driver for the format + self.stream_info.format = DecodedFormat::MM21; + self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect()); + self.stream_info.coded_resolution = coded_resolution; + self.stream_info.min_num_frames = min_num_frames; + + Ok(self.device.initialize_queues(fourcc, coded_resolution, min_num_frames as u32)?) + } +} + +impl StatelessDecoderBackend for V4l2StatelessDecoderBackend { + type Handle = V4l2StatelessDecoderHandle; + + fn stream_info(&self) -> Option<&StreamInfo> { + // TODO + Some(&self.stream_info) + } + + fn reset_backend(&mut self) -> anyhow::Result<()> { + Ok(self.device.reset_queues()?) + } +} diff --git a/vendor/cros-codecs/src/backend/v4l2/encoder.rs b/vendor/cros-codecs/src/backend/v4l2/encoder.rs new file mode 100644 index 0000000..8089821 --- /dev/null +++ b/vendor/cros-codecs/src/backend/v4l2/encoder.rs @@ -0,0 +1,1368 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::collections::BTreeMap; +use std::fmt::Debug; +use std::marker::PhantomData; +use std::os::fd::AsRawFd; +use std::path::PathBuf; +use std::sync::Arc; + +use nix::sys::stat::fstat; +use thiserror::Error; +use v4l2r::bindings::v4l2_streamparm; +use v4l2r::controls::codec::VideoBitrate; +use v4l2r::controls::codec::VideoBitrateMode; +use v4l2r::controls::codec::VideoConstantQuality; +use v4l2r::controls::codec::VideoForceKeyFrame; +use v4l2r::controls::codec::VideoHeaderMode; +use v4l2r::controls::ExtControlTrait; +use v4l2r::controls::SafeExtControl; +use v4l2r::device::poller::DeviceEvent; +use v4l2r::device::poller::PollError; +use v4l2r::device::poller::Poller; +use v4l2r::device::queue::direction::Capture; +use v4l2r::device::queue::direction::Output; +use v4l2r::device::queue::dqbuf::DqBuffer; +use v4l2r::device::queue::qbuf::QBuffer; +use v4l2r::device::queue::BuffersAllocated; +use v4l2r::device::queue::CreateQueueError; +use v4l2r::device::queue::GetFreeBufferError; +use v4l2r::device::queue::GetFreeCaptureBuffer; +use v4l2r::device::queue::GetFreeOutputBuffer; +use v4l2r::device::queue::OutputQueueable; +use v4l2r::device::queue::OutputQueueableProvider; +use v4l2r::device::queue::Queue; +use v4l2r::device::queue::RequestBuffersError; +use v4l2r::device::AllocatedQueue; +use v4l2r::device::Device; +use v4l2r::device::DeviceConfig; +use v4l2r::device::Stream; +use v4l2r::device::TryDequeue; +use v4l2r::ioctl; +use v4l2r::ioctl::BufferFlags; +use v4l2r::ioctl::EncoderCommand; +use v4l2r::ioctl::StreamOnError; +use v4l2r::ioctl::V4l2BufferFromError; +use v4l2r::memory::BufferHandles; +use v4l2r::memory::DmaBufHandle; +use v4l2r::memory::MmapHandle; +use v4l2r::memory::PlaneHandle; +use v4l2r::memory::PrimitiveBufferHandles; +use v4l2r::memory::UserPtrHandle; +use v4l2r::nix::errno::Errno; +use v4l2r::nix::sys::time::TimeVal; +use v4l2r::Format; +use v4l2r::PixelFormat; +use v4l2r::QueueDirection; +use v4l2r::QueueType; + +use crate::encoder::stateful::BackendOutput; +use crate::encoder::stateful::BackendRequest; +use crate::encoder::stateful::BackendRequestId; +use crate::encoder::stateful::StatefulBackendError; +use crate::encoder::stateful::StatefulBackendResult; +use crate::encoder::stateful::StatefulVideoEncoderBackend; +use crate::encoder::CodedBitstreamBuffer; +use crate::encoder::EncodeError; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::Tunings; +use crate::utils::DmabufFrame; +use crate::utils::UserPtrFrame; +use crate::video_frame::V4l2VideoFrame; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::FrameLayout; +use crate::Resolution; + +#[derive(Debug, Error)] +pub enum UnsupportedError { + #[error("frame upscaling")] + FrameUpscaling, + + #[error("buffer lacking TIMESTAMP_COPY flag")] + NoTimestampCopyFlag, + + #[error("unsupported profile")] + Profile, +} + +#[derive(Debug, Error)] +pub enum InitializationError { + #[error(transparent)] + Unsupported(UnsupportedError), + + #[error("failed to create a CAPTURE queue: {0:?}")] + CaptureQueueCreate(CreateQueueError), + + #[error("failed to create a OUTPUT queue: {0:?}")] + OutputQueueCreate(CreateQueueError), + + #[error("failed to set format for CAPTURE: {0:?}")] + SetFormatCapture(ioctl::SFmtError), + + #[error("failed to set format for OUTPUT: {0:?}")] + SetFormatOutput(ioctl::SFmtError), + + #[error("failed to request CAPTURE buffers: {0:?}")] + RequestBufferCatpure(RequestBuffersError), + + #[error("failed to request OUTPUT buffers: {0:?}")] + RequestBufferOutput(RequestBuffersError), + + #[error("failed to stream on CAPTURE: {0:?}")] + StreamOnCapture(StreamOnError), + + #[error("failed to stream on OUTPUT: {0:?}")] + StreamOnOutput(StreamOnError), + + #[error(transparent)] + EncoderStart(#[from] ioctl::EncoderCmdError), + + #[error(transparent)] + CreatePoller(v4l2r::nix::Error), + + #[error(transparent)] + SetSelection(ioctl::SSelectionError), + + #[error(transparent)] + Contro(#[from] ControlError), +} + +#[derive(Debug, Error)] +pub struct ControlError { + which: &'static str, + error: Errno, +} + +impl std::fmt::Display for ControlError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("failed to set '{}': {:?}", self.which, self.error)) + } +} + +#[derive(Debug, Error)] +pub enum BackendError { + #[error(transparent)] + Unsupported(UnsupportedError), + + #[error(transparent)] + GetFreeBufferError(#[from] GetFreeBufferError), + + #[error(transparent)] + QueueBitstreamBuffer(anyhow::Error), + + #[error(transparent)] + MapBitstreamBuffer(anyhow::Error), + + #[error(transparent)] + QueueFrameHandleError(anyhow::Error), + + #[error(transparent)] + DequeueBuffer(#[from] ioctl::DqBufError), + + #[error("failed to map capture buffer: {0:?}")] + FailedToMapCapture(Timestamp), + + #[error(transparent)] + DrainCommand(#[from] ioctl::EncoderCmdError), + + #[error(transparent)] + Poll(#[from] PollError), + + #[error(transparent)] + GetFormat(#[from] ioctl::GFmtError), + + #[error(transparent)] + Control(#[from] ControlError), +} + +pub type BackendResult = std::result::Result; + +impl From for StatefulBackendError { + fn from(value: BackendError) -> Self { + StatefulBackendError::Other(anyhow::anyhow!(value)) + } +} + +impl From for EncodeError { + fn from(value: BackendError) -> Self { + EncodeError::StatefulBackendError(value.into()) + } +} + +/// Frame timestamp helper struct +#[repr(transparent)] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Timestamp(pub u64); + +impl From for Timestamp { + fn from(value: v4l2r::bindings::timeval) -> Self { + let timestamp = value.tv_sec.wrapping_mul(1_000_000); + let timestamp = timestamp.wrapping_add(value.tv_usec); + Timestamp(timestamp.max(0) as u64) + } +} + +impl From<&Timestamp> for TimeVal { + fn from(value: &Timestamp) -> Self { + let tv_sec = (value.0 / 1_000_000).min(i64::MAX as u64); + let tv_usec = (value.0 % 1_000_000).min(i64::MAX as u64); + Self::new(tv_sec as i64, tv_usec as i64) + } +} + +pub type OutputBuffer<'a, P> = + > as OutputQueueableProvider<'a, P>>::Queueable; + +/// Encoder input frame handle, that can be queued to OUTPUT queue. +pub trait OutputBufferHandle { + type PrimitiveBufferHandles: PrimitiveBufferHandles; + + fn queue(self, buffer: OutputBuffer<'_, Self::PrimitiveBufferHandles>) -> anyhow::Result<()>; +} + +pub trait AlwaysEntireBufferUsed {} + +impl AlwaysEntireBufferUsed for UserPtrFrame {} + +impl AlwaysEntireBufferUsed for DmabufFrame {} + +impl AlwaysEntireBufferUsed for V4l2VideoFrame {} + +impl OutputBufferHandle for T +where + T: PrimitiveBufferHandles + AlwaysEntireBufferUsed, +{ + type PrimitiveBufferHandles = Self; + + fn queue(self, buffer: OutputBuffer<'_, Self>) -> anyhow::Result<()> { + let mut bytes_used = Vec::new(); + for i in 0..self.len() { + let mut plane = v4l2r::bindings::v4l2_plane::default(); + self.fill_v4l2_plane(i, &mut plane); + bytes_used.push(plane.length as usize); + } + + log::trace!("Queueing buffer bytes_used={bytes_used:?}"); + buffer.queue_with_handles(self, &bytes_used).unwrap(); + Ok(()) + } +} + +impl BufferHandles for UserPtrFrame { + type SupportedMemoryType = v4l2r::memory::MemoryType; + + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2r::bindings::v4l2_plane) { + let plane_layout = &self.layout.planes[index]; + + plane.m.userptr = self.buffers[plane_layout.buffer_index] as _; + plane.data_offset = plane_layout.offset as _; + plane.length = self.mem_layout.size() as _; + } + + fn len(&self) -> usize { + self.layout.planes.len() + } +} + +impl PrimitiveBufferHandles for UserPtrFrame { + type HandleType = UserPtrHandle<[u8; 0]>; + const MEMORY_TYPE: Self::SupportedMemoryType = v4l2r::memory::MemoryType::UserPtr; +} + +// SAFETY: Access to the frame is read only +unsafe impl Send for UserPtrFrame {} + +// SAFETY: Access to the frame is read only +unsafe impl Sync for UserPtrFrame {} + +impl BufferHandles for DmabufFrame { + type SupportedMemoryType = v4l2r::memory::MemoryType; + + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2r::bindings::v4l2_plane) { + let plane_layout = &self.layout.planes[index]; + let fd = &self.fds[plane_layout.buffer_index]; + + plane.m.fd = fd.as_raw_fd(); + plane.data_offset = plane_layout.offset as u32; + plane.length = fstat(fd.as_raw_fd()).map(|stat| stat.st_size as u32).unwrap_or(0); + + if plane.length == 0 { + log::warn!("Failed to fstat proper plane size index={index}"); + } + } + + fn len(&self) -> usize { + self.layout.planes.len() + } +} + +impl PrimitiveBufferHandles for DmabufFrame { + type HandleType = DmaBufHandle; + const MEMORY_TYPE: Self::SupportedMemoryType = v4l2r::memory::MemoryType::DmaBuf; +} + +/// Encoder's coded specific trait enabling setting codec specific tunings +pub trait EncoderCodec { + /// Set's [`Tunings`] for the [`v4l2r::device::Device`] + fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError>; +} + +/// Trait responsible for CAPTURE buffers of the encoder's [`V4L2Backend`]. Enable custom logic of +/// CAPTURE specific for device/client use case. Useful especially when MMAP buffer type is not +/// supported for CAPTURE queue. In such scenario the client may choose to implement this function +/// and use own logic for allocating DMABUF or USERPTR. +pub trait CaptureBuffers { + /// [`PlaneHandle`] that is going to be used for CAPTURE buffers. + type PlaneHandle: PlaneHandle; + + /// Queues the buffer with [`CaptureBuffers::PlaneHandle`]s and returns true, + /// otherwise if the buffer may not be queue returns false. + fn queue( + &mut self, + buffer: QBuffer< + Capture, + Vec, + Vec, + &Queue>>, + >, + ) -> anyhow::Result; + + /// Maps the the buffer and returns its contents in form of [`Vec`] + fn export(&self, buffer: DqBuffer>) -> anyhow::Result>; +} + +/// [`CaptureBuffers`] implementation for MMAP memory type +pub struct MmapingCapture; + +impl CaptureBuffers for MmapingCapture { + type PlaneHandle = MmapHandle; + + fn queue( + &mut self, + buffer: QBuffer< + Capture, + Vec, + Vec, + &Queue>>, + >, + ) -> anyhow::Result { + buffer.queue()?; + Ok(true) + } + + fn export(&self, buffer: DqBuffer>) -> anyhow::Result> { + let timestamp = Timestamp::from(buffer.data.timestamp()); + let Some(mapping) = buffer.get_plane_mapping(0) else { + log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}"); + return Err(BackendError::FailedToMapCapture(timestamp).into()); + }; + + let bytesused = *buffer.data.get_first_plane().bytesused as usize; + + Ok(Vec::from(&mapping.data[..bytesused])) + } +} + +/// V4L2 stateful encoder implementation +pub struct V4L2Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, + Self: EncoderCodec, +{ + /// V4L2 encoder device + device: Arc, + + /// OUTPUT_MPLANE V4L2 queue + output_queue: Queue>, + + /// CAPTURE_MPLANE V4L2 queue + capture_queue: Queue>>, + + /// [`CaptureBuffers`] implementation + capture_buffers: CaptureBufferz, + + /// Buffers that are currently processed by the encoder device + currently_processed: BTreeMap, + + /// Currently set [`Tunings`] used to detected tunings change + current_tunings: Tunings, + + /// Device poller for implementing [`StatefulVideoEncoderBackend::sync`] + poller: Poller, + + _phantom: PhantomData<(Handle, Codec)>, +} + +impl V4L2Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, + Self: EncoderCodec, +{ + /// Checks if the device has the given control and sets it to desired value if it's diffrent + pub(crate) fn apply_ctrl( + device: &Device, + name: &'static str, + value: C, + ) -> Result<(), ControlError> + where + C: ExtControlTrait + Into, + { + let mut current = SafeExtControl::::from_value(0); + + log::trace!("Trying to set control {name}"); + match ioctl::g_ext_ctrls(device, ioctl::CtrlWhich::Current, &mut current) { + Ok(()) => (), + Err(ioctl::ExtControlError { + error_idx: _, + error: ioctl::ExtControlErrorType::IoctlError(Errno::EINVAL), + }) => { + log::debug!("Setting/getting {name} control is not supported for this device"); + return Ok(()); + } + Err(ioctl::ExtControlError { + error_idx: _, + error: ioctl::ExtControlErrorType::IoctlError(error), + }) => { + log::error!("Getting {name} control returned {:?}", error.desc()); + return Err(ControlError { which: name, error }); + } + }; + + let desired: i32 = value.into(); + if current.value() == desired { + log::debug!("Control {name} already has desired value"); + } + + let mut value = SafeExtControl::::from_value(desired); + + match ioctl::s_ext_ctrls(device, ioctl::CtrlWhich::Current, &mut value) { + Ok(()) => (), + Err(ioctl::ExtControlError { + error_idx: _, + error: ioctl::ExtControlErrorType::IoctlError(Errno::EINVAL), + }) => { + log::debug!("Setting/getting {name} control is not supported for this device"); + return Ok(()); + } + Err(ioctl::ExtControlError { + error_idx: _, + error: ioctl::ExtControlErrorType::IoctlError(error), + }) => return Err(ControlError { which: name, error }), + }; + + let value = value.value(); + + if value != desired { + // TODO: raise error? + log::warn!("Failed to set desired {name} (to: {desired}, is: {value})",); + } else { + log::trace!("Control {name} set correctly to {value}"); + } + + Ok(()) + } + + /// Sets the frame rate using S_PARM ioctl for the queue type on the device. + pub(crate) fn apply_parm(device: &Device, queue_type: QueueType, framerate: u32) { + let mut parm = v4l2_streamparm { type_: queue_type as u32, ..Default::default() }; + + let (num, denum) = if framerate != 0 { (1, framerate) } else { (0, 1) }; + + if matches!(queue_type, v4l2r::QueueType::VideoOutputMplane) { + parm.parm.output.capability = 0; + parm.parm.output.outputmode = 0; + parm.parm.output.timeperframe.numerator = num; + parm.parm.output.timeperframe.denominator = denum; + } else { + parm.parm.capture.capability = 0; + parm.parm.capture.timeperframe.numerator = num; + parm.parm.capture.timeperframe.denominator = denum; + } + + match v4l2r::ioctl::s_parm::<_, v4l2_streamparm>(device, parm) { + Ok(parm) => match QueueType::n(parm.type_).as_ref().map(QueueType::direction) { + // SAFETY: The type is set to output + Some(QueueDirection::Output) => unsafe { + log::debug!( + "OUTPUT: Time per frame set to {}/{}", + parm.parm.output.timeperframe.numerator, + parm.parm.output.timeperframe.denominator, + ); + }, + // SAFETY: The type is set to capture + Some(QueueDirection::Capture) => unsafe { + log::debug!( + "CAPTURE: Time per frame set to {}/{}", + parm.parm.capture.timeperframe.numerator, + parm.parm.capture.timeperframe.denominator, + ); + }, + _ => {} + }, + Err(errno) => log::warn!("{:?}: Failed to set parm: {errno:?}", queue_type.direction()), + } + } + + /// Sets the rate mode and bitrate params on the device. + fn apply_rate_control( + device: &Device, + framerate: u32, + rate_control: &RateControl, + ) -> Result<(), ControlError> { + Self::apply_parm(device, QueueType::VideoOutputMplane, framerate); + Self::apply_parm(device, QueueType::VideoCaptureMplane, 1000); + + Self::apply_ctrl( + device, + "bitrate mode", + match rate_control { + RateControl::ConstantBitrate(_) => VideoBitrateMode::ConstantBitrate, + RateControl::ConstantQuality(_) => VideoBitrateMode::ConstantQuality, + }, + )?; + + if let Some(bitrate) = rate_control.bitrate_target() { + Self::apply_ctrl(device, "bitrate", VideoBitrate(bitrate as i32))?; + } + + if let RateControl::ConstantQuality(qp) = rate_control { + Self::apply_ctrl(device, "constant quality", VideoConstantQuality(*qp as i32))?; + } + + Ok(()) + } + + /// Sets the crop. + pub fn apply_selection( + device: &Device, + visible_size: Resolution, + ) -> Result<(), ioctl::SSelectionError> { + let rect = + v4l2r::Rect { left: 0, top: 0, width: visible_size.width, height: visible_size.height }; + + log::trace!( + "Trying to apply to selection to (left: {}, top: {}, width: {}, height: {})", + rect.left, + rect.top, + rect.width, + rect.height + ); + + let rect = ioctl::s_selection::<_, v4l2r::Rect>( + device, + ioctl::SelectionType::Output, + ioctl::SelectionTarget::Crop, + rect, + ioctl::SelectionFlags::empty(), + )?; + + if rect.left == 0 + && rect.top == 0 + && rect.width == visible_size.width + && rect.height == visible_size.height + { + log::trace!("Selection set successfully"); + } else { + log::warn!( + "Driver set selection to (left: {}, top: {}, width: {}, height: {})", + rect.left, + rect.top, + rect.width, + rect.height + ); + } + + Ok(()) + } + + /// Creates and sets up the backend instance using the given configuration + pub fn create( + device: Arc, + capture_buffers: CaptureBufferz, + fourcc: Fourcc, + coded_size: Resolution, + visible_size: Resolution, + capture_pixfmt: v4l2r::PixelFormat, + tunings: Tunings, + ) -> Result { + let mut capture_queue = Queue::get_capture_mplane_queue(device.clone()) + .map_err(InitializationError::CaptureQueueCreate)?; + + let mut output_queue = Queue::get_output_mplane_queue(device.clone()) + .map_err(InitializationError::OutputQueueCreate)?; + + // Coded buffer size multiplier. It's inteded to give head room for the encoder. + const CODED_SIZE_MUL: u32 = 2; + + // Default coded buffer size if bitrate control is not used. + const DEFAULT_CODED_SIZE: u32 = 1_500_000; + + let coded_buffer_size = tunings + .rate_control + .bitrate_target() + .map(|e| e as u32 * CODED_SIZE_MUL) + .unwrap_or(DEFAULT_CODED_SIZE); + + let capture_format = Format { + width: coded_size.width, + height: coded_size.height, + pixelformat: capture_pixfmt, + plane_fmt: vec![v4l2r::PlaneLayout { sizeimage: coded_buffer_size, bytesperline: 0 }], + }; + + let capture_format = capture_queue + .set_format(capture_format) + .map_err(InitializationError::SetFormatCapture)?; + + // TODO: Map single planar formats to mutli planar format if single planar is not + // supported. + let output_pixfmt: PixelFormat = fourcc.0.into(); + + let output_format = Format { + width: coded_size.width, + height: coded_size.height, + pixelformat: output_pixfmt, + // Let the driver pick + plane_fmt: vec![], + }; + + let output_format = + output_queue.set_format(output_format).map_err(InitializationError::SetFormatOutput)?; + + log::debug!("CAPTURE queue format = {capture_format:#?}"); + log::debug!("OUTPUT queue format = {output_format:#?}"); + + Self::apply_rate_control(&device, tunings.framerate, &tunings.rate_control)?; + Self::apply_tunings(&device, &tunings)?; + + Self::apply_ctrl(&device, "header mode", VideoHeaderMode::JoinedWith1stFrame)?; + + if visible_size.width > output_format.width || visible_size.height > output_format.height { + return Err(InitializationError::Unsupported(UnsupportedError::FrameUpscaling)); + } else if visible_size.width != output_format.width + || visible_size.height != output_format.height + { + log::info!("The frame visible size is not aligned to coded size, applying selection"); + if let Err(err) = Self::apply_selection(&device, visible_size) { + log::error!("Failed to set selection: {err:?}"); + } + } + + log::debug!("CAPTURE: Requesting buffers"); + let capture_queue = capture_queue + .request_buffers::<_>(16) + .map_err(InitializationError::RequestBufferOutput)?; + + log::debug!("OUTPUT: Requesting buffers"); + let output_queue = output_queue + .request_buffers::(16) + .map_err(InitializationError::RequestBufferOutput)?; + + log::debug!("CAPTURE: Invoking stream on"); + capture_queue.stream_on().map_err(InitializationError::StreamOnCapture)?; + + log::debug!("OUTPUT: Invoking stream on"); + output_queue.stream_on().map_err(InitializationError::StreamOnOutput)?; + + log::debug!("Sending start command to encoder"); + ioctl::encoder_cmd::<_, ()>(&device, &EncoderCommand::Start) + .map_err(InitializationError::EncoderStart)?; + + let mut poller = Poller::new(device.clone()).map_err(InitializationError::CreatePoller)?; + + poller + .enable_event(DeviceEvent::CaptureReady) + .map_err(InitializationError::CreatePoller)?; + + Ok(Self { + device, + output_queue, + capture_queue, + capture_buffers, + currently_processed: Default::default(), + current_tunings: tunings, + poller, + _phantom: Default::default(), + }) + } + + pub fn output_format>(&self) -> BackendResult { + Ok(self.output_queue.get_format()?) + } + + fn poll_device(&mut self) -> BackendResult<()> { + self.poller.poll(None)?; + + Ok(()) + } + + /// Attempts to queue all free CAPTURE buffer for filling with encoded bitstream + fn queue_capture(&mut self) -> BackendResult<()> { + while self.capture_queue.num_free_buffers() != 0 { + let buffer = self.capture_queue.try_get_free_buffer()?; + let buffer_index = buffer.index(); + + let queued = + self.capture_buffers.queue(buffer).map_err(BackendError::QueueBitstreamBuffer)?; + + if !queued { + log::warn!("CAPTURE: Capture buffer was queued. Will retry later"); + break; + } + + log::trace!("CAPTURE: Queued new buffer index={}", buffer_index); + } + + Ok(()) + } + + /// Tries to dequeue a CAPTURE buffer and transforms the buffer contents into [`BackendOutput`] + fn dequeue_capture(&mut self) -> BackendResult> { + if self.capture_queue.num_queued_buffers() == 0 { + // Don't dequeue if there is nothing to dequeue + log::warn!("Polled while no buffer was queued on CAPTURE queue"); + return Ok(None); + } + + let buffer = match self.capture_queue.try_dequeue() { + Ok(buffer) => buffer, + Err(ioctl::DqBufError::IoctlError( + err @ ioctl::DqBufIoctlError::NotReady | err @ ioctl::DqBufIoctlError::Eos, + )) => { + log::trace!("Dequeue result: {err:?}"); + return Ok(None); + } + Err(err) => return Err(err.into()), + }; + + let timestamp = Timestamp::from(buffer.data.timestamp()); + log::debug!( + "CAPTRUE: Dequeued buffer index={} timestamp={:?} is_last={} bytesused={}, flags={:?}", + buffer.data.index(), + timestamp, + buffer.data.is_last(), + *buffer.data.get_first_plane().bytesused, + buffer.data.flags(), + ); + + if *buffer.data.get_first_plane().bytesused == 0 { + // Don't warn about empty lasty buffer + if !buffer.data.is_last() { + log::warn!("CAPTURE: Dequeued empty buffer. Skipping it."); + } + return Ok(None); + } + + if !buffer.data.flags().intersects(BufferFlags::TIMESTAMP_COPY) { + log::error!("CAPTURE: Buffer does not have TIMESTAMP_COPY flag"); + return Err(BackendError::Unsupported(UnsupportedError::NoTimestampCopyFlag)); + } + + let Some((request_id, meta)) = self.currently_processed.remove(×tamp) else { + log::error!("CAPTURE: Failed to find buffer timestamp={timestamp:?}"); + return Err(BackendError::FailedToMapCapture(timestamp)); + }; + + let bitstream = + self.capture_buffers.export(buffer).map_err(BackendError::MapBitstreamBuffer)?; + + let output = + BackendOutput { request_id, buffer: CodedBitstreamBuffer::new(meta, bitstream) }; + + Ok(Some(output)) + } + + /// Dequeues all processed OUTPUT buffers and drops them + fn drain_output_queue(&mut self) -> BackendResult<()> { + // Don't dequeue if there is nothing to dequeue + while self.output_queue.num_queued_buffers() != 0 { + match self.output_queue.try_dequeue() { + Ok(buffer) => { + log::debug!( + "OUTPUT: Dequeued buffer index={} timestamp={:?}", + buffer.data.index(), + Timestamp::from(buffer.data.timestamp()) + ); + // Drop the finished buffer + drop(buffer); + } + Err(ioctl::DqBufError::IoctlError(ioctl::DqBufIoctlError::NotReady)) => break, + Err(ioctl::DqBufError::IoctlError(ioctl::DqBufIoctlError::Eos)) => {} + Err(err) => return Err(err.into()), + } + } + + Ok(()) + } + + /// Takes the [`BackendRequest`] and queues it to OUTPUT queue + fn handle_request(&mut self, request: BackendRequest) -> BackendResult<()> { + if self.current_tunings != request.tunings { + log::debug!("Changing tunings to {:#?}", request.tunings); + Self::apply_rate_control( + &self.device, + request.tunings.framerate, + &request.tunings.rate_control, + )?; + Self::apply_tunings(&self.device, &request.tunings)?; + self.current_tunings = request.tunings; + } + + let buffer = self.output_queue.try_get_free_buffer()?; + + let timestamp = Timestamp(request.meta.timestamp); + let buffer = buffer.set_timestamp(TimeVal::from(×tamp)); + + let index = buffer.index(); + + if request.meta.force_keyframe { + let mut force = SafeExtControl::::from_value(1); + ioctl::s_ext_ctrls(&self.device, ioctl::CtrlWhich::Current, &mut force).map_err( + |error| ControlError { which: "force keyframe", error: error.error.into() }, + )?; + } + + request.handle.queue(buffer).map_err(BackendError::QueueFrameHandleError)?; + + log::debug!("OUTPUT: Queued buffer index={} timestamp={:?}", index, timestamp); + + // TODO: Use RequestId for this? + self.currently_processed.insert(timestamp, (request.request_id, request.meta)); + + Ok(()) + } + + /// Performs the essential processing ie. queues and dequeues the buffers from CAPTURE and + /// OUTPUT queue. + fn handle_buffers(&mut self) -> BackendResult<()> { + self.queue_capture()?; + self.drain_output_queue()?; + + log::debug!( + "Queue status: OUTPUT(free: {}, queued: {}) CAPTURE(free: {}, queued: {})", + self.output_queue.num_free_buffers(), + self.output_queue.num_queued_buffers(), + self.capture_queue.num_free_buffers(), + self.capture_queue.num_queued_buffers(), + ); + + Ok(()) + } +} + +impl StatefulVideoEncoderBackend + for V4L2Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, + Self: EncoderCodec, +{ + fn consume_request( + &mut self, + request: &mut Option>, + ) -> StatefulBackendResult<()> { + self.handle_buffers()?; + + if self.output_queue.num_free_buffers() == 0 { + return Ok(()); + } + + let Some(request) = request.take() else { + log::error!("StatefulEncoder passed an empty request"); + return Err(StatefulBackendError::InvalidInternalState); + }; + + self.handle_request(request)?; + + Ok(()) + } + + fn sync(&mut self) -> StatefulBackendResult<()> { + self.poll_device()?; + Ok(()) + } + + fn poll(&mut self) -> StatefulBackendResult> { + Ok(self.dequeue_capture()?) + } + + fn drain(&mut self) -> StatefulBackendResult> { + if self.currently_processed.is_empty() { + log::info!("Skipping drain sequence, nothing to drain."); + return Ok(Vec::new()); + } + + log::debug!( + "Sending stop command to encoder. Currently processing count: {}", + self.currently_processed.len() + ); + + ioctl::encoder_cmd::<_, ()>(&self.device, &EncoderCommand::Stop(false)) + .map_err(BackendError::DrainCommand)?; + + let mut drained_output = Vec::new(); + while !self.currently_processed.is_empty() { + self.poll_device()?; + self.handle_buffers()?; + + if let Some(output) = self.dequeue_capture()? { + drained_output.push(output); + } + } + + // Dequeue is_last=true buffer + if let Some(output) = self.dequeue_capture()? { + drained_output.push(output); + } + + log::debug!("Sending start command to encoder"); + ioctl::encoder_cmd::<_, ()>(&self.device, &EncoderCommand::Start) + .map_err(BackendError::DrainCommand)?; + + log::debug!("Drain finished"); + Ok(drained_output) + } +} + +pub fn find_device_with_capture(pixfmt: v4l2r::PixelFormat) -> Option { + const MAX_DEVICE_NO: usize = 128; + for dev_no in 0..MAX_DEVICE_NO { + let device_path = PathBuf::from(format!("/dev/video{dev_no}")); + let Ok(device) = Device::open(&device_path, DeviceConfig::new()) else { + continue; + }; + + let device = Arc::new(device); + + let Ok(queue) = Queue::get_capture_mplane_queue(device) else { + continue; + }; + + for fmt in queue.format_iter() { + if fmt.pixelformat == pixfmt { + return Some(device_path); + } + } + } + + None +} + +pub fn v4l2_format_to_frame_layout(format: &v4l2r::Format) -> FrameLayout { + let mut layout = FrameLayout { + format: (Fourcc::from(format.pixelformat.to_u32()), 0), + size: Resolution { width: format.width, height: format.height }, + planes: format + .plane_fmt + .iter() + .map(|plane| crate::PlaneLayout { + buffer_index: 0, + offset: 0, + stride: plane.bytesperline as usize, + }) + .collect(), + }; + + // Patch FrameLayout + match &format.pixelformat.to_fourcc() { + b"NM12" if layout.planes.len() == 2 => { + layout.planes[1].buffer_index = 1; + } + b"NV12" if layout.planes.len() == 1 => {} + _ => panic!("Unknown format"), + }; + + layout +} + +#[cfg(test)] +pub(crate) mod tests { + use std::os::fd::AsFd; + use std::os::fd::BorrowedFd; + use std::os::fd::OwnedFd; + use std::path::Path; + use std::path::PathBuf; + + use anyhow::Context; + use v4l2r::device::queue::CaptureQueueable; + use v4l2r::device::DeviceConfig; + use v4l2r::memory::DmaBufSource; + + use super::*; + + use crate::backend::v4l2::encoder::CaptureBuffers; + use crate::encoder::simple_encode_loop; + use crate::encoder::stateful::StatefulEncoder; + use crate::encoder::tests::fill_test_frame_nm12; + use crate::encoder::tests::fill_test_frame_nv12; + use crate::encoder::tests::get_test_frame_t; + + /// A simple wrapper for a GBM device node. + pub struct GbmDevice(std::fs::File); + + impl AsFd for GbmDevice { + fn as_fd(&self) -> BorrowedFd<'_> { + self.0.as_fd() + } + } + + impl drm::Device for GbmDevice {} + + /// Simple helper methods for opening a `Card`. + impl GbmDevice { + pub fn open>(path: P) -> std::io::Result { + std::fs::OpenOptions::new().read(true).write(true).open(path).map(GbmDevice) + } + } + + pub struct BoCaptureBuffer { + bo: gbm::BufferObject<()>, + fd: OwnedFd, + len: u64, + } + + impl AsRawFd for BoCaptureBuffer { + fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd { + self.fd.as_raw_fd() + } + } + + impl AsFd for BoCaptureBuffer { + fn as_fd(&self) -> BorrowedFd<'_> { + self.fd.as_fd() + } + } + + impl DmaBufSource for BoCaptureBuffer { + fn len(&self) -> u64 { + self.len + } + } + + impl std::fmt::Debug for BoCaptureBuffer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("BoCaptureBuffer").finish() + } + } + + unsafe impl Sync for BoCaptureBuffer {} + + unsafe impl Send for BoCaptureBuffer {} + + // SAFETY: copied from gbm.h + pub const GBM_BO_USE_SW_READ_OFTEN: gbm::BufferObjectFlags = + unsafe { gbm::BufferObjectFlags::from_bits_truncate(1 << 9) }; + + // SAFETY: copied from gbm.h + pub const GBM_BO_USE_HW_VIDEO_ENCODER: gbm::BufferObjectFlags = + unsafe { gbm::BufferObjectFlags::from_bits_truncate(1 << 14) }; + + pub struct BoPoolAllocator { + gbm: Arc>, + } + + impl BoPoolAllocator { + pub fn new(gbm: Arc>) -> Self { + Self { gbm } + } + } + + impl CaptureBuffers for BoPoolAllocator { + type PlaneHandle = DmaBufHandle; + + fn queue( + &mut self, + buffer: QBuffer< + Capture, + Vec, + Vec, + &Queue>>, + >, + ) -> anyhow::Result { + let len = 2 * 1024 * 1024; + + log::trace!("Allocating new bo"); + let bo = self + .gbm + .create_buffer_object::<()>( + len as u32, + 1, + gbm::Format::R8, + GBM_BO_USE_HW_VIDEO_ENCODER | GBM_BO_USE_SW_READ_OFTEN, + ) + .context("gbm_bo_create")?; + + let fd = bo.fd_for_plane(0).unwrap(); + let handle = BoCaptureBuffer { bo, fd, len }; + + buffer + .queue_with_handles(vec![DmaBufHandle(handle)]) + .context("queue bo as dmabuf handle")?; + + Ok(true) + } + + fn export( + &self, + mut buffer: DqBuffer>, + ) -> anyhow::Result> { + let timestamp = Timestamp::from(buffer.data.timestamp()); + + let Some(mut handle) = buffer.take_handles() else { + log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}"); + return Err(BackendError::FailedToMapCapture(timestamp).into()); + }; + + let Some(handle) = handle.pop() else { + log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}"); + return Err(BackendError::FailedToMapCapture(timestamp).into()); + }; + + let bytesused = *buffer.data.get_first_plane().bytesused; + + let mut content = Vec::with_capacity(bytesused as usize); + + handle.0.bo.map(&self.gbm, 0, 0, bytesused, 1, |mapped| { + content.extend(mapped.buffer()); + })??; + + Ok(content) + } + } + + pub struct TestMmapFrame { + meta: FrameMetadata, + frame_count: u64, + } + + impl OutputBufferHandle for TestMmapFrame { + type PrimitiveBufferHandles = Vec; + + fn queue( + self, + buffer: OutputBuffer<'_, Self::PrimitiveBufferHandles>, + ) -> anyhow::Result<()> { + if self.meta.layout.format == (Fourcc::from(b"NM12"), 0) { + let mut y_plane = buffer.get_plane_mapping(0).unwrap(); + let mut uv_plane = buffer.get_plane_mapping(1).unwrap(); + + fill_test_frame_nm12( + self.meta.layout.size.width as usize, + self.meta.layout.size.height as usize, + [self.meta.layout.planes[0].stride, self.meta.layout.planes[1].stride], + get_test_frame_t(self.meta.timestamp, self.frame_count), + y_plane.as_mut(), + uv_plane.as_mut(), + ); + + buffer.queue(&[y_plane.len(), uv_plane.len()])?; + } else if self.meta.layout.format == (Fourcc::from(b"NV12"), 0) { + let mut plane = buffer.get_plane_mapping(0).unwrap(); + + let strides = + [self.meta.layout.planes[0].stride, self.meta.layout.planes[0].stride]; + let offsets = [ + self.meta.layout.planes[0].offset, + self.meta.layout.planes[0].stride * self.meta.layout.size.height as usize, + ]; + + fill_test_frame_nv12( + self.meta.layout.size.width as usize, + self.meta.layout.size.height as usize, + strides, + offsets, + get_test_frame_t(self.meta.timestamp, self.frame_count), + plane.as_mut(), + ); + + buffer.queue(&[plane.len()])?; + } else { + return Err(anyhow::anyhow!("unsupported format")); + } + + Ok(()) + } + } + + /// Helper struct. Procedurally generate NV12 or NM12 frames for test purposes. + pub struct TestMmapFrameGenerator { + counter: u64, + max_count: u64, + frame_layout: FrameLayout, + } + + impl TestMmapFrameGenerator { + pub fn new(max_count: u64, frame_layout: FrameLayout) -> Self { + Self { counter: 0, max_count, frame_layout } + } + } + + impl Iterator for TestMmapFrameGenerator { + type Item = (FrameMetadata, TestMmapFrame); + + fn next(&mut self) -> Option { + if self.counter > self.max_count { + return None; + } + + self.counter += 1; + + let meta = FrameMetadata { + timestamp: self.counter, + layout: self.frame_layout.clone(), + force_keyframe: false, + }; + + let handle = TestMmapFrame { meta: meta.clone(), frame_count: self.max_count }; + + Some((meta, handle)) + } + } + + pub fn perform_v4l2_encoder_mmap_test( + frame_count: u64, + mut encoder: StatefulEncoder< + TestMmapFrame, + V4L2Backend, + >, + coded_consumer: impl FnMut(CodedBitstreamBuffer), + ) where + V4L2Backend: EncoderCodec, + { + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + let layout = v4l2_format_to_frame_layout(&format); + let mut frame_producer = TestMmapFrameGenerator::new(frame_count, layout); + + simple_encode_loop(&mut encoder, &mut frame_producer, coded_consumer).expect("encode loop"); + } + + /// Helper struct. Procedurally generate NV12 or NM12 frames for test purposes. + pub struct TestDmabufFrameGenerator { + counter: u64, + max_count: u64, + coded_size: Resolution, + visible_size: Resolution, + gbm: Arc>, + } + + impl TestDmabufFrameGenerator { + pub fn new( + max_count: u64, + coded_size: Resolution, + visible_size: Resolution, + gbm: Arc>, + ) -> Self { + Self { counter: 0, max_count, coded_size, visible_size, gbm } + } + } + + impl Iterator for TestDmabufFrameGenerator { + type Item = (FrameMetadata, DmabufFrame); + + fn next(&mut self) -> Option { + if self.counter > self.max_count { + return None; + } + + self.counter += 1; + + let bo = self + .gbm + .create_buffer_object::<()>( + self.coded_size.width, + self.coded_size.height, + gbm::Format::Nv12, + GBM_BO_USE_HW_VIDEO_ENCODER, + ) + .expect("create bo"); + + let plane_count = bo.plane_count().unwrap() as i32; + let fourcc = bo.format().unwrap(); + + if plane_count > 2 { + // NOTE: NV12 should be at most 2 plane. + panic!("Unsupported plane count for bo"); + } + + let mut fds: Vec = Vec::new(); + let mut inodes: Vec = Vec::new(); + let mut planes = Vec::new(); + + for plane in 0..(bo.plane_count().unwrap() as i32) { + let fd = bo.fd_for_plane(plane).unwrap(); + let stat = fstat(fd.as_raw_fd()).unwrap(); + let offset = bo.offset(plane as _).unwrap() as usize; + let stride = bo.stride_for_plane(plane as _).unwrap() as usize; + let buffer_index; + + // Deduplicate fds + if let Some((index, _)) = + inodes.iter().enumerate().find(|(_, s)| **s == stat.st_ino) + { + buffer_index = index; + } else { + buffer_index = fds.len(); + fds.push(fd); + inodes.push(stat.st_ino); + } + + planes.push(crate::PlaneLayout { buffer_index, offset, stride }) + } + + let layout = FrameLayout { + format: (Fourcc::from(fourcc as u32), 0), + size: self.visible_size, + planes, + }; + dbg!(&layout); + + let meta = FrameMetadata { + timestamp: self.counter, + layout: layout.clone(), + force_keyframe: false, + }; + + let frame = DmabufFrame { fds, layout }; + + Some((meta, frame)) + } + } + + pub fn perform_v4l2_encoder_dmabuf_test( + coded_size: Resolution, + visible_size: Resolution, + frame_count: u64, + gbm: Arc>, + mut encoder: StatefulEncoder>, + coded_consumer: impl FnMut(CodedBitstreamBuffer), + ) where + V4L2Backend: EncoderCodec, + { + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + + let mut frame_producer = + TestDmabufFrameGenerator::new(frame_count, coded_size, visible_size, gbm).map( + |(meta, mut frame)| { + if frame.layout.format.0 == Fourcc::from(b"NV12") + && frame.layout.planes.len() == 2 + && format.pixelformat == PixelFormat::from_fourcc(b"NV12") + && format.plane_fmt.len() == 1 + { + // Remove last NV12 plane when GBM advertises 2 plaens and V4L2 expects a + // single frame. + frame.layout.planes.pop(); + } + + (meta, frame) + }, + ); + + simple_encode_loop(&mut encoder, &mut frame_producer, coded_consumer).expect("encode loop"); + } +} diff --git a/vendor/cros-codecs/src/backend/vaapi.rs b/vendor/cros-codecs/src/backend/vaapi.rs new file mode 100644 index 0000000..58320b3 --- /dev/null +++ b/vendor/cros-codecs/src/backend/vaapi.rs @@ -0,0 +1,270 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! VAAPI backend for both stateless decoders and encoders. + +use std::collections::HashSet; +use std::fmt::Debug; +use std::os::fd::AsRawFd; + +use anyhow::anyhow; +use libva::Display; +use libva::VAConfigAttrib; +use libva::VAConfigAttribType; + +use crate::utils::DmabufFrame; +use crate::utils::UserPtrFrame; +use crate::DecodedFormat; + +pub mod decoder; +pub mod encoder; +pub mod surface_pool; + +#[allow(dead_code)] +fn va_rt_format_to_string(va_rt_format: u32) -> String { + String::from(match va_rt_format { + libva::VA_RT_FORMAT_YUV420 => "YUV420", + libva::VA_RT_FORMAT_YUV422 => "YUV422", + libva::VA_RT_FORMAT_YUV444 => "YUV444", + libva::VA_RT_FORMAT_YUV420_10 => "YUV420_10", + libva::VA_RT_FORMAT_YUV420_12 => "YUV420_12", + libva::VA_RT_FORMAT_YUV422_10 => "YUV422_10", + libva::VA_RT_FORMAT_YUV422_12 => "YUV422_12", + libva::VA_RT_FORMAT_YUV444_10 => "YUV444_10", + libva::VA_RT_FORMAT_YUV444_12 => "YUV444_12", + other => return format!("unknown VA rt_format {}", other), + }) +} + +#[allow(dead_code)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +struct FormatMap { + pub rt_format: u32, + pub va_fourcc: u32, + pub decoded_format: DecodedFormat, +} + +/// Maps a given VA_RT_FORMAT to a compatible decoded format in an arbitrary +/// preferred order. +#[allow(dead_code)] +const FORMAT_MAP: [FormatMap; 10] = [ + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV420, + va_fourcc: libva::VA_FOURCC_NV12, + decoded_format: DecodedFormat::NV12, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV420, + va_fourcc: libva::VA_FOURCC_I420, + decoded_format: DecodedFormat::I420, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV422, + va_fourcc: libva::VA_FOURCC_422H, + decoded_format: DecodedFormat::I422, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV444, + va_fourcc: libva::VA_FOURCC_444P, + decoded_format: DecodedFormat::I444, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV420_10, + va_fourcc: libva::VA_FOURCC_P010, + decoded_format: DecodedFormat::I010, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV420_12, + va_fourcc: libva::VA_FOURCC_P012, + decoded_format: DecodedFormat::I012, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV422_10, + va_fourcc: libva::VA_FOURCC_Y210, + decoded_format: DecodedFormat::I210, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV422_12, + va_fourcc: libva::VA_FOURCC_Y212, + decoded_format: DecodedFormat::I212, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV444_10, + va_fourcc: libva::VA_FOURCC_Y410, + decoded_format: DecodedFormat::I410, + }, + FormatMap { + rt_format: libva::VA_RT_FORMAT_YUV444_12, + va_fourcc: libva::VA_FOURCC_Y412, + decoded_format: DecodedFormat::I412, + }, +]; + +/// Returns a set of supported decoded formats given `rt_format` +#[allow(dead_code)] +fn supported_formats_for_rt_format( + display: &Display, + rt_format: u32, + profile: i32, + entrypoint: u32, + image_formats: &[libva::VAImageFormat], +) -> anyhow::Result> { + let mut attrs = + vec![VAConfigAttrib { type_: VAConfigAttribType::VAConfigAttribRTFormat, value: 0 }]; + + display.get_config_attributes(profile, entrypoint, &mut attrs)?; + + // See whether this RT_FORMAT is supported by the given VAProfile and + // VAEntrypoint pair. + if attrs[0].value == libva::VA_ATTRIB_NOT_SUPPORTED || attrs[0].value & rt_format == 0 { + return Err(anyhow!( + "rt_format {:?} not supported for profile {:?} and entrypoint {:?}", + rt_format, + profile, + entrypoint + )); + } + + let mut supported_formats = HashSet::new(); + + for format in FORMAT_MAP { + if format.rt_format == rt_format { + supported_formats.insert(format); + } + } + + // Only retain those that the hardware can actually map into. + supported_formats + .retain(|&entry| image_formats.iter().any(|fmt| fmt.fourcc == entry.va_fourcc)); + + Ok(supported_formats) +} + +impl TryFrom<&libva::VAImageFormat> for DecodedFormat { + type Error = anyhow::Error; + + fn try_from(value: &libva::VAImageFormat) -> Result { + match value.fourcc { + libva::VA_FOURCC_I420 => Ok(DecodedFormat::I420), + libva::VA_FOURCC_NV12 => Ok(DecodedFormat::NV12), + libva::VA_FOURCC_P010 => Ok(DecodedFormat::I010), + libva::VA_FOURCC_P012 => Ok(DecodedFormat::I012), + libva::VA_FOURCC_Y210 => Ok(DecodedFormat::I210), + libva::VA_FOURCC_Y212 => Ok(DecodedFormat::I212), + libva::VA_FOURCC_Y410 => Ok(DecodedFormat::I410), + libva::VA_FOURCC_Y412 => Ok(DecodedFormat::I412), + _ => Err(anyhow!("Unsupported format")), + } + } +} + +impl libva::ExternalBufferDescriptor for UserPtrFrame { + const MEMORY_TYPE: libva::MemoryType = libva::MemoryType::UserPtr; + type DescriptorAttribute = libva::VASurfaceAttribExternalBuffers; + + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute { + let pitches = self + .layout + .planes + .iter() + .map(|p| p.stride as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(); + let offsets = self + .layout + .planes + .iter() + .map(|p| p.offset as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(); + + libva::VASurfaceAttribExternalBuffers { + pixel_format: self.layout.format.0.into(), + width: self.layout.size.width, + height: self.layout.size.height, + data_size: self.mem_layout.size() as u32, + num_planes: self.layout.planes.len() as u32, + pitches, + offsets, + buffers: self.buffers.as_mut_ptr() as *mut _, + num_buffers: self.buffers.len() as u32, + flags: 0, + private_data: std::ptr::null_mut(), + } + } +} + +impl libva::ExternalBufferDescriptor for DmabufFrame { + const MEMORY_TYPE: libva::MemoryType = libva::MemoryType::DrmPrime2; + type DescriptorAttribute = libva::VADRMPRIMESurfaceDescriptor; + + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute { + let objects = self + .fds + .iter() + .map(|fd| libva::VADRMPRIMESurfaceDescriptorObject { + fd: fd.as_raw_fd(), + size: nix::sys::stat::fstat(fd.as_raw_fd()) + .map(|stat| stat.st_size as u32) + // If we don't have the information about the plane fd size, fallback to 0. + // Libva seems to be *sometimes* "happy" with zero. + .unwrap_or(0), + // TODO should the descriptor be moved to individual objects? + drm_format_modifier: self.layout.format.1, + }) + .chain(std::iter::repeat(Default::default())) + .take(4) + .collect::>() + .try_into() + .unwrap(); + + let layers = [ + libva::VADRMPRIMESurfaceDescriptorLayer { + drm_format: self.layout.format.0.into(), + num_planes: self.layout.planes.len() as u32, + object_index: [0, 0, 0, 0], + offset: self + .layout + .planes + .iter() + .map(|p| p.offset as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + pitch: self + .layout + .planes + .iter() + .map(|p| p.stride as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + }, + Default::default(), + Default::default(), + Default::default(), + ]; + + libva::VADRMPRIMESurfaceDescriptor { + // TODO should we match and use VA_FOURCC_* here? + fourcc: self.layout.format.0.into(), + width: self.layout.size.width, + height: self.layout.size.height, + num_objects: 1, + objects, + num_layers: 1, + layers, + } + } +} diff --git a/vendor/cros-codecs/src/backend/vaapi/decoder.rs b/vendor/cros-codecs/src/backend/vaapi/decoder.rs new file mode 100644 index 0000000..555a692 --- /dev/null +++ b/vendor/cros-codecs/src/backend/vaapi/decoder.rs @@ -0,0 +1,339 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; + +use anyhow::anyhow; +use anyhow::Context as AnyhowContext; +use libva::{ + Buffer, Context, Display, Picture, PictureEnd, PictureNew, PictureSync, Surface, + SurfaceMemoryDescriptor, VaError, +}; + +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::DecodedHandle as DecodedHandleTrait; +use crate::decoder::StreamInfo; +use crate::video_frame::VideoFrame; +use crate::DecodedFormat; +use crate::Rect; +use crate::Resolution; + +/// A decoded frame handle. +pub(crate) type DecodedHandle = Rc>>; + +/// Gets the VASurfaceID for the given `picture`. +pub(crate) fn va_surface_id( + handle: &Option>, +) -> libva::VASurfaceID { + match handle { + None => libva::VA_INVALID_SURFACE, + Some(handle) => handle.borrow().surface().id(), + } +} + +impl DecodedHandleTrait for DecodedHandle { + type Frame = V; + + fn video_frame(&self) -> Arc { + self.borrow().backing_frame.clone() + } + + fn coded_resolution(&self) -> Resolution { + self.borrow().surface().size().into() + } + + fn display_resolution(&self) -> Resolution { + self.borrow().display_resolution + } + + fn timestamp(&self) -> u64 { + self.borrow().timestamp() + } + + fn is_ready(&self) -> bool { + self.borrow().state.is_ready().unwrap_or(true) + } + + fn sync(&self) -> anyhow::Result<()> { + self.borrow_mut().sync().context("while syncing picture")?; + + Ok(()) + } +} + +/// A trait for providing the basic information needed to setup libva for decoding. +pub(crate) trait VaStreamInfo { + /// Returns the VA profile of the stream. + fn va_profile(&self) -> anyhow::Result; + /// Returns the RT format of the stream. + #[allow(dead_code)] + fn rt_format(&self) -> anyhow::Result; + /// Returns the minimum number of surfaces required to decode the stream. + fn min_num_surfaces(&self) -> usize; + /// Returns the coded size of the surfaces required to decode the stream. + fn coded_size(&self) -> Resolution; + /// Returns the visible rectangle within the coded size for the stream. + fn visible_rect(&self) -> Rect; +} + +/// Rendering state of a VA picture. +enum PictureState { + Ready(Picture>), + Pending(Picture>), + // Only set in sync when we take ownership of the VA picture. + Invalid, +} + +impl PictureState { + /// Make sure that all pending operations on the picture have completed. + fn sync(&mut self) -> Result<(), VaError> { + let res; + + (*self, res) = match std::mem::replace(self, PictureState::Invalid) { + state @ PictureState::Ready(_) => (state, Ok(())), + PictureState::Pending(picture) => match picture.sync() { + Ok(picture) => (PictureState::Ready(picture), Ok(())), + Err((e, picture)) => (PictureState::Pending(picture), Err(e)), + }, + PictureState::Invalid => unreachable!(), + }; + + res + } + + fn surface(&self) -> &Surface { + match self { + PictureState::Ready(picture) => picture.surface(), + PictureState::Pending(picture) => picture.surface(), + PictureState::Invalid => unreachable!(), + } + } + + fn timestamp(&self) -> u64 { + match self { + PictureState::Ready(picture) => picture.timestamp(), + PictureState::Pending(picture) => picture.timestamp(), + PictureState::Invalid => unreachable!(), + } + } + + fn is_ready(&self) -> Result { + match self { + PictureState::Ready(_) => Ok(true), + PictureState::Pending(picture) => picture + .surface() + .query_status() + .map(|s| s == libva::VASurfaceStatus::VASurfaceReady), + PictureState::Invalid => unreachable!(), + } + } + + fn new_from_same_surface(&self, timestamp: u64) -> Picture> { + match &self { + PictureState::Ready(picture) => Picture::new_from_same_surface(timestamp, picture), + PictureState::Pending(picture) => Picture::new_from_same_surface(timestamp, picture), + PictureState::Invalid => unreachable!(), + } + } +} + +/// VA-API backend handle. +/// +/// This includes the VA picture which can be pending rendering or complete, as well as useful +/// meta-information. +pub struct VaapiDecodedHandle { + backing_frame: Arc, + state: PictureState<::MemDescriptor>, + /// Actual resolution of the visible rectangle in the decoded buffer. + display_resolution: Resolution, +} + +impl VaapiDecodedHandle { + /// Creates a new pending handle on `surface_id`. + fn new(picture: VaapiPicture, display_resolution: Resolution) -> anyhow::Result { + let backing_frame = picture.backing_frame; + let picture = picture.picture.begin()?.render()?.end()?; + Ok(Self { + backing_frame: backing_frame, + state: PictureState::Pending(picture), + display_resolution: display_resolution, + }) + } + + fn sync(&mut self) -> Result<(), VaError> { + self.state.sync() + } + + /// Creates a new picture from the surface backing the current one. Useful for interlaced + /// decoding. TODO: Do we need this for other purposes? We don't intend to support interlaced. + pub(crate) fn new_picture_from_same_surface(&self, timestamp: u64) -> VaapiPicture { + VaapiPicture { + picture: self.state.new_from_same_surface(timestamp), + backing_frame: self.backing_frame.clone(), + } + } + + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): made public so a client can + // read frames back with vaGetImage. Mapping the client-allocated DMA-BUF + // directly is a 44 MB/s uncached PCIe read on a discrete GPU; the driver's own + // copy path is ~100x faster. + pub fn surface(&self) -> &Surface<::MemDescriptor> { + self.state.surface() + } + + /// Returns the timestamp of this handle. + fn timestamp(&self) -> u64 { + self.state.timestamp() + } +} + +pub struct VaapiBackend { + pub display: Rc, + pub context: Rc, + stream_info: StreamInfo, + // TODO: We should try to support context reuse + _supports_context_reuse: bool, + _phantom_data: PhantomData, +} + +impl VaapiBackend { + pub(crate) fn new(display: Rc, supports_context_reuse: bool) -> Self { + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): upstream probes with a + // 16x16 context, which Mesa radeonsi rejects with VA_STATUS_ERROR_UNIMPLEMENTED + // (measured: 16x16 and 48x48 fail, 64x64 up succeed), and the `expect` below + // then aborts. This placeholder is replaced by `new_sequence` anyway. + let init_stream_info = StreamInfo { + format: DecodedFormat::NV12, + coded_resolution: Resolution::from((64, 64)), + display_resolution: Resolution::from((64, 64)), + min_num_frames: 1, + }; + let config = display + .create_config( + vec![libva::VAConfigAttrib { + type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, + value: libva::VA_RT_FORMAT_YUV420, + }], + libva::VAProfile::VAProfileH264Main, + libva::VAEntrypoint::VAEntrypointVLD, + ) + .expect("Could not create initial VAConfig!"); + let context = display + .create_context::<::MemDescriptor>( + &config, + init_stream_info.coded_resolution.width, + init_stream_info.coded_resolution.height, + None, + true, + ) + .expect("Could not create initial VAContext!"); + Self { + display: display, + context: context, + _supports_context_reuse: supports_context_reuse, + stream_info: init_stream_info, + _phantom_data: Default::default(), + } + } + + pub(crate) fn new_sequence( + &mut self, + stream_params: &StreamData, + ) -> StatelessBackendResult<()> + where + for<'a> &'a StreamData: VaStreamInfo, + { + self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect()); + self.stream_info.coded_resolution = stream_params.coded_size().clone(); + self.stream_info.min_num_frames = stream_params.min_num_surfaces(); + + // TODO: Handle context re-use + // TODO: We should obtain RT_FORMAT from stream_info + let config = self + .display + .create_config( + vec![libva::VAConfigAttrib { + type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, + value: libva::VA_RT_FORMAT_YUV420, + }], + stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?, + libva::VAEntrypoint::VAEntrypointVLD, + ) + .map_err(|_| anyhow!("Could not create VAConfig!"))?; + let context = self + .display + .create_context::<::MemDescriptor>( + &config, + self.stream_info.coded_resolution.width, + self.stream_info.coded_resolution.height, + None, + true, + ) + .map_err(|_| anyhow!("Could not create VAContext!"))?; + self.context = context; + + Ok(()) + } + + pub(crate) fn process_picture( + &mut self, + picture: VaapiPicture, + ) -> StatelessBackendResult<::Handle> + where + Self: StatelessDecoderBackendPicture, + for<'a> &'a Codec::FormatInfo: VaStreamInfo, + { + Ok(Rc::new(RefCell::new(VaapiDecodedHandle::new( + picture, + self.stream_info.display_resolution.clone(), + )?))) + } +} + +/// Shortcut for pictures used for the VAAPI backend. +pub struct VaapiPicture { + picture: Picture>, + backing_frame: Arc, +} + +impl VaapiPicture { + pub fn new(timestamp: u64, context: Rc, backing_frame: V) -> Self { + let display = context.display(); + let surface = backing_frame + .to_native_handle(display) + .expect("Failed to export video frame to vaapi picture!") + .into(); + Self { + backing_frame: Arc::new(backing_frame), + picture: Picture::new(timestamp, context, surface), + } + } + + pub fn surface(&self) -> &Surface { + self.picture.surface() + } + + pub fn add_buffer(&mut self, buffer: Buffer) { + self.picture.add_buffer(buffer) + } +} + +impl StatelessDecoderBackend for VaapiBackend { + type Handle = DecodedHandle; + + fn stream_info(&self) -> Option<&StreamInfo> { + Some(&self.stream_info) + } + + fn reset_backend(&mut self) -> anyhow::Result<()> { + //TODO(bchoobineh): Implement VAAPI DRC + Ok(()) + } +} diff --git a/vendor/cros-codecs/src/backend/vaapi/encoder.rs b/vendor/cros-codecs/src/backend/vaapi/encoder.rs new file mode 100644 index 0000000..095c5b5 --- /dev/null +++ b/vendor/cros-codecs/src/backend/vaapi/encoder.rs @@ -0,0 +1,651 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::any::Any; +use std::marker::PhantomData; +use std::rc::Rc; + +use anyhow::anyhow; +use libva::Config; +use libva::Context; +use libva::Display; +use libva::EncCodedBuffer; +use libva::MappedCodedBuffer; +use libva::Picture; +use libva::PictureEnd; +use libva::Surface; +use libva::SurfaceMemoryDescriptor; +use libva::UsageHint; +use libva::VAEntrypoint::VAEntrypointEncSlice; +use libva::VAEntrypoint::VAEntrypointEncSliceLP; +use libva::VAProfile; +use libva::VASurfaceStatus; + +use crate::backend::vaapi::surface_pool::PooledVaSurface; +use crate::backend::vaapi::surface_pool::VaSurfacePool; +use crate::backend::vaapi::FORMAT_MAP; +use crate::decoder::FramePool; +use crate::encoder::stateless::BackendPromise; +use crate::encoder::stateless::StatelessBackendError; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessEncoderBackendImport; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::Tunings; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Resolution; + +/// The number of frames that encoder backend should initialize scratch pool with. +const INITIAL_SCRATCH_POOL_SIZE: usize = 16; +/// The maximum size of scratch pool size, after which the backend will refure to allocate more +/// scratch frames. +const MAX_SCRATCH_POOL_SIZE: usize = INITIAL_SCRATCH_POOL_SIZE * 4; + +impl From for StatelessBackendError { + fn from(value: libva::VaError) -> Self { + Self::Other(value.into()) + } +} + +pub(crate) fn tunings_to_libva_rc( + tunings: &Tunings, +) -> StatelessBackendResult { + let bits_per_second = tunings.rate_control.bitrate_target().unwrap_or(0); + let bits_per_second = u32::try_from(bits_per_second).map_err(|e| anyhow::anyhow!(e))?; + + // At the moment we don't support variable bitrate therefore target 100% + const TARGET_PERCENTAGE: u32 = 100; + + // Window size in ms that the RC should apply to + const WINDOW_SIZE: u32 = 1_500; + + // Clamp minium QP + let min_qp = tunings.min_quality.clamp(CLAMP_MIN_QP, CLAMP_MAX_QP); + + let basic_unit_size = 0; + + // Don't reset the rate controller + const RESET: u32 = 0; + + // Don't skip frames + const DISABLE_FRAME_SKIP: u32 = 1; + + // Allow bit stuffing + const DISABLE_BIT_STUFFING: u32 = 0; + + // Use default + const MB_RATE_CONTROL: u32 = 0; + + // SVC encoding is not supported for now + const TEMPORAL_ID: u32 = 0; + + // Don't ensure intraframe size + const CFS_I_FRAMES: u32 = 0; + + // We don't use hierarchical B frames currently + const ENABLE_PARALLEL_BRC: u32 = 0; + + // Disable dynamic scaling + const ENABLE_DYNAMIC_SCALING: u32 = 0; + + // Use default tolerance mode + const FRAME_TOLERANCE_MODE: u32 = 0; + + // ICQ mode is not used + const ICQ_QUALITY_FACTOR: u32 = 0; + + // Clamp maximum QP + let max_qp = tunings.max_quality.clamp(CLAMP_MIN_QP, CLAMP_MAX_QP); + + // Unsed + const QUALITY_FACTOR: u32 = 0; + + // No limits + const TARGET_FRAME_SIZE: u32 = 0; + + // If ConstantQuality is used then set to it's value, otherwise use middle + let initial_qp = match tunings.rate_control { + RateControl::ConstantQuality(qp) => qp.clamp(min_qp, max_qp), + _ => (min_qp + max_qp) / 2, + }; + + Ok(libva::EncMiscParameterRateControl::new( + bits_per_second, + TARGET_PERCENTAGE, + WINDOW_SIZE, + initial_qp, + min_qp, + basic_unit_size, + libva::RcFlags::new( + RESET, + DISABLE_FRAME_SKIP, + DISABLE_BIT_STUFFING, + MB_RATE_CONTROL, + TEMPORAL_ID, + CFS_I_FRAMES, + ENABLE_PARALLEL_BRC, + ENABLE_DYNAMIC_SCALING, + FRAME_TOLERANCE_MODE, + ), + ICQ_QUALITY_FACTOR, + max_qp, + QUALITY_FACTOR, + TARGET_FRAME_SIZE, + )) +} + +pub struct Reconstructed(PooledVaSurface<()>); + +impl Reconstructed { + pub(crate) fn surface(&self) -> &Surface<()> { + use std::borrow::Borrow; + Borrow::>::borrow(&self.0) + } + + pub(crate) fn surface_id(&self) -> u32 { + self.surface().id() + } +} + +pub struct VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow> + 'static, +{ + /// VA config. + #[allow(dead_code)] + va_config: Config, + + /// VA context used for encoding. + context: Rc, + + _va_profile: VAProfile::Type, + scratch_pool: VaSurfacePool<()>, + _phantom: PhantomData<(M, H)>, +} + +impl VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow>, +{ + pub fn new( + display: Rc, + va_profile: VAProfile::Type, + fourcc: Fourcc, + coded_size: Resolution, + bitrate_control: u32, + low_power: bool, + ) -> StatelessBackendResult { + let format_map = FORMAT_MAP + .iter() + .find(|&map| map.va_fourcc == fourcc.0) + .ok_or_else(|| StatelessBackendError::UnsupportedFormat)?; + + let rt_format = format_map.rt_format; + + let va_config = display.create_config( + vec![ + libva::VAConfigAttrib { + type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, + value: rt_format, + }, + libva::VAConfigAttrib { + type_: libva::VAConfigAttribType::VAConfigAttribRateControl, + value: bitrate_control, + }, + ], + va_profile, + if low_power { VAEntrypointEncSliceLP } else { VAEntrypointEncSlice }, + )?; + + let context = display.create_context::( + &va_config, + coded_size.width, + coded_size.height, + None, + true, + )?; + + let mut scratch_pool = VaSurfacePool::new( + Rc::clone(&display), + rt_format, + Some(UsageHint::USAGE_HINT_ENCODER), + coded_size, + ); + + // TODO: Allow initial size to be changed + scratch_pool.add_frames(vec![(); INITIAL_SCRATCH_POOL_SIZE])?; + + Ok(Self { + va_config, + context, + scratch_pool, + _va_profile: va_profile, + _phantom: Default::default(), + }) + } + + pub(crate) fn context(&self) -> &Rc { + &self.context + } + + pub(crate) fn new_coded_buffer( + &self, + rate_control: &RateControl, + ) -> StatelessBackendResult { + // Coded buffer size multiplier. It's inteded to give head room for the encoder. + const CODED_SIZE_MUL: usize = 2; + + // Default coded buffer size if bitrate control is not used. + const DEFAULT_CODED_SIZE: usize = 1_500_000; + + let coded_size = rate_control + .bitrate_target() + .map(|e| e as usize * CODED_SIZE_MUL) + .unwrap_or(DEFAULT_CODED_SIZE); + + Ok(self.context().create_enc_coded(coded_size)?) + } + + // Creates an empty surface that will be filled with reconstructed picture during encoding + // which will be later used as frame reference + pub(crate) fn new_scratch_picture(&mut self) -> StatelessBackendResult { + if self.scratch_pool.num_free_frames() == 0 { + if self.scratch_pool.num_managed_frames() >= MAX_SCRATCH_POOL_SIZE { + log::error!("Scratch pool is exhausted and hit the size limit"); + return Err(StatelessBackendError::OutOfResources); + } + + log::debug!( + "Scratch pool empty, allocating one more surface. (previous pool size: {})", + self.scratch_pool.num_managed_frames() + ); + self.scratch_pool.add_frames(vec![()])?; + } + + let surface = + self.scratch_pool.get_surface().ok_or(StatelessBackendError::OutOfResources)?; + + Ok(Reconstructed(surface)) + } +} + +impl StatelessEncoderBackendImport for VaapiBackend +where + M: SurfaceMemoryDescriptor, + Handle: std::borrow::Borrow>, +{ + fn import_picture( + &mut self, + _metadata: &FrameMetadata, + handle: Handle, + ) -> StatelessBackendResult { + Ok(handle) + } +} + +impl StatelessEncoderBackendImport> + for VaapiBackend> +{ + fn import_picture( + &mut self, + _metadata: &FrameMetadata, + handle: V, + ) -> StatelessBackendResult> { + Ok(handle.to_native_handle(self.context.display()).map_err(|err| anyhow!(err))?.into()) + } +} + +/// Vaapi's implementation of [`crate::encoder::stateless::BackendPromise`] +pub struct CodedOutputPromise +where + M: SurfaceMemoryDescriptor, + P: std::borrow::Borrow>, +{ + /// Currently processed picture/surface. + handle: Picture, + + /// Hold reference frames/object from being dropped while `handle` is processed. + references: Vec>, + + // VaBuffer where the coded output will be present after processing + // is finished. + coded_buf: EncCodedBuffer, + + /// Container for the request output. Moved from + /// [`crate::encoder::stateless::StatelessVideoEncoderBackend`] request. The output will be + /// appended to it. + coded_output: Vec, + + _phantom: PhantomData, +} + +impl CodedOutputPromise +where + M: SurfaceMemoryDescriptor, + P: std::borrow::Borrow>, +{ + pub fn new( + handle: Picture, + references: Vec>, + coded_buf: EncCodedBuffer, + coded_output: Vec, + ) -> Self { + Self { handle, references, coded_buf, coded_output, _phantom: Default::default() } + } +} + +impl BackendPromise for CodedOutputPromise +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow>, +{ + type Output = Vec; + + fn sync(mut self) -> StatelessBackendResult { + if let Err((err, _)) = self.handle.sync() { + // TODO consider going back to PictureEnd + return Err(err.into()); + } + + // Drop all references as processing is finished + self.references.clear(); + + // Map coded buffer and collect bitstream + let coded = MappedCodedBuffer::new(&self.coded_buf)?; + let mut bitstream = self.coded_output; + for segment in coded.segments() { + // TODO: Handle flags? + // NOTE: on flags: 0-7 bits are average QP value + if segment.bit_offset > 0 { + log::warn!("unsupported bit_offset != 0 (yet)"); + } + bitstream.extend(segment.buf) + } + + Ok(bitstream) + } + + fn is_ready(&self) -> bool { + match self.handle.surface().query_status() { + Ok(status) => status == VASurfaceStatus::VASurfaceReady, + Err(_) => { + // An error occurred while processing or checking the status of the underlying + // processing, in both cases consider it is done. In either cases it will be + // returned with [`sync`]. + true + } + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use std::borrow::Borrow; + + use libva::VA_FOURCC_NV12; + use libva::VA_FOURCC_P010; + + use super::*; + use crate::encoder::tests::fill_test_frame_nv12; + use crate::encoder::tests::fill_test_frame_p010; + use crate::encoder::tests::get_test_frame_t; + use crate::encoder::FrameMetadata; + use crate::FrameLayout; + + fn map_surface<'a, M: SurfaceMemoryDescriptor>( + display: &Rc, + surface: &'a Surface, + fourcc: u32, + ) -> libva::Image<'a> { + let image_fmts = display.query_image_formats().unwrap(); + let image_fmt = image_fmts.into_iter().find(|f| f.fourcc == fourcc).unwrap(); + + libva::Image::create_from(surface, image_fmt, surface.size(), surface.size()).unwrap() + } + + fn map_surface_nv12<'a, M: SurfaceMemoryDescriptor>( + display: &Rc, + surface: &'a Surface, + ) -> libva::Image<'a> { + map_surface(display, surface, VA_FOURCC_NV12) + } + + fn map_surface_p010<'a, M: SurfaceMemoryDescriptor>( + display: &Rc, + surface: &'a Surface, + ) -> libva::Image<'a> { + map_surface(display, surface, VA_FOURCC_P010) + } + + /// Uploads raw NV12 to Surface + pub fn upload_nv12_img( + display: &Rc, + surface: &Surface, + width: u32, + height: u32, + data: &[u8], + ) { + let mut image = map_surface_nv12(display, surface); + + let va_image = *image.image(); + let dest = image.as_mut(); + let width = width as usize; + let height = height as usize; + + let mut src: &[u8] = data; + let mut dst = &mut dest[va_image.offsets[0] as usize..]; + + // Copy luma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[0] as usize..]; + src = &src[width..]; + } + + // Advance to the offset of the chroma plane + let mut src = &data[width * height..]; + let mut dst = &mut dest[va_image.offsets[1] as usize..]; + + let height = height / 2; + + // Copy chroma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[1] as usize..]; + src = &src[width..]; + } + + surface.sync().unwrap(); + drop(image); + } + + /// Helper struct. [`Iterator`] to fetch frames from [`SurfacePool`]. + pub struct PooledFrameIterator { + counter: u64, + display: Rc, + pool: VaSurfacePool<()>, + frame_layout: FrameLayout, + } + + impl PooledFrameIterator { + pub fn new( + display: Rc, + pool: VaSurfacePool<()>, + frame_layout: FrameLayout, + ) -> Self { + Self { counter: 0, display, pool, frame_layout } + } + } + + impl Iterator for PooledFrameIterator { + type Item = (FrameMetadata, PooledVaSurface<()>); + + fn next(&mut self) -> Option { + let handle = self.pool.get_surface().unwrap(); + + let meta = FrameMetadata { + layout: self.frame_layout.clone(), + force_keyframe: false, + timestamp: self.counter, + }; + + self.counter += 1; + + Some((meta, handle)) + } + } + + /// Helper struct. Uses [`Iterator`] with raw chunks and uploads to pooled surface from + /// [`SurfacePool`] to produce frames. + pub struct NV12FrameProducer<'l, I> + where + I: Iterator, + { + raw_iterator: I, + pool_iter: PooledFrameIterator, + } + + impl<'l, I> NV12FrameProducer<'l, I> + where + I: Iterator, + { + #[allow(dead_code)] + pub fn new( + raw_iterator: I, + display: Rc, + pool: VaSurfacePool<()>, + frame_layout: FrameLayout, + ) -> Self { + Self { raw_iterator, pool_iter: PooledFrameIterator::new(display, pool, frame_layout) } + } + } + + impl<'l, I> Iterator for NV12FrameProducer<'l, I> + where + I: Iterator, + { + type Item = (FrameMetadata, PooledVaSurface<()>); + + fn next(&mut self) -> Option { + let raw = match self.raw_iterator.next() { + Some(raw) => raw, + None => return None, + }; + + let (meta, handle) = self.pool_iter.next().unwrap(); + + let width = meta.layout.size.width; + let height = meta.layout.size.height; + debug_assert_eq!((width * height + width * height / 2) as usize, raw.len()); + + upload_nv12_img(&self.pool_iter.display, handle.borrow(), width, height, raw); + + Some((meta, handle)) + } + } + + pub fn upload_test_frame_nv12( + display: &Rc, + surface: &Surface, + t: f32, + ) { + let mut image = map_surface_nv12(display, surface); + + let (width, height) = image.display_resolution(); + + let offsets = image.image().offsets; + let pitches = image.image().pitches; + + fill_test_frame_nv12( + width as usize, + height as usize, + [pitches[0] as usize, pitches[1] as usize], + [offsets[0] as usize, offsets[1] as usize], + t, + image.as_mut(), + ); + + drop(image); + surface.sync().unwrap(); + } + + pub fn upload_test_frame_p010( + display: &Rc, + surface: &Surface, + t: f32, + ) { + let mut image = map_surface_p010(display, surface); + + let (width, height) = image.display_resolution(); + + let offsets = image.image().offsets; + let pitches = image.image().pitches; + + fill_test_frame_p010( + width as usize, + height as usize, + [pitches[0] as usize, pitches[1] as usize], + [offsets[0] as usize, offsets[1] as usize], + t, + image.as_mut(), + ); + + drop(image); + surface.sync().unwrap(); + } + + /// Helper struct. Procedurally generate NV12 frames for test purposes. + pub struct TestFrameGenerator { + counter: u64, + max_count: u64, + pool_iter: PooledFrameIterator, + display: Rc, + fourcc: Fourcc, + } + + impl TestFrameGenerator { + pub fn new( + max_count: u64, + display: Rc, + pool: VaSurfacePool<()>, + frame_layout: FrameLayout, + ) -> Self { + Self { + counter: 0, + max_count, + fourcc: frame_layout.format.0, + pool_iter: PooledFrameIterator::new(display.clone(), pool, frame_layout), + display, + } + } + } + + impl Iterator for TestFrameGenerator { + type Item = (FrameMetadata, PooledVaSurface<()>); + + fn next(&mut self) -> Option { + if self.counter > self.max_count { + return None; + } + + self.counter += 1; + + let (meta, handle) = self.pool_iter.next().unwrap(); + + let surface: &Surface<()> = handle.borrow(); + + let t = get_test_frame_t(meta.timestamp, self.max_count); + match self.fourcc.0 { + VA_FOURCC_NV12 => upload_test_frame_nv12(&self.display, surface, t), + VA_FOURCC_P010 => upload_test_frame_p010(&self.display, surface, t), + _ => unreachable!(), + } + + Some((meta, handle)) + } + } +} diff --git a/vendor/cros-codecs/src/backend/vaapi/surface_pool.rs b/vendor/cros-codecs/src/backend/vaapi/surface_pool.rs new file mode 100644 index 0000000..a04ae91 --- /dev/null +++ b/vendor/cros-codecs/src/backend/vaapi/surface_pool.rs @@ -0,0 +1,225 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Borrow; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::collections::VecDeque; +use std::rc::Rc; +use std::rc::Weak; + +use libva::Display; +use libva::Surface; +use libva::SurfaceMemoryDescriptor; +use libva::VASurfaceID; + +use crate::decoder::FramePool; +use crate::Resolution; + +/// A VA Surface obtained from a `[SurfacePool]`. +/// +/// The surface will automatically be returned to its pool upon dropping, provided the pool still +/// exists and the surface is still compatible with it. +pub struct PooledVaSurface { + surface: Option>, + pool: Weak>>, +} + +impl PooledVaSurface { + fn new(surface: Surface, pool: &Rc>>) -> Self { + Self { surface: Some(surface), pool: Rc::downgrade(pool) } + } + + /// Detach this surface from the pool. It will not be returned, and we can dispose of it + /// freely. + pub fn detach_from_pool(mut self) -> Surface { + // `unwrap` will never fail as `surface` is `Some` up to this point. + let surface = self.surface.take().unwrap(); + + if let Some(pool) = self.pool.upgrade() { + (*pool).borrow_mut().managed_surfaces.remove(&surface.id()); + } + + surface + } +} + +impl Borrow> for PooledVaSurface { + fn borrow(&self) -> &Surface { + // `unwrap` will never fail as `surface` is `Some` until the object is dropped. + self.surface.as_ref().unwrap() + } +} + +impl AsRef for PooledVaSurface { + fn as_ref(&self) -> &M { + >>::borrow(self).as_ref() + } +} + +impl Drop for PooledVaSurface { + fn drop(&mut self) { + // If the surface has not been detached... + if let Some(surface) = self.surface.take() { + // ... and the pool still exists... + if let Some(pool) = self.pool.upgrade() { + let mut pool_borrowed = (*pool).borrow_mut(); + // ... and the pool is still managing this surface, return it. + if pool_borrowed.managed_surfaces.contains_key(&surface.id()) { + pool_borrowed.surfaces.push_back(surface); + return; + } + } + + // The surface cannot be returned to the pool and can be gracefully dropped. + log::debug!("Dropping stale surface: {}, ({:?})", surface.id(), surface.size()) + } + } +} + +struct VaSurfacePoolInner { + display: Rc, + rt_format: u32, + usage_hint: Option, + coded_resolution: Resolution, + surfaces: VecDeque>, + /// All the surfaces managed by this pool, indexed by their surface ID. We keep their + /// resolution so we can remove them in case of a coded resolution change even if they + /// are currently borrowed. + managed_surfaces: BTreeMap, +} + +/// A surface pool to reduce the number of costly Surface allocations. +/// +/// The pool only houses Surfaces that fits the pool's coded resolution. +/// Stale surfaces are dropped when either the pool resolution changes, or when +/// stale surfaces are retrieved. +/// +/// This means that this pool is suitable for inter-frame DRC, as the stale +/// surfaces will gracefully be dropped, which is arguably better than the +/// alternative of having more than one pool active at a time. +pub struct VaSurfacePool { + inner: Rc>>, +} + +impl VaSurfacePool { + /// Add a surface to the pool. + /// + /// This can be an entirely new surface, or one that has been previously obtained using + /// `get_surface` and is returned. + /// + /// Returns an error (and the passed `surface` back) if the surface is not at least as + /// large as the current coded resolution of the pool. + #[allow(dead_code)] + fn add_surface(&mut self, surface: Surface) -> Result<(), Surface> { + let mut inner = (*self.inner).borrow_mut(); + + if Resolution::from(surface.size()).can_contain(inner.coded_resolution) { + inner.managed_surfaces.insert(surface.id(), surface.size().into()); + inner.surfaces.push_back(surface); + Ok(()) + } else { + Err(surface) + } + } + + /// Create a new pool. + /// + // # Arguments + /// + /// * `display` - the VA display to create the surfaces from. + /// * `rt_format` - the VA RT format to use for the surfaces. + /// * `usage_hint` - hint about how the surfaces from this pool will be used. + /// * `coded_resolution` - resolution of the surfaces. + pub fn new( + display: Rc, + rt_format: u32, + usage_hint: Option, + coded_resolution: Resolution, + ) -> Self { + Self { + inner: Rc::new(RefCell::new(VaSurfacePoolInner { + display, + rt_format, + usage_hint, + coded_resolution, + surfaces: VecDeque::new(), + managed_surfaces: Default::default(), + })), + } + } + + /// Gets a free surface from the pool. + pub fn get_surface(&mut self) -> Option> { + let mut inner = (*self.inner).borrow_mut(); + let surface = inner.surfaces.pop_front(); + + // Make sure the invariant holds when debugging. Can save costly + // debugging time during future refactors, if any. + debug_assert!({ + match surface.as_ref() { + Some(s) => Resolution::from(s.size()).can_contain(inner.coded_resolution), + None => true, + } + }); + + surface.map(|s| PooledVaSurface::new(s, &self.inner)) + } +} + +impl FramePool for VaSurfacePool { + type Descriptor = M; + + fn coded_resolution(&self) -> Resolution { + (*self.inner).borrow().coded_resolution + } + + fn set_coded_resolution(&mut self, resolution: Resolution) { + let mut inner = (*self.inner).borrow_mut(); + + inner.coded_resolution = resolution; + inner.managed_surfaces.retain(|_, res| res.can_contain(resolution)); + inner.surfaces.retain(|s| Resolution::from(s.size()).can_contain(resolution)); + } + + fn add_frames(&mut self, descriptors: Vec) -> Result<(), anyhow::Error> { + let mut inner = (*self.inner).borrow_mut(); + + let surfaces = inner + .display + .create_surfaces( + inner.rt_format, + // Let the hardware decide the best internal format - we will get the desired fourcc + // when creating the image. + None, + inner.coded_resolution.width, + inner.coded_resolution.height, + inner.usage_hint, + descriptors, + ) + .map_err(|e| anyhow::anyhow!(e))?; + + for surface in &surfaces { + inner.managed_surfaces.insert(surface.id(), surface.size().into()); + } + inner.surfaces.extend(surfaces); + + Ok(()) + } + + fn num_free_frames(&self) -> usize { + (*self.inner).borrow().surfaces.len() + } + + fn num_managed_frames(&self) -> usize { + (*self.inner).borrow().managed_surfaces.len() + } + + fn clear(&mut self) { + let mut pool = (*self.inner).borrow_mut(); + + pool.surfaces.clear(); + pool.managed_surfaces.clear(); + } +} diff --git a/vendor/cros-codecs/src/bitstream_utils.rs b/vendor/cros-codecs/src/bitstream_utils.rs new file mode 100644 index 0000000..d9ac031 --- /dev/null +++ b/vendor/cros-codecs/src/bitstream_utils.rs @@ -0,0 +1,768 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Cow; +use std::fmt; +use std::io::Cursor; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::marker::PhantomData; + +use crate::codec::h264::parser::Nalu as H264Nalu; +use crate::codec::h265::parser::Nalu as H265Nalu; + +/// A bit reader for codec bitstreams. It properly handles emulation-prevention +/// bytes and stop bits for H264. +#[derive(Clone)] +pub(crate) struct BitReader<'a> { + /// A reference into the next unread byte in the stream. + data: Cursor<&'a [u8]>, + /// Contents of the current byte. First unread bit starting at position 8 - + /// num_remaining_bits_in_curr_bytes. + curr_byte: u8, + /// Number of bits remaining in `curr_byte` + num_remaining_bits_in_curr_byte: usize, + /// Used in emulation prevention byte detection. + prev_two_bytes: u16, + /// Number of emulation prevention bytes (i.e. 0x000003) we found. + num_epb: usize, + /// Whether or not we need emulation prevention logic. + needs_epb: bool, + /// How many bits have been read so far. + position: u64, +} + +#[derive(Debug)] +pub(crate) enum GetByteError { + OutOfBits, +} + +impl fmt::Display for GetByteError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "reader ran out of bits") + } +} + +#[derive(Debug)] +pub(crate) enum ReadBitsError { + TooManyBitsRequested(usize), + GetByte(GetByteError), + ConversionFailed, +} + +impl fmt::Display for ReadBitsError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ReadBitsError::TooManyBitsRequested(bits) => { + write!(f, "more than 31 ({}) bits were requested", bits) + } + ReadBitsError::GetByte(_) => write!(f, "failed to advance the current byte"), + ReadBitsError::ConversionFailed => { + write!(f, "failed to convert read input to target type") + } + } + } +} + +impl From for ReadBitsError { + fn from(err: GetByteError) -> Self { + ReadBitsError::GetByte(err) + } +} + +impl<'a> BitReader<'a> { + pub fn new(data: &'a [u8], needs_epb: bool) -> Self { + Self { + data: Cursor::new(data), + curr_byte: Default::default(), + num_remaining_bits_in_curr_byte: Default::default(), + prev_two_bytes: 0xffff, + num_epb: Default::default(), + needs_epb: needs_epb, + position: 0, + } + } + + /// Read a single bit from the stream. + pub fn read_bit(&mut self) -> Result { + let bit = self.read_bits::(1)?; + match bit { + 1 => Ok(true), + 0 => Ok(false), + _ => panic!("Unexpected value {}", bit), + } + } + + /// Read up to 31 bits from the stream. Note that we don't want to read 32 + /// bits even though we're returning a u32 because that would break the + /// read_bits_signed() function. 31 bits should be overkill for compressed + /// header parsing anyway. + pub fn read_bits>(&mut self, num_bits: usize) -> Result { + if num_bits > 31 { + return Err(ReadBitsError::TooManyBitsRequested(num_bits).to_string()); + } + + let mut bits_left = num_bits; + let mut out = 0u32; + + while self.num_remaining_bits_in_curr_byte < bits_left { + out |= (self.curr_byte as u32) << (bits_left - self.num_remaining_bits_in_curr_byte); + bits_left -= self.num_remaining_bits_in_curr_byte; + self.move_to_next_byte().map_err(|err| err.to_string())?; + } + + out |= (self.curr_byte >> (self.num_remaining_bits_in_curr_byte - bits_left)) as u32; + out &= (1 << num_bits) - 1; + self.num_remaining_bits_in_curr_byte -= bits_left; + self.position += num_bits as u64; + + U::try_from(out).map_err(|_| ReadBitsError::ConversionFailed.to_string()) + } + + /// Reads a two's complement signed integer of length |num_bits|. + pub fn read_bits_signed>(&mut self, num_bits: usize) -> Result { + let mut out: i32 = self + .read_bits::(num_bits)? + .try_into() + .map_err(|_| ReadBitsError::ConversionFailed.to_string())?; + if out >> (num_bits - 1) != 0 { + out |= -1i32 ^ ((1 << num_bits) - 1); + } + + U::try_from(out).map_err(|_| ReadBitsError::ConversionFailed.to_string()) + } + + /// Reads an unsigned integer from the stream and checks if the stream is byte aligned. + pub fn read_bits_aligned>(&mut self, num_bits: usize) -> Result { + if self.num_remaining_bits_in_curr_byte % 8 != 0 { + return Err("Attempted unaligned read_le()".into()); + } + + Ok(self.read_bits(num_bits).map_err(|err| err.to_string())?) + } + + /// Skip `num_bits` bits from the stream. + pub fn skip_bits(&mut self, mut num_bits: usize) -> Result<(), String> { + while num_bits > 0 { + let n = std::cmp::min(num_bits, 31); + self.read_bits::(n)?; + num_bits -= n; + } + + Ok(()) + } + + /// Returns the amount of bits left in the stream + pub fn num_bits_left(&mut self) -> usize { + let cur_pos = self.data.position(); + // This should always be safe to unwrap. + let end_pos = self.data.seek(SeekFrom::End(0)).unwrap(); + let _ = self.data.seek(SeekFrom::Start(cur_pos)); + ((end_pos - cur_pos) as usize) * 8 + self.num_remaining_bits_in_curr_byte + } + + /// Returns the number of emulation-prevention bytes read so far. + pub fn num_epb(&self) -> usize { + self.num_epb + } + + /// Whether the stream still has RBSP data. Implements more_rbsp_data(). See + /// the spec for more details. + pub fn has_more_rsbp_data(&mut self) -> bool { + if self.num_remaining_bits_in_curr_byte == 0 && self.move_to_next_byte().is_err() { + // no more data at all in the rbsp + return false; + } + + // If the next bit is the stop bit, then we should only see unset bits + // until the end of the data. + if (self.curr_byte & ((1 << (self.num_remaining_bits_in_curr_byte - 1)) - 1)) != 0 { + return true; + } + + let mut buf = [0u8; 1]; + let orig_pos = self.data.position(); + while let Ok(_) = self.data.read_exact(&mut buf) { + if buf[0] != 0 { + self.data.set_position(orig_pos); + return true; + } + } + false + } + + /// Reads an Unsigned Exponential golomb coding number from the next bytes in the + /// bitstream. This may advance the state of position within the bitstream even if the + /// read operation is unsuccessful. See H264 Annex B specification 9.1 for details. + pub fn read_ue>(&mut self) -> Result { + let mut num_bits = 0; + + while self.read_bits::(1)? == 0 { + num_bits += 1; + if num_bits > 31 { + return Err("invalid stream".into()); + } + } + + let value = ((1u32 << num_bits) - 1) + .checked_add(self.read_bits::(num_bits)?) + .ok_or::("read number cannot fit in 32 bits".into())?; + + U::try_from(value).map_err(|_| "conversion error".into()) + } + + pub fn read_ue_bounded>(&mut self, min: u32, max: u32) -> Result { + let ue = self.read_ue()?; + if ue > max || ue < min { + Err(format!("Value out of bounds: expected {} - {}, got {}", min, max, ue)) + } else { + Ok(U::try_from(ue).map_err(|_| String::from("Conversion error"))?) + } + } + + pub fn read_ue_max>(&mut self, max: u32) -> Result { + self.read_ue_bounded(0, max) + } + + /// Reads a signed exponential golomb coding number. Instead of using two's + /// complement, this scheme maps even integers to positive numbers and odd + /// integers to negative numbers. The least significant bit indicates the + /// sign. See H264 Annex B specification 9.1.1 for details. + pub fn read_se>(&mut self) -> Result { + let ue = self.read_ue::()? as i32; + + if ue % 2 == 0 { + Ok(U::try_from(-(ue / 2)).map_err(|_| String::from("Conversion error"))?) + } else { + Ok(U::try_from(ue / 2 + 1).map_err(|_| String::from("Conversion error"))?) + } + } + + pub fn read_se_bounded>(&mut self, min: i32, max: i32) -> Result { + let se = self.read_se()?; + if se < min || se > max { + Err(format!("Value out of bounds, expected between {}-{}, got {}", min, max, se)) + } else { + Ok(U::try_from(se).map_err(|_| String::from("Conversion error"))?) + } + } + + /// Read little endian multi-byte integer. + pub fn read_le>(&mut self, num_bits: u8) -> Result { + let mut t = 0; + + for i in 0..num_bits { + let byte = self.read_bits_aligned::(8)?; + t += byte << (i * 8) + } + + Ok(U::try_from(t).map_err(|_| String::from("Conversion error"))?) + } + + /// Return the position of this bitstream in bits. + pub fn position(&self) -> u64 { + self.position + } + + fn get_byte(&mut self) -> Result { + let mut buf = [0u8; 1]; + self.data.read_exact(&mut buf).map_err(|_| GetByteError::OutOfBits)?; + Ok(buf[0]) + } + + fn move_to_next_byte(&mut self) -> Result<(), GetByteError> { + let mut byte = self.get_byte()?; + + if self.needs_epb { + if self.prev_two_bytes == 0 && byte == 0x03 { + // We found an epb + self.num_epb += 1; + // Read another byte + byte = self.get_byte()?; + // We need another 3 bytes before another epb can happen. + self.prev_two_bytes = 0xffff; + } + self.prev_two_bytes = (self.prev_two_bytes << 8) | u16::from(byte); + } + + self.num_remaining_bits_in_curr_byte = 8; + self.curr_byte = byte; + Ok(()) + } +} + +/// Iterator over IVF packets. +pub struct IvfIterator<'a> { + cursor: Cursor<&'a [u8]>, +} + +impl<'a> IvfIterator<'a> { + pub fn new(data: &'a [u8]) -> Self { + let mut cursor = Cursor::new(data); + + // Skip the IVH header entirely. + cursor.seek(std::io::SeekFrom::Start(32)).unwrap(); + + Self { cursor } + } +} + +impl<'a> Iterator for IvfIterator<'a> { + type Item = &'a [u8]; + + fn next(&mut self) -> Option { + // Make sure we have a header. + let mut len_buf = [0u8; 4]; + self.cursor.read_exact(&mut len_buf).ok()?; + let len = ((len_buf[3] as usize) << 24) + | ((len_buf[2] as usize) << 16) + | ((len_buf[1] as usize) << 8) + | (len_buf[0] as usize); + + // Skip PTS. + self.cursor.seek(std::io::SeekFrom::Current(8)).ok()?; + + let start = self.cursor.position() as usize; + let _ = self.cursor.seek(std::io::SeekFrom::Current(len as i64)).ok()?; + let end = self.cursor.position() as usize; + + Some(&self.cursor.get_ref()[start..end]) + } +} + +/// Helper struct for synthesizing IVF file header +pub struct IvfFileHeader { + pub magic: [u8; 4], + pub version: u16, + pub header_size: u16, + pub codec: [u8; 4], + pub width: u16, + pub height: u16, + pub framerate: u32, + pub timescale: u32, + pub frame_count: u32, + pub unused: u32, +} + +impl Default for IvfFileHeader { + fn default() -> Self { + Self { + magic: Self::MAGIC, + version: 0, + header_size: 32, + codec: Self::CODEC_VP9, + width: 320, + height: 240, + framerate: 1, + timescale: 1000, + frame_count: 1, + unused: Default::default(), + } + } +} + +impl IvfFileHeader { + pub const MAGIC: [u8; 4] = *b"DKIF"; + pub const CODEC_VP8: [u8; 4] = *b"VP80"; + pub const CODEC_VP9: [u8; 4] = *b"VP90"; + pub const CODEC_AV1: [u8; 4] = *b"AV01"; + + pub fn new(codec: [u8; 4], width: u16, height: u16, framerate: u32, frame_count: u32) -> Self { + let default = Self::default(); + + Self { + codec, + width, + height, + framerate: framerate * default.timescale, + frame_count, + ..default + } + } +} + +impl IvfFileHeader { + /// Writes header into writer + pub fn writo_into(&self, writer: &mut impl std::io::Write) -> std::io::Result<()> { + writer.write_all(&self.magic)?; + writer.write_all(&self.version.to_le_bytes())?; + writer.write_all(&self.header_size.to_le_bytes())?; + writer.write_all(&self.codec)?; + writer.write_all(&self.width.to_le_bytes())?; + writer.write_all(&self.height.to_le_bytes())?; + writer.write_all(&self.framerate.to_le_bytes())?; + writer.write_all(&self.timescale.to_le_bytes())?; + writer.write_all(&self.frame_count.to_le_bytes())?; + writer.write_all(&self.unused.to_le_bytes())?; + + Ok(()) + } +} + +/// Helper struct for synthesizing IVF frame header +pub struct IvfFrameHeader { + pub frame_size: u32, + pub timestamp: u64, +} + +impl IvfFrameHeader { + /// Writes header into writer + pub fn writo_into(&self, writer: &mut impl std::io::Write) -> std::io::Result<()> { + writer.write_all(&self.frame_size.to_le_bytes())?; + writer.write_all(&self.timestamp.to_le_bytes())?; + Ok(()) + } +} + +/// Iterator NALUs in a bitstream. +pub struct NalIterator<'a, Nalu>(Cursor<&'a [u8]>, PhantomData); + +impl<'a, Nalu> NalIterator<'a, Nalu> { + pub fn new(stream: &'a [u8]) -> Self { + Self(Cursor::new(stream), PhantomData) + } +} + +impl<'a> Iterator for NalIterator<'a, H264Nalu<'a>> { + type Item = Cow<'a, [u8]>; + + fn next(&mut self) -> Option { + H264Nalu::next(&mut self.0).map(|n| n.data).ok() + } +} + +impl<'a> Iterator for NalIterator<'a, H265Nalu<'a>> { + type Item = Cow<'a, [u8]>; + + fn next(&mut self) -> Option { + H265Nalu::next(&mut self.0).map(|n| n.data).ok() + } +} + +#[derive(Debug)] +pub enum BitWriterError { + InvalidBitCount, + Io(std::io::Error), +} + +impl fmt::Display for BitWriterError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + BitWriterError::InvalidBitCount => write!(f, "invalid bit count"), + BitWriterError::Io(x) => write!(f, "{}", x.to_string()), + } + } +} + +impl From for BitWriterError { + fn from(err: std::io::Error) -> Self { + BitWriterError::Io(err) + } +} + +pub type BitWriterResult = std::result::Result; + +pub struct BitWriter { + out: W, + nth_bit: u8, + curr_byte: u8, +} + +impl BitWriter { + pub fn new(writer: W) -> Self { + Self { out: writer, curr_byte: 0, nth_bit: 0 } + } + + /// Writes fixed bit size integer (up to 32 bit) + pub fn write_f>(&mut self, bits: usize, value: T) -> BitWriterResult { + let value = value.into(); + + if bits > 32 { + return Err(BitWriterError::InvalidBitCount); + } + + let mut written = 0; + for bit in (0..bits).rev() { + let bit = (1 << bit) as u32; + + self.write_bit((value & bit) == bit)?; + written += 1; + } + + Ok(written) + } + + /// Takes a single bit that will be outputed to [`std::io::Write`] + pub fn write_bit(&mut self, bit: bool) -> BitWriterResult<()> { + self.curr_byte |= (bit as u8) << (7u8 - self.nth_bit); + self.nth_bit += 1; + + if self.nth_bit == 8 { + self.out.write_all(&[self.curr_byte])?; + self.nth_bit = 0; + self.curr_byte = 0; + } + + Ok(()) + } + + /// Immediately outputs any cached bits to [`std::io::Write`] + pub fn flush(&mut self) -> BitWriterResult<()> { + if self.nth_bit != 0 { + self.out.write_all(&[self.curr_byte])?; + self.nth_bit = 0; + self.curr_byte = 0; + } + + self.out.flush()?; + Ok(()) + } + + /// Returns `true` if ['Self`] hold data that wasn't written to [`std::io::Write`] + pub fn has_data_pending(&self) -> bool { + self.nth_bit != 0 + } + + pub(crate) fn inner(&self) -> &W { + &self.out + } + + pub(crate) fn inner_mut(&mut self) -> &mut W { + &mut self.out + } +} + +impl Drop for BitWriter { + fn drop(&mut self) { + if let Err(e) = self.flush() { + log::error!("Unable to flush bits {e:?}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ivf_file_header() { + let mut hdr = IvfFileHeader { + version: 0, + codec: IvfFileHeader::CODEC_VP9, + width: 256, + height: 256, + framerate: 30_000, + timescale: 1_000, + frame_count: 1, + + ..Default::default() + }; + + let mut buf = Vec::new(); + hdr.writo_into(&mut buf).unwrap(); + + const EXPECTED: [u8; 32] = [ + 0x44, 0x4b, 0x49, 0x46, 0x00, 0x00, 0x20, 0x00, 0x56, 0x50, 0x39, 0x30, 0x00, 0x01, + 0x00, 0x01, 0x30, 0x75, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + ]; + + assert_eq!(&buf, &EXPECTED); + + hdr.width = 1920; + hdr.height = 800; + hdr.framerate = 24; + hdr.timescale = 1; + hdr.frame_count = 100; + + buf.clear(); + hdr.writo_into(&mut buf).unwrap(); + + const EXPECTED2: [u8; 32] = [ + 0x44, 0x4b, 0x49, 0x46, 0x00, 0x00, 0x20, 0x00, 0x56, 0x50, 0x39, 0x30, 0x80, 0x07, + 0x20, 0x03, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + ]; + + assert_eq!(&buf, &EXPECTED2); + } + + #[test] + fn test_ivf_frame_header() { + let mut hdr = IvfFrameHeader { frame_size: 199249, timestamp: 0 }; + + let mut buf = Vec::new(); + hdr.writo_into(&mut buf).unwrap(); + + const EXPECTED: [u8; 12] = + [0x51, 0x0a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + assert_eq!(&buf, &EXPECTED); + + hdr.timestamp = 1; + hdr.frame_size = 52; + + buf.clear(); + hdr.writo_into(&mut buf).unwrap(); + + const EXPECTED2: [u8; 12] = + [0x34, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + assert_eq!(&buf, &EXPECTED2); + } + + #[test] + fn test_bitwriter_f1() { + let mut buf = Vec::::new(); + { + let mut writer = BitWriter::new(&mut buf); + writer.write_f(1, true).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + } + assert_eq!(buf, vec![0b10001111u8]); + } + + #[test] + fn test_bitwriter_f3() { + let mut buf = Vec::::new(); + { + let mut writer = BitWriter::new(&mut buf); + writer.write_f(3, 0b100u8).unwrap(); + writer.write_f(3, 0b101u8).unwrap(); + writer.write_f(3, 0b011u8).unwrap(); + } + assert_eq!(buf, vec![0b10010101u8, 0b10000000u8]); + } + + #[test] + fn test_bitwriter_f4() { + let mut buf = Vec::::new(); + { + let mut writer = BitWriter::new(&mut buf); + writer.write_f(4, 0b1000u8).unwrap(); + writer.write_f(4, 0b1011u8).unwrap(); + } + assert_eq!(buf, vec![0b10001011u8]); + } + + // These tests are adapted from the chromium tests at media/video/h264_bit_reader_unitttest.cc + + #[test] + fn read_stream_without_escape_and_trailing_zero_bytes() { + const RBSP: [u8; 6] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xa0]; + + let mut reader = BitReader::new(&RBSP, true); + assert_eq!(reader.read_bits::(1).unwrap(), 0); + assert_eq!(reader.num_bits_left(), 47); + assert!(reader.has_more_rsbp_data()); + + assert_eq!(reader.read_bits::(8).unwrap(), 0x02); + assert_eq!(reader.num_bits_left(), 39); + assert!(reader.has_more_rsbp_data()); + + assert_eq!(reader.read_bits::(31).unwrap(), 0x23456789); + assert_eq!(reader.num_bits_left(), 8); + assert!(reader.has_more_rsbp_data()); + + assert_eq!(reader.read_bits::(1).unwrap(), 1); + assert_eq!(reader.num_bits_left(), 7); + assert!(reader.has_more_rsbp_data()); + + assert_eq!(reader.read_bits::(1).unwrap(), 0); + assert_eq!(reader.num_bits_left(), 6); + assert!(!reader.has_more_rsbp_data()); + } + + #[test] + fn single_byte_stream() { + const RBSP: [u8; 1] = [0x18]; + + let mut reader = BitReader::new(&RBSP, true); + assert_eq!(reader.num_bits_left(), 8); + assert!(reader.has_more_rsbp_data()); + assert_eq!(reader.read_bits::(4).unwrap(), 1); + assert!(!reader.has_more_rsbp_data()); + } + + #[test] + fn stop_bit_occupy_full_byte() { + const RBSP: [u8; 2] = [0xab, 0x80]; + + let mut reader = BitReader::new(&RBSP, true); + assert_eq!(reader.num_bits_left(), 16); + assert!(reader.has_more_rsbp_data()); + + assert_eq!(reader.read_bits::(8).unwrap(), 0xab); + assert_eq!(reader.num_bits_left(), 8); + + assert!(!reader.has_more_rsbp_data()); + } + + // Check that read_ue behaves properly with input at the limits. + #[test] + fn read_ue() { + // Regular value. + let mut reader = BitReader::new(&[0b0001_1010], true); + assert_eq!(reader.read_ue::().unwrap(), 12); + assert_eq!(reader.data.position(), 1); + assert_eq!(reader.num_remaining_bits_in_curr_byte, 1); + + // 0 value. + let mut reader = BitReader::new(&[0b1000_0000], true); + assert_eq!(reader.read_ue::().unwrap(), 0); + assert_eq!(reader.data.position(), 1); + assert_eq!(reader.num_remaining_bits_in_curr_byte, 7); + + // No prefix stop bit. + let mut reader = BitReader::new(&[0b0000_0000], true); + reader.read_ue::().unwrap_err(); + + // u32 max value: 31 0-bits, 1 bit marker, 31 bits 1-bits. + let mut reader = BitReader::new( + &[ + 0b0000_0000, + 0b0000_0000, + 0b0000_0000, + 0b0000_0001, + 0b1111_1111, + 0b1111_1111, + 0b1111_1111, + 0b1111_1110, + ], + true, + ); + assert_eq!(reader.read_ue::().unwrap(), 0xffff_fffe); + assert_eq!(reader.data.position(), 8); + assert_eq!(reader.num_remaining_bits_in_curr_byte, 1); + } + + // Check that emulation prevention is being handled correctly. + #[test] + fn skip_epb_when_enabled() { + let mut reader = BitReader::new(&[0x00, 0x00, 0x03, 0x01], false); + assert_eq!(reader.read_bits::(8).unwrap(), 0x00); + assert_eq!(reader.read_bits::(8).unwrap(), 0x00); + assert_eq!(reader.read_bits::(8).unwrap(), 0x03); + assert_eq!(reader.read_bits::(8).unwrap(), 0x01); + + let mut reader = BitReader::new(&[0x00, 0x00, 0x03, 0x01], true); + assert_eq!(reader.read_bits::(8).unwrap(), 0x00); + assert_eq!(reader.read_bits::(8).unwrap(), 0x00); + assert_eq!(reader.read_bits::(8).unwrap(), 0x01); + } + + #[test] + fn read_signed_bits() { + let mut reader = BitReader::new(&[0b1111_0000], false); + assert_eq!(reader.read_bits_signed::(4).unwrap(), -1); + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper.rs b/vendor/cros-codecs/src/c2_wrapper.rs new file mode 100644 index 0000000..97b3309 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper.rs @@ -0,0 +1,381 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use nix::errno::Errno; +use nix::sys::eventfd::EfdFlags; +use nix::sys::eventfd::EventFd; + +use thiserror::Error; + +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::sync::atomic::AtomicU32; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; +use std::thread::JoinHandle; +use std::vec::Vec; + +use crate::decoder::StreamInfo; +use crate::video_frame::VideoFrame; +use crate::Fourcc; + +pub mod c2_decoder; +pub mod c2_encoder; +#[cfg(feature = "v4l2")] +pub mod c2_v4l2_decoder; +#[cfg(feature = "v4l2")] +pub mod c2_v4l2_encoder; +#[cfg(feature = "vaapi")] +pub mod c2_vaapi_decoder; +#[cfg(feature = "vaapi")] +pub mod c2_vaapi_encoder; + +#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)] +pub enum DrainMode { + // Not draining + #[default] + NoDrain = -1, + // Drain the C2 component and signal an EOS. Currently we also change the state to stop. + EOSDrain = 0, + // Drain the C2 component, but keep accepting new jobs in the queue immediately after. + NoEOSDrain = 1, +} + +#[derive(Debug)] +pub struct C2DecodeJob { + // Compressed input data + // TODO: Use VideoFrame for input too + pub input: Vec, + // Decompressed output frame. Note that this needs to be reference counted because we may still + // use this frame as a reference frame even while we're displaying it. + pub output: Option>, + pub drain: DrainMode, + // TODO: Add output delay and color aspect support as needed. +} + +impl Job for C2DecodeJob +where + V: VideoFrame, +{ + type Frame = V; + + fn set_drain(&mut self, drain: DrainMode) { + self.drain = drain; + } + + fn get_drain(&self) -> DrainMode { + self.drain + } +} + +impl Default for C2DecodeJob { + fn default() -> Self { + Self { input: vec![], output: None, drain: DrainMode::NoDrain } + } +} + +pub trait Job: Send + 'static { + type Frame: VideoFrame; + + fn set_drain(&mut self, drain: DrainMode) -> (); + fn get_drain(&self) -> DrainMode; +} + +#[derive(Debug)] +pub struct C2EncodeJob { + pub input: Option, + // TODO: Use VideoFrame for output too + pub output: Vec, + // In microseconds. + pub timestamp: u64, + // TODO: only support CBR right now, follow up with VBR support. + pub bitrate: u64, + // Framerate is actually negotiated, so the encoder can change this value + // based on the timestamps of the frames it receives. + pub framerate: Arc, + pub drain: DrainMode, +} + +impl Default for C2EncodeJob { + fn default() -> Self { + Self { + input: None, + output: vec![], + timestamp: 0, + bitrate: 0, + framerate: Arc::new(AtomicU32::new(0)), + drain: DrainMode::NoDrain, + } + } +} + +impl Job for C2EncodeJob +where + V: VideoFrame, +{ + type Frame = V; + + fn set_drain(&mut self, drain: DrainMode) { + self.drain = drain; + } + + fn get_drain(&self) -> DrainMode { + self.drain + } +} + +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +pub enum C2State { + C2Running, + C2Stopped, + // Note that on state C2Error, stop() must be called before we can start() + // again. + C2Error, +} + +// This is not a very "Rust-y" way of doing error handling, but it will +// hopefully make the FFI easier to write. Numerical values taken from +// frameworks/av/media/codec2/core/include/C2.h +// TODO: Improve error handling by adding more statuses. +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +pub enum C2Status { + C2Ok = 0, + C2BadState = 1, // EPERM + C2BadValue = 22, // EINVAL +} + +// J should be either C2DecodeJob or C2EncodeJob. +pub trait C2Worker +where + J: Send + Job + 'static, +{ + type Options: Clone + Send + 'static; + + fn new( + input_fourcc: Fourcc, + output_fourcc: Fourcc, + awaiting_job_event: Arc, + error_cb: Arc>, + work_done_cb: Arc>, + work_queue: Arc>>, + state: Arc>, + framepool_hint_cb: Arc>, + alloc_cb: Arc Option<::Frame> + Send + 'static>>, + options: Self::Options, + ) -> Result + where + Self: Sized; + + fn process_loop(&mut self); +} + +#[derive(Debug, Error)] +pub enum C2WrapperError { + #[error("failed to create EventFd for awaiting job event: {0}")] + AwaitingJobEventFd(Errno), +} + +// Note that we do not guarantee thread safety in C2CrosCodecsWrapper. +pub struct C2Wrapper +where + J: Send + Default + Job + 'static, + W: C2Worker, +{ + awaiting_job_event: Arc, + input_fourcc: Fourcc, + output_fourcc: Fourcc, + error_cb: Arc>, + work_done_cb: Arc>, + work_queue: Arc>>, + state: Arc>, + framepool_hint_cb: Arc>, + alloc_cb: Arc Option<::Frame> + Send + 'static>>, + options: >::Options, + worker_thread: Option>, + // The instance of V actually lives in the thread creation closure, not + // this struct. + _phantom: PhantomData, +} + +impl C2Wrapper +where + J: Send + Default + Job + 'static, + W: C2Worker, +{ + pub fn new( + input_fourcc: Fourcc, + output_fourcc: Fourcc, + error_cb: impl FnMut(C2Status) + Send + 'static, + work_done_cb: impl FnMut(J) + Send + 'static, + framepool_hint_cb: impl FnMut(StreamInfo) + Send + 'static, + alloc_cb: impl FnMut() -> Option<::Frame> + Send + 'static, + options: >::Options, + ) -> Self { + Self { + awaiting_job_event: Arc::new( + EventFd::from_flags(EfdFlags::EFD_SEMAPHORE) + .map_err(C2WrapperError::AwaitingJobEventFd) + .unwrap(), + ), + input_fourcc: input_fourcc, + output_fourcc: output_fourcc, + error_cb: Arc::new(Mutex::new(error_cb)), + work_done_cb: Arc::new(Mutex::new(work_done_cb)), + work_queue: Arc::new(Mutex::new(VecDeque::new())), + state: Arc::new(Mutex::new(C2State::C2Stopped)), + framepool_hint_cb: Arc::new(Mutex::new(framepool_hint_cb)), + alloc_cb: Arc::new(Mutex::new(alloc_cb)), + options: options, + worker_thread: None, + _phantom: Default::default(), + } + } + + // This isn't part of C2, but it's convenient to check if our worker thread + // is still running. + pub fn is_alive(&self) -> bool { + match &self.worker_thread { + Some(worker_thread) => !worker_thread.is_finished(), + None => false, + } + } + + // Start the decoder/encoder. + // State will be C2Running after this call. + pub fn start(&mut self) -> C2Status { + { + let mut state = self.state.lock().unwrap(); + if *state != C2State::C2Stopped { + (*self.error_cb.lock().unwrap())(C2Status::C2BadState); + return C2Status::C2BadState; + } + *state = C2State::C2Running; + } + + let input_fourcc = self.input_fourcc.clone(); + let output_fourcc = self.output_fourcc.clone(); + let error_cb = self.error_cb.clone(); + let work_done_cb = self.work_done_cb.clone(); + let work_queue = self.work_queue.clone(); + let state = self.state.clone(); + let options = self.options.clone(); + let awaiting_job_event = self.awaiting_job_event.clone(); + let framepool_hint_cb = self.framepool_hint_cb.clone(); + let alloc_cb = self.alloc_cb.clone(); + self.worker_thread = Some(thread::spawn(move || { + let worker = W::new( + input_fourcc, + output_fourcc, + awaiting_job_event, + error_cb.clone(), + work_done_cb, + work_queue, + state.clone(), + framepool_hint_cb, + alloc_cb, + options, + ); + match worker { + Ok(mut worker) => worker.process_loop(), + Err(msg) => { + log::debug!("Error instantiating C2Worker {}", msg); + *state.lock().unwrap() = C2State::C2Error; + (*error_cb.lock().unwrap())(C2Status::C2BadValue); + } + }; + })); + + C2Status::C2Ok + } + + // Stop the decoder/encoder and abandon in-flight work. + // C2's reset() function is equivalent for our purposes. + // Note that in event of error, stop() must be called before we can start() + // again. This is to ensure we clear out the work queue. + // State will be C2Stopped after this call. + pub fn stop(&mut self) -> C2Status { + *self.state.lock().unwrap() = C2State::C2Stopped; + let mut worker_thread: Option> = None; + std::mem::swap(&mut worker_thread, &mut self.worker_thread); + self.worker_thread = match worker_thread { + Some(worker_thread) => { + let _ = worker_thread.join(); + None + } + None => None, + }; + + self.work_queue.lock().unwrap().drain(..); + + self.awaiting_job_event.write(1).unwrap(); + + C2Status::C2Ok + } + + // Add work to the work queue. + // State must be C2Running or this function is invalid. + // State will remain C2Running. + pub fn queue(&mut self, work_items: Vec) -> C2Status { + if *self.state.lock().unwrap() != C2State::C2Running { + (*self.error_cb.lock().unwrap())(C2Status::C2BadState); + return C2Status::C2BadState; + } + + self.work_queue.lock().unwrap().extend(work_items.into_iter()); + + self.awaiting_job_event.write(1).unwrap(); + + C2Status::C2Ok + } + + // Flush work from the queue and return it as |flushed_work|. + // State will not change after this call. + // TODO: Support different flush modes. + pub fn flush(&mut self, flushed_work: &mut Vec) -> C2Status { + if *self.state.lock().unwrap() != C2State::C2Running { + (*self.error_cb.lock().unwrap())(C2Status::C2BadState); + return C2Status::C2BadState; + } + + let mut tmp = self.work_queue.lock().unwrap().drain(..).collect::>(); + flushed_work.append(&mut tmp); + + C2Status::C2Ok + } + + // Signal to the decoder/encoder that it does not need to wait for + // additional work to begin processing. This is an unusual name for this + // function, but it is the convention that C2 uses. + // State must be C2Running or this function is invalid. + // State will remain C2Running until the last frames drain, at which point + // the state will change to C2Stopped. + // TODO: Support different drain modes. + pub fn drain(&mut self, mode: DrainMode) -> C2Status { + if *self.state.lock().unwrap() != C2State::C2Running { + (*self.error_cb.lock().unwrap())(C2Status::C2BadState); + return C2Status::C2BadState; + } + + let mut drain_job: J = Default::default(); + drain_job.set_drain(mode); + self.work_queue.lock().unwrap().push_back(drain_job); + + self.awaiting_job_event.write(1).unwrap(); + + C2Status::C2Ok + } +} + +// Instead of C2's release() function, we implement Drop and use RAII to +// accomplish the same thing +impl Drop for C2Wrapper +where + J: Send + Default + Job + 'static, + W: C2Worker, +{ + fn drop(&mut self) { + self.stop(); + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_decoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_decoder.rs new file mode 100644 index 0000000..4d8f915 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_decoder.rs @@ -0,0 +1,338 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use nix::errno::Errno; +use nix::sys::epoll::Epoll; +use nix::sys::epoll::EpollCreateFlags; +use nix::sys::epoll::EpollEvent; +use nix::sys::epoll::EpollFlags; +use nix::sys::epoll::EpollTimeout; +use nix::sys::eventfd::EventFd; + +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::os::fd::AsFd; +#[cfg(feature = "vaapi")] +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::Mutex; +use thiserror::Error; + +use crate::c2_wrapper::C2DecodeJob; +use crate::c2_wrapper::C2State; +use crate::c2_wrapper::C2Status; +use crate::c2_wrapper::C2Worker; +use crate::c2_wrapper::DrainMode; +use crate::c2_wrapper::Job; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DynStatelessVideoDecoder; +use crate::decoder::DecoderEvent; +use crate::decoder::StreamInfo; +use crate::image_processing::convert_video_frame; +use crate::video_frame::frame_pool::FramePool; +use crate::video_frame::frame_pool::PooledVideoFrame; +#[cfg(feature = "vaapi")] +use crate::video_frame::gbm_video_frame::{GbmDevice, GbmUsage, GbmVideoFrame}; +#[cfg(feature = "v4l2")] +use crate::video_frame::v4l2_mmap_video_frame::V4l2MmapVideoFrame; +use crate::video_frame::VideoFrame; +use crate::EncodedFormat; +use crate::Fourcc; + +#[derive(Debug, Error)] +pub enum C2DecoderPollErrorWrapper { + #[error("failed to create Epoll: {0}")] + Epoll(Errno), + #[error("failed to add poll FDs to Epoll: {0}")] + EpollAdd(Errno), +} + +pub trait C2DecoderBackend { + type DecoderOptions: Clone + Send + 'static; + + fn new(options: Self::DecoderOptions) -> Result + where + Self: Sized; + fn supported_output_formats(&self) -> Vec; + // TODO: Support stateful video decoders. + fn get_decoder( + &mut self, + input_format: EncodedFormat, + ) -> Result, String>; +} + +#[cfg(feature = "vaapi")] +type AuxiliaryVideoFrame = GbmVideoFrame; +#[cfg(feature = "v4l2")] +type AuxiliaryVideoFrame = V4l2MmapVideoFrame; + +// An "importing decoder" can directly import the DMA bufs we are getting, while a "converting +// decoder" is used for performing image processing routines to convert between the video hardware +// output and a pixel format that can be consumed by the GPU and display controller. +// TODO: Come up with a better name for these? +enum C2Decoder { + ImportingDecoder(DynStatelessVideoDecoder), + ConvertingDecoder(DynStatelessVideoDecoder>), +} + +pub struct C2DecoderWorker +where + V: VideoFrame, + B: C2DecoderBackend, +{ + decoder: C2Decoder, + epoll_fd: Epoll, + awaiting_job_event: Arc, + auxiliary_frame_pool: Option>, + error_cb: Arc>, + work_done_cb: Arc) + Send + 'static>>, + framepool_hint_cb: Arc>, + alloc_cb: Arc Option + Send + 'static>>, + work_queue: Arc>>>, + frame_num: u64, + state: Arc>, + _phantom: PhantomData, +} + +impl C2DecoderWorker +where + V: VideoFrame, + B: C2DecoderBackend, +{ + // Processes events from the decoder. Primarily these are frame decoded events and DRCs. + fn check_events(&mut self) { + loop { + let stream_info = match &self.decoder { + C2Decoder::ImportingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()), + C2Decoder::ConvertingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()), + }; + match &mut self.decoder { + C2Decoder::ImportingDecoder(decoder) => match decoder.next_event() { + Some(DecoderEvent::FrameReady(frame)) => { + frame.sync().unwrap(); + let mut job: C2DecodeJob = Default::default(); + job.output = Some(frame.video_frame()); + (*self.work_done_cb.lock().unwrap())(job); + } + Some(DecoderEvent::FormatChanged) => match stream_info { + Some(stream_info) => { + (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone()); + } + None => { + log::debug!("Could not get stream info after format change!"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + } + }, + _ => break, + }, + C2Decoder::ConvertingDecoder(decoder) => match decoder.next_event() { + Some(DecoderEvent::FrameReady(frame)) => { + frame.sync().unwrap(); + let mut job: C2DecodeJob = Default::default(); + let mut dst_frame = + (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!"); + let src_frame = &*frame.video_frame(); + if let Err(err) = convert_video_frame(src_frame, &mut dst_frame) { + log::debug!("Error converting VideoFrame! {err}"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + } + job.output = Some(Arc::new(dst_frame)); + (*self.work_done_cb.lock().unwrap())(job); + } + Some(DecoderEvent::FormatChanged) => match stream_info { + Some(stream_info) => { + (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone()); + self.auxiliary_frame_pool.as_mut().unwrap().resize(&stream_info); + } + None => { + log::debug!("Could not get stream info after format change!"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + } + }, + _ => break, + }, + } + } + } +} + +impl C2Worker> for C2DecoderWorker +where + V: VideoFrame, + B: C2DecoderBackend, +{ + type Options = ::DecoderOptions; + + fn new( + input_fourcc: Fourcc, + output_fourcc: Fourcc, + awaiting_job_event: Arc, + error_cb: Arc>, + work_done_cb: Arc) + Send + 'static>>, + work_queue: Arc>>>, + state: Arc>, + framepool_hint_cb: Arc>, + alloc_cb: Arc Option + Send + 'static>>, + options: Self::Options, + ) -> Result { + let mut backend = B::new(options)?; + let backend_fourccs = backend.supported_output_formats(); + let (auxiliary_frame_pool, decoder) = if backend_fourccs.contains(&output_fourcc) { + ( + None, + C2Decoder::ImportingDecoder( + backend.get_decoder(EncodedFormat::from(input_fourcc))?, + ), + ) + } else { + #[cfg(feature = "vaapi")] + { + let gbm_device = Arc::new( + GbmDevice::open(PathBuf::from("/dev/dri/renderD128")) + .expect("Could not open GBM device!"), + ); + let framepool = FramePool::new(move |stream_info: &StreamInfo| { + // TODO: Query the driver for these alignment params. + as Clone>::clone(&gbm_device) + .new_frame( + Fourcc::from(stream_info.format), + stream_info.display_resolution.clone(), + stream_info.coded_resolution.clone(), + GbmUsage::Decode, + ) + .expect("Could not allocate frame for auxiliary frame pool!") + }); + ( + Some(framepool), + C2Decoder::ConvertingDecoder( + backend.get_decoder(EncodedFormat::from(input_fourcc))?, + ), + ) + } + #[cfg(feature = "v4l2")] + { + let framepool = FramePool::new(move |stream_info: &StreamInfo| { + V4l2MmapVideoFrame::new( + Fourcc::from(stream_info.format), + stream_info.display_resolution.clone(), + ) + }); + ( + Some(framepool), + C2Decoder::ConvertingDecoder( + backend.get_decoder(EncodedFormat::from(input_fourcc))?, + ), + ) + } + }; + Ok(Self { + decoder: decoder, + auxiliary_frame_pool: auxiliary_frame_pool, + epoll_fd: Epoll::new(EpollCreateFlags::empty()) + .map_err(C2DecoderPollErrorWrapper::Epoll) + .unwrap(), + awaiting_job_event: awaiting_job_event, + error_cb: error_cb, + work_done_cb: work_done_cb, + framepool_hint_cb: framepool_hint_cb, + alloc_cb: alloc_cb, + work_queue: work_queue, + frame_num: 0, + state: state, + _phantom: Default::default(), + }) + } + + fn process_loop(&mut self) { + self.epoll_fd = Epoll::new(EpollCreateFlags::empty()) + .map_err(C2DecoderPollErrorWrapper::Epoll) + .unwrap(); + let _ = self + .epoll_fd + .add( + match &self.decoder { + C2Decoder::ImportingDecoder(decoder) => decoder.poll_fd(), + C2Decoder::ConvertingDecoder(decoder) => decoder.poll_fd(), + }, + EpollEvent::new(EpollFlags::EPOLLIN, 1), + ) + .map_err(C2DecoderPollErrorWrapper::EpollAdd); + self.epoll_fd + .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 2)) + .map_err(C2DecoderPollErrorWrapper::EpollAdd) + .unwrap(); + + while *self.state.lock().unwrap() == C2State::C2Running { + // Poll for decoder events or pending job events. + let mut events = [EpollEvent::empty()]; + let _nb_fds = self.epoll_fd.wait(&mut events, EpollTimeout::NONE).unwrap(); + + if events == [EpollEvent::new(EpollFlags::EPOLLIN, 2)] { + self.awaiting_job_event.read().unwrap(); + } + + // We want to try sending compressed buffers to the decoder regardless of what event + // woke us up, because we either have new work, or we might more output buffers + // available. + let mut possible_job = (*self.work_queue.lock().unwrap()).pop_front(); + while let Some(mut job) = possible_job { + if job.get_drain() != DrainMode::NoDrain { + let flush_result = match &mut self.decoder { + C2Decoder::ImportingDecoder(decoder) => decoder.flush(), + C2Decoder::ConvertingDecoder(decoder) => decoder.flush(), + }; + if let Err(_) = flush_result { + log::debug!("Error handling drain request!"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + } else { + if job.get_drain() == DrainMode::EOSDrain { + *self.state.lock().unwrap() = C2State::C2Stopped; + } + self.check_events(); + } + break; + } else { + let bitstream = job.input.as_slice(); + let decode_result = match &mut self.decoder { + C2Decoder::ImportingDecoder(decoder) => decoder.decode( + self.frame_num, + bitstream, + &mut *self.alloc_cb.lock().unwrap(), + ), + C2Decoder::ConvertingDecoder(decoder) => { + decoder.decode(self.frame_num, bitstream, &mut || { + self.auxiliary_frame_pool.as_mut().unwrap().alloc() + }) + } + }; + match decode_result { + Ok(num_bytes) => { + self.frame_num += 1; + if num_bytes != job.input.len() { + job.input = (&job.input[num_bytes..]).to_vec(); + (*self.work_queue.lock().unwrap()).push_front(job); + } + } + Err(DecodeError::NotEnoughOutputBuffers(_) | DecodeError::CheckEvents) => { + (*self.work_queue.lock().unwrap()).push_front(job); + break; + } + Err(e) => { + log::debug!("Unhandled error message from decoder {e:?}"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + } + } + possible_job = (*self.work_queue.lock().unwrap()).pop_front(); + } + self.check_events(); + } + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_encoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_encoder.rs new file mode 100644 index 0000000..d21bd45 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_encoder.rs @@ -0,0 +1,272 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use nix::sys::epoll::Epoll; +use nix::sys::epoll::EpollCreateFlags; +use nix::sys::epoll::EpollEvent; +use nix::sys::epoll::EpollFlags; +use nix::sys::epoll::EpollTimeout; +use nix::sys::eventfd::EventFd; + +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::os::fd::AsFd; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Mutex; +use std::time::Duration; + +use crate::c2_wrapper::C2EncodeJob; +use crate::c2_wrapper::C2State; +use crate::c2_wrapper::C2Status; +use crate::c2_wrapper::C2Worker; +use crate::c2_wrapper::DrainMode; +use crate::c2_wrapper::Job; +use crate::decoder::StreamInfo; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::RateControl::ConstantBitrate; +use crate::encoder::RateControl::ConstantQuality; +use crate::encoder::Tunings; +use crate::encoder::VideoEncoder; +use crate::image_processing::convert_video_frame; +use crate::image_processing::extend_border_nv12; +#[cfg(feature = "v4l2")] +use crate::video_frame::V4l2VideoFrame; +use crate::video_frame::VideoFrame; +use crate::video_frame::UV_PLANE; +use crate::video_frame::Y_PLANE; +use crate::DecodedFormat; +use crate::EncodedFormat; +use crate::Fourcc; +use crate::Resolution; + +pub trait C2EncoderBackend { + type EncoderOptions: Clone + Send + 'static; + + fn new(options: Self::EncoderOptions) -> Result + where + Self: Sized; + + // Returns a new encoder, the visible resolution, and the coded resolution. + #[cfg(feature = "vaapi")] + fn get_encoder( + &mut self, + input_format: DecodedFormat, + output_format: EncodedFormat, + ) -> Result<(Box>, Resolution, Resolution), String>; + #[cfg(feature = "v4l2")] + fn get_encoder( + &mut self, + input_format: DecodedFormat, + output_format: EncodedFormat, + ) -> Result<(Box>>, Resolution, Resolution), String>; +} + +pub struct C2EncoderWorker +where + V: VideoFrame, + B: C2EncoderBackend, +{ + #[cfg(feature = "vaapi")] + encoder: Box>, + #[cfg(feature = "v4l2")] + encoder: Box>>, + awaiting_job_event: Arc, + error_cb: Arc>, + work_done_cb: Arc) + Send + 'static>>, + alloc_cb: Arc Option + Send + 'static>>, + work_queue: Arc>>>, + in_flight_queue: VecDeque>, + state: Arc>, + current_tunings: Tunings, + visible_resolution: Resolution, + coded_resolution: Resolution, + _phantom: PhantomData, +} + +impl C2EncoderWorker +where + V: VideoFrame, + B: C2EncoderBackend, +{ + fn poll_complete_frames(&mut self) { + loop { + match self.encoder.poll() { + Ok(Some(coded)) => { + let mut job = self.in_flight_queue.pop_front().unwrap(); + job.output = coded.bitstream; + (*self.work_done_cb.lock().unwrap())(job); + } + Err(err) => { + log::debug!("Error during encode! {:?}", err); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + _ => break, + } + } + } +} + +impl C2Worker> for C2EncoderWorker +where + V: VideoFrame, + B: C2EncoderBackend, +{ + type Options = B::EncoderOptions; + + fn new( + input_fourcc: Fourcc, + output_fourcc: Fourcc, + awaiting_job_event: Arc, + error_cb: Arc>, + work_done_cb: Arc) + Send + 'static>>, + work_queue: Arc>>>, + state: Arc>, + framepool_hint_cb: Arc>, + alloc_cb: Arc Option + Send + 'static>>, + options: Self::Options, + ) -> Result { + let mut backend = B::new(options)?; + let (encoder, visible_resolution, coded_resolution) = backend + .get_encoder(DecodedFormat::from(input_fourcc), EncodedFormat::from(output_fourcc))?; + (*framepool_hint_cb.lock().unwrap())(StreamInfo { + format: DecodedFormat::from(input_fourcc), + coded_resolution: coded_resolution.clone(), + display_resolution: visible_resolution.clone(), + // Needs to be equal to the pipeline depth, which is decided by the client. Ideally, we + // will never need these temp frames though if Gralloc works properly. + min_num_frames: 0, + }); + + Ok(Self { + encoder: encoder, + awaiting_job_event: awaiting_job_event, + error_cb: error_cb, + work_done_cb: work_done_cb, + work_queue: work_queue, + in_flight_queue: VecDeque::new(), + state: state, + alloc_cb: alloc_cb, + current_tunings: Default::default(), + visible_resolution: visible_resolution, + coded_resolution: coded_resolution, + _phantom: Default::default(), + }) + } + + fn process_loop(&mut self) { + let epoll_fd = Epoll::new(EpollCreateFlags::empty()).expect("Failed to create Epoll"); + let _ = epoll_fd + .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1)) + .expect("Failed to add job event to Epoll"); + + while *self.state.lock().unwrap() == C2State::C2Running { + let mut events = [EpollEvent::empty()]; + // We need an actual timeout because the encoder is poll based rather than async. + let _ = epoll_fd + .wait(&mut events, EpollTimeout::try_from(Duration::from_millis(10)).unwrap()) + .expect("Epoll wait failed"); + if events != [EpollEvent::new(EpollFlags::EPOLLIN, 1)] { + self.poll_complete_frames(); + continue; + } + + self.awaiting_job_event.read().unwrap(); + + // Unlike the decoder, we can assume a 1:1 relationship between jobs in the work_queue + // and wake-up events. The encoders are not asynchronous, so the only events we will + // ever wake-up for are jobs being added to the work_queue. + let mut job = (*self.work_queue.lock().unwrap()) + .pop_front() + .expect("Missing job from work queue!"); + if job.get_drain() != DrainMode::NoDrain { + if let Err(err) = self.encoder.drain() { + log::debug!("Error draining encoder! {:?}", err); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + if job.get_drain() == DrainMode::EOSDrain { + *self.state.lock().unwrap() = C2State::C2Stopped; + } + } else { + let frame_y_stride = job.input.as_ref().unwrap().get_plane_pitch()[0]; + let frame_y_size = job.input.as_ref().unwrap().get_plane_size()[0]; + let can_import_frame = frame_y_stride == self.coded_resolution.width as usize + && frame_y_size >= self.coded_resolution.get_area(); + let frame = if can_import_frame { + job.input.take().unwrap() + } else { + let mut tmp = (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!"); + + if let Err(_) = convert_video_frame(job.input.as_ref().unwrap(), &mut tmp) { + log::debug!("Failed to copy input frame to properly aligned buffer!"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + { + let tmp_mapping = tmp.map_mut().expect("Failed to map tmp frame!"); + let tmp_planes = tmp_mapping.get(); + extend_border_nv12( + *tmp_planes[Y_PLANE].borrow_mut(), + *tmp_planes[UV_PLANE].borrow_mut(), + self.visible_resolution.width as usize, + self.visible_resolution.height as usize, + self.coded_resolution.width as usize, + self.coded_resolution.height as usize, + ); + } + + tmp + }; + + let curr_bitrate = match self.current_tunings.rate_control { + ConstantBitrate(bitrate) => bitrate, + ConstantQuality(_) => { + log::debug!("CQ encoding not currently supported"); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + }; + let new_framerate = job.framerate.load(Ordering::Relaxed); + if job.bitrate != curr_bitrate || new_framerate != self.current_tunings.framerate { + self.current_tunings.rate_control = RateControl::ConstantBitrate(job.bitrate); + self.current_tunings.framerate = new_framerate; + if let Err(err) = self.encoder.tune(self.current_tunings.clone()) { + log::debug!("Error adjusting tunings! {:?}", err); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + }; + + let meta = FrameMetadata { + timestamp: job.timestamp, + layout: Default::default(), + force_keyframe: false, + }; + #[cfg(feature = "vaapi")] + let encode_result = self.encoder.encode(meta, frame); + #[cfg(feature = "v4l2")] + let encode_result = self.encoder.encode(meta, V4l2VideoFrame(frame)); + match encode_result { + Ok(_) => self.in_flight_queue.push_back(job), + Err(err) => { + log::debug!("Error encoding frame! {:?}", err); + *self.state.lock().unwrap() = C2State::C2Error; + (*self.error_cb.lock().unwrap())(C2Status::C2BadValue); + break; + } + } + } + + self.poll_complete_frames(); + } + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_decoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_decoder.rs new file mode 100644 index 0000000..7858d24 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_decoder.rs @@ -0,0 +1,60 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::path::PathBuf; + +use crate::c2_wrapper::c2_decoder::C2DecoderBackend; +use crate::decoder::stateless::av1::Av1; +use crate::decoder::stateless::h264::H264; +use crate::decoder::stateless::vp8::Vp8; +use crate::decoder::stateless::vp9::Vp9; +use crate::decoder::stateless::DynStatelessVideoDecoder; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::video_frame::VideoFrame; +use crate::EncodedFormat; +use crate::Fourcc; + +#[derive(Clone, Debug)] +pub struct C2V4L2DecoderOptions { + // TODO: This is currently unused, but we should plumb it to V4L2Device initialization. + pub video_device_path: Option, +} + +pub struct C2V4L2Decoder {} + +impl C2DecoderBackend for C2V4L2Decoder { + type DecoderOptions = C2V4L2DecoderOptions; + + fn new(_options: C2V4L2DecoderOptions) -> Result { + Ok(Self {}) + } + + // TODO: Actually query the driver for this information. + fn supported_output_formats(&self) -> Vec { + vec![Fourcc::from(b"MM21")] + } + + fn get_decoder( + &mut self, + format: EncodedFormat, + ) -> Result, String> { + Ok(match format { + EncodedFormat::AV1 => StatelessDecoder::::new_v4l2(BlockingMode::NonBlocking) + .map_err(|_| "Failed to instantiate AV1 decoder")? + .into_trait_object(), + EncodedFormat::H264 => StatelessDecoder::::new_v4l2(BlockingMode::NonBlocking) + .map_err(|_| "Failed to instantiate H264 decoder")? + .into_trait_object(), + EncodedFormat::VP8 => StatelessDecoder::::new_v4l2(BlockingMode::NonBlocking) + .map_err(|_| "Failed to instantiate VP8 decoder")? + .into_trait_object(), + EncodedFormat::VP9 => StatelessDecoder::::new_v4l2(BlockingMode::NonBlocking) + .map_err(|_| "Failed to instantiate VP9 decoder")? + .into_trait_object(), + _ => return Err(format!("Unsupported format {format:?}")), + }) + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_encoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_encoder.rs new file mode 100644 index 0000000..edc8ce2 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_v4l2_encoder.rs @@ -0,0 +1,131 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::sync::Arc; + +use crate::backend::v4l2::encoder::find_device_with_capture; +use crate::backend::v4l2::encoder::MmapingCapture; +use crate::c2_wrapper::c2_encoder::C2EncoderBackend; +use crate::encoder::stateful::h264::v4l2::V4L2StatefulH264Encoder; +use crate::encoder::stateful::vp8::v4l2::V4L2StatefulVP8Encoder; +use crate::encoder::stateful::vp9::v4l2::V4L2StatefulVP9Encoder; +use crate::encoder::VideoEncoder; +use crate::video_frame::V4l2VideoFrame; +use crate::video_frame::VideoFrame; +use crate::DecodedFormat; +use crate::EncodedFormat; +use crate::Fourcc; +use crate::Resolution; + +use v4l2r::device::Device; +use v4l2r::device::DeviceConfig; + +fn v4l2_format_to_coded_size(format: &v4l2r::Format) -> Resolution { + let stride = format.plane_fmt[0].bytesperline; + let size = format.plane_fmt[0].sizeimage; + Resolution { width: stride, height: size / stride } +} + +#[derive(Clone, Debug)] +pub struct C2V4L2EncoderOptions { + pub output_fourcc: Fourcc, + pub visible_resolution: Resolution, +} + +pub struct C2V4L2Encoder { + visible_resolution: Resolution, + device: Arc, +} + +impl C2EncoderBackend for C2V4L2Encoder { + type EncoderOptions = C2V4L2EncoderOptions; + + fn new(options: C2V4L2EncoderOptions) -> Result { + let pixel_format = v4l2r::PixelFormat::from_u32(u32::from(options.output_fourcc)); + let device = find_device_with_capture(pixel_format) + .ok_or("Could not find V4L2 device!".to_string())?; + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()) + .map_err(|err| format!("Error opening V4L2 device! {:?}", err))?; + Ok(Self { visible_resolution: options.visible_resolution, device: Arc::new(device) }) + } + + fn get_encoder( + &mut self, + input_format: DecodedFormat, + output_format: EncodedFormat, + ) -> Result<(Box>>, Resolution, Resolution), String> { + Ok(match output_format { + EncodedFormat::H264 => { + let mut encoder = V4L2StatefulH264Encoder::new( + self.device.clone(), + MmapingCapture, + crate::encoder::h264::EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + Default::default(), + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + let coded_format = encoder + .backend() + .output_format() + .map_err(|err| format!("Error querying backend format! {:?}", err))?; + ( + Box::new(encoder), + self.visible_resolution.clone(), + v4l2_format_to_coded_size(&coded_format), + ) + } + EncodedFormat::VP8 => { + let mut encoder = V4L2StatefulVP8Encoder::new( + self.device.clone(), + MmapingCapture, + crate::encoder::vp8::EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + Default::default(), + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + let coded_format = encoder + .backend() + .output_format() + .map_err(|err| format!("Error querying backend format! {:?}", err))?; + ( + Box::new(encoder), + self.visible_resolution.clone(), + v4l2_format_to_coded_size(&coded_format), + ) + } + EncodedFormat::VP9 => { + let mut encoder = V4L2StatefulVP9Encoder::new( + self.device.clone(), + MmapingCapture, + crate::encoder::vp9::EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + Default::default(), + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + let coded_format = encoder + .backend() + .output_format() + .map_err(|err| format!("Error querying backend format! {:?}", err))?; + ( + Box::new(encoder), + self.visible_resolution.clone(), + v4l2_format_to_coded_size(&coded_format), + ) + } + _ => return Err(format!("Format not supported by V4L2! {:?}", output_format)), + }) + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_decoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_decoder.rs new file mode 100644 index 0000000..6f234f3 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_decoder.rs @@ -0,0 +1,86 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::path::PathBuf; +use std::rc::Rc; + +use crate::c2_wrapper::c2_decoder::C2DecoderBackend; +use crate::decoder::stateless::av1::Av1; +use crate::decoder::stateless::h264::H264; +use crate::decoder::stateless::h265::H265; +use crate::decoder::stateless::vp8::Vp8; +use crate::decoder::stateless::vp9::Vp9; +use crate::decoder::stateless::DynStatelessVideoDecoder; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::video_frame::VideoFrame; +use crate::EncodedFormat; +use crate::Fourcc; + +#[derive(Clone, Debug)] +pub struct C2VaapiDecoderOptions { + pub libva_device_path: Option, +} + +pub struct C2VaapiDecoder { + display: Rc, +} + +impl C2DecoderBackend for C2VaapiDecoder { + type DecoderOptions = C2VaapiDecoderOptions; + + fn new(options: C2VaapiDecoderOptions) -> Result { + let display = match options.libva_device_path { + Some(libva_device_path) => libva::Display::open_drm_display(libva_device_path.clone()) + .map_err(|_| format!("failed to open libva display {libva_device_path:?}"))?, + None => libva::Display::open().ok_or("failed to open libva display")?, + }; + + Ok(Self { display: display }) + } + + // TODO: Actually query the driver for this information. + fn supported_output_formats(&self) -> Vec { + vec![Fourcc::from(b"NV12")] + } + + fn get_decoder( + &mut self, + format: EncodedFormat, + ) -> Result, String> { + Ok(match format { + EncodedFormat::H264 => StatelessDecoder::::new_vaapi( + self.display.clone(), + BlockingMode::NonBlocking, + ) + .map_err(|_| "Failed to instantiate H264 encoder")? + .into_trait_object(), + EncodedFormat::H265 => StatelessDecoder::::new_vaapi( + self.display.clone(), + BlockingMode::NonBlocking, + ) + .map_err(|_| "Failed to instantiate H265 encoder")? + .into_trait_object(), + EncodedFormat::VP8 => StatelessDecoder::::new_vaapi( + self.display.clone(), + BlockingMode::NonBlocking, + ) + .map_err(|_| "Failed to instantiate VP8 encoder")? + .into_trait_object(), + EncodedFormat::VP9 => StatelessDecoder::::new_vaapi( + self.display.clone(), + BlockingMode::NonBlocking, + ) + .map_err(|_| "Failed to instantiate VP9 encoder")? + .into_trait_object(), + EncodedFormat::AV1 => StatelessDecoder::::new_vaapi( + self.display.clone(), + BlockingMode::NonBlocking, + ) + .map_err(|_| "Failed to instantiate AV1 encoder")? + .into_trait_object(), + }) + } +} diff --git a/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_encoder.rs b/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_encoder.rs new file mode 100644 index 0000000..d285692 --- /dev/null +++ b/vendor/cros-codecs/src/c2_wrapper/c2_vaapi_encoder.rs @@ -0,0 +1,112 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::c2_wrapper::c2_encoder::C2EncoderBackend; +use crate::encoder::av1::EncoderConfig as AV1EncoderConfig; +use crate::encoder::h264::EncoderConfig as H264EncoderConfig; +use crate::encoder::stateless::av1; +use crate::encoder::stateless::h264; +use crate::encoder::stateless::vp9; +use crate::encoder::vp9::EncoderConfig as VP9EncoderConfig; +use crate::encoder::VideoEncoder; +use crate::utils::align_up; +use crate::video_frame::VideoFrame; +use crate::BlockingMode; +use crate::DecodedFormat; +use crate::EncodedFormat; +use crate::Fourcc; +use crate::Resolution; + +#[derive(Clone, Debug)] +pub struct C2VaapiEncoderOptions { + pub low_power: bool, + pub visible_resolution: Resolution, +} + +pub struct C2VaapiEncoder { + display: Rc, + low_power: bool, + visible_resolution: Resolution, + coded_resolution: Resolution, +} + +impl C2EncoderBackend for C2VaapiEncoder { + type EncoderOptions = C2VaapiEncoderOptions; + + fn new(options: C2VaapiEncoderOptions) -> Result { + const VAAPI_WIDTH_ALIGN: u32 = 16; + const VAAPI_HEIGHT_ALIGN: u32 = 16; + + // TODO: Support alternative display paths + let display = libva::Display::open().ok_or("Error opening LibVA display!".to_string())?; + Ok(Self { + display: display, + low_power: options.low_power, + visible_resolution: options.visible_resolution.clone(), + // TODO: This really shouldn't be necessary, but for some reason minigbm gets the + // vertical alignment wrong when we omit it :( + coded_resolution: Resolution { + width: align_up(options.visible_resolution.width, VAAPI_WIDTH_ALIGN), + height: align_up(options.visible_resolution.height, VAAPI_HEIGHT_ALIGN), + }, + }) + } + + fn get_encoder( + &mut self, + input_format: DecodedFormat, + output_format: EncodedFormat, + ) -> Result<(Box>, Resolution, Resolution), String> { + Ok(match output_format { + EncodedFormat::H264 => { + let encoder = h264::StatelessEncoder::new_vaapi( + self.display.clone(), + H264EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + self.low_power, + BlockingMode::Blocking, + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone()) + } + EncodedFormat::VP9 => { + let encoder = vp9::StatelessEncoder::new_vaapi( + self.display.clone(), + VP9EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + self.low_power, + BlockingMode::Blocking, + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone()) + } + EncodedFormat::AV1 => { + let encoder = av1::StatelessEncoder::new_vaapi( + self.display.clone(), + AV1EncoderConfig { + resolution: self.visible_resolution.clone(), + ..Default::default() + }, + Fourcc::from(input_format), + self.visible_resolution.clone(), + self.low_power, + BlockingMode::Blocking, + ) + .map_err(|err| format!("Error initializing encoder! {:?}", err))?; + (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone()) + } + _ => return Err(format!("Format not supported by V4L2! {:?}", output_format)), + }) + } +} diff --git a/vendor/cros-codecs/src/codec.rs b/vendor/cros-codecs/src/codec.rs new file mode 100644 index 0000000..582ef5f --- /dev/null +++ b/vendor/cros-codecs/src/codec.rs @@ -0,0 +1,18 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Parsers for various kinds of encoded streams. +//! +//! This module does not provide any actual decoding tools - that's the job of the +//! [crate::decoder] module. However the parsers of this module are heavily used in order to +//! implement stateless decoding. +//! +//! There shall be no dependencies from other modules of this crate to this module, so that it +//! can be turned into a crate of its own if needed in the future. + +pub mod av1; +pub mod h264; +pub mod h265; +pub mod vp8; +pub mod vp9; diff --git a/vendor/cros-codecs/src/codec/av1.rs b/vendor/cros-codecs/src/codec/av1.rs new file mode 100644 index 0000000..477cd90 --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1.rs @@ -0,0 +1,9 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +mod helpers; +pub mod parser; +pub mod reader; +pub mod synthesizer; +pub mod writer; diff --git a/vendor/cros-codecs/src/codec/av1/helpers.rs b/vendor/cros-codecs/src/codec/av1/helpers.rs new file mode 100644 index 0000000..ccf65b4 --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1/helpers.rs @@ -0,0 +1,178 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::av1::parser::NUM_REF_FRAMES; + +const DIV_LUT: [i32; 257] = [ + 16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768, 15709, 15650, + 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142, 15087, 15033, 14980, 14926, + 14873, 14821, 14769, 14717, 14665, 14614, 14564, 14513, 14463, 14413, 14364, 14315, 14266, + 14218, 14170, 14122, 14075, 14028, 13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662, + 13618, 13574, 13530, 13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107, + 13066, 13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633, 12596, + 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228, 12193, 12157, 12122, + 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848, 11815, 11782, 11749, 11716, 11683, + 11651, 11619, 11586, 11555, 11523, 11491, 11460, 11429, 11398, 11367, 11336, 11305, 11275, + 11245, 11215, 11185, 11155, 11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894, + 10866, 10838, 10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538, + 10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255, 10230, 10205, + 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986, 9963, 9939, 9916, 9892, 9869, + 9846, 9823, 9800, 9777, 9754, 9732, 9709, 9687, 9664, 9642, 9620, 9598, 9576, 9554, 9533, 9511, + 9489, 9468, 9447, 9425, 9404, 9383, 9362, 9341, 9321, 9300, 9279, 9259, 9239, 9218, 9198, 9178, + 9158, 9138, 9118, 9098, 9079, 9059, 9039, 9020, 9001, 8981, 8962, 8943, 8924, 8905, 8886, 8867, + 8849, 8830, 8812, 8793, 8775, 8756, 8738, 8720, 8702, 8684, 8666, 8648, 8630, 8613, 8595, 8577, + 8560, 8542, 8525, 8508, 8490, 8473, 8456, 8439, 8422, 8405, 8389, 8372, 8355, 8339, 8322, 8306, + 8289, 8273, 8257, 8240, 8224, 8208, 8192, +]; + +const DIV_LUT_BITS: u32 = 8; +const DIV_LUT_PREC_BITS: u32 = 14; + +/// Implements FloorLog2(x), which is defined to be the floor of the base 2 +/// logarithm of the input x. +/// +/// The input x will always be an integer, and will always be greater than or equal to 1. +/// This function extracts the location of the most significant bit in x. +pub fn floor_log2(mut x: u32) -> u32 { + assert!(x > 0); + let mut s = 0; + + while x != 0 { + x >>= 1; + s += 1; + } + + s - 1 +} + +/// Implements 5.9.3. Get relative distance function +pub fn get_relative_dist(enable_order_hint: bool, order_hint_bits: i32, a: i32, b: i32) -> i32 { + if !enable_order_hint { + 0 + } else { + let diff = a - b; + let m = 1 << (order_hint_bits - 1); + (diff & (m - 1)) - (diff & m) + } +} + +/// Implements find_latest_backward from section 7.8. +pub fn find_latest_backward( + shifted_order_hints: &[i32; NUM_REF_FRAMES], + used_frame: &[bool; NUM_REF_FRAMES], + cur_frame_hint: i32, + latest_order_hint: &mut i32, +) -> i32 { + let mut _ref = -1; + + for i in 0..NUM_REF_FRAMES { + let hint = shifted_order_hints[i]; + if !used_frame[i] && hint >= cur_frame_hint && (_ref < 0 || hint >= *latest_order_hint) { + _ref = i as i32; + *latest_order_hint = hint; + } + } + + _ref +} + +/// Implements find_earliest_backward from section 7.8. +pub fn find_earliest_backward( + shifted_order_hints: &[i32; NUM_REF_FRAMES], + used_frame: &[bool; NUM_REF_FRAMES], + cur_frame_hint: i32, + earliest_order_hint: &mut i32, +) -> i32 { + let mut _ref = -1; + + for i in 0..NUM_REF_FRAMES { + let hint = shifted_order_hints[i]; + if !used_frame[i] && hint >= cur_frame_hint && (_ref < 0 || hint < *earliest_order_hint) { + _ref = i as i32; + *earliest_order_hint = hint; + } + } + + _ref +} + +/// Implements find_latest_forward from section 7.8. +pub fn find_latest_forward( + shifted_order_hints: &[i32; NUM_REF_FRAMES], + used_frame: &[bool; NUM_REF_FRAMES], + cur_frame_hint: i32, + latest_order_hint: &mut i32, +) -> i32 { + let mut _ref = -1; + for i in 0..NUM_REF_FRAMES { + let hint = shifted_order_hints[i]; + if !used_frame[i] && hint < cur_frame_hint && (_ref < 0 || hint >= *latest_order_hint) { + _ref = i as i32; + *latest_order_hint = hint; + } + } + + _ref +} + +pub fn tile_log2(blk_size: u32, target: u32) -> u32 { + let mut k = 0; + + while (blk_size << k) < target { + k += 1; + } + + k +} + +pub fn clip3(x: i32, y: i32, z: i32) -> i32 { + if z < x { + x + } else if z > y { + y + } else { + z + } +} + +/// 5.9.29 +pub fn inverse_recenter(r: i32, v: i32) -> i32 { + if v > 2 * r { + v + } else if v & 1 != 0 { + r - ((v + 1) >> 1) + } else { + r + (v >> 1) + } +} + +/// Implements Round2. See 4.7: mathematical functions. +pub fn round2(x: u32, n: u32) -> u32 { + (x + 2u32.pow(n - 1)) / 2u32.pow(n) +} + +/// Implements Round2Signed. See 4.7: mathematical functions. +pub fn round2signed(x: i32, n: u32) -> Result { + if x >= 0 { + i32::try_from(round2(x as u32, n)).map_err(|e| e.to_string()) + } else { + let x = x as i64; + let val = i32::try_from(round2(-x as u32, n)).map_err(|e| e.to_string())?; + Ok(-val) + } +} + +/// Implements 7.11.3.7. Resolve divisor process +pub fn resolve_divisor(d: i32) -> Result<(u32, i32), String> { + let abs_d = u32::try_from(d.abs()).unwrap(); // abs cannot return a negative + let n = floor_log2(abs_d); + let e = abs_d - (1 << n); + + let f = if n > DIV_LUT_BITS { round2(e, n - DIV_LUT_BITS) } else { e << (DIV_LUT_BITS - n) }; + + let div_shift = n + DIV_LUT_PREC_BITS; + let div_factor = if d < 0 { -DIV_LUT[f as usize] } else { DIV_LUT[f as usize] }; + + Ok((div_shift, div_factor)) +} diff --git a/vendor/cros-codecs/src/codec/av1/parser.rs b/vendor/cros-codecs/src/codec/av1/parser.rs new file mode 100644 index 0000000..b059a22 --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1/parser.rs @@ -0,0 +1,4216 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Cow; +use std::rc::Rc; + +use crate::codec::av1::helpers; +use crate::codec::av1::reader::Reader; + +pub const TOTAL_REFS_PER_FRAME: usize = 8; +pub const NUM_REF_FRAMES: usize = 8; +pub const REFS_PER_FRAME: usize = 7; +pub const MAX_SEGMENTS: usize = 8; +pub const SEG_LVL_ALT_Q: usize = 0; +pub const SEG_LVL_ALT_LF_Y_V: usize = 1; +pub const SEG_LVL_REF_FRAME: usize = 5; +pub const SEG_LVL_SKIP: usize = 6; +pub const SEG_LVL_GLOBAL_MV: usize = 7; +pub const SEG_LVL_MAX: usize = 8; +pub const MAX_TILE_COLS: usize = 64; +pub const MAX_TILE_ROWS: usize = 64; +pub const CDEF_MAX: usize = 1 << 3; +pub const MAX_NUM_PLANES: usize = 3; +pub const MAX_NUM_Y_POINTS: usize = 16; +pub const MAX_NUM_CB_POINTS: usize = 16; +pub const MAX_NUM_CR_POINTS: usize = 16; +pub const MAX_NUM_POS_LUMA: usize = 25; +pub const MAX_NUM_SPATIAL_LAYERS: usize = 4; +pub const MAX_NUM_TEMPORAL_LAYERS: usize = 8; +pub const MAX_NUM_OPERATING_POINTS: usize = MAX_NUM_SPATIAL_LAYERS * MAX_NUM_TEMPORAL_LAYERS; +pub const SELECT_SCREEN_CONTENT_TOOLS: usize = 2; +pub const SELECT_INTEGER_MV: usize = 2; +pub const PRIMARY_REF_NONE: u32 = 7; +pub const SUPERRES_DENOM_BITS: usize = 3; +pub const SUPERRES_DENOM_MIN: usize = 9; +pub const SUPERRES_NUM: usize = 8; +pub const MAX_TILE_WIDTH: u32 = 4096; +pub const MAX_TILE_HEIGHT: u32 = 2304; +pub const MAX_TILE_AREA: u32 = MAX_TILE_WIDTH * MAX_TILE_HEIGHT; +pub const RESTORATION_TILESIZE_MAX: u16 = 256; +pub const WARPEDMODEL_PREC_BITS: u32 = 16; +pub const WARP_PARAM_REDUCE_BITS: u32 = 6; +pub const GM_ABS_ALPHA_BITS: u32 = 12; +pub const GM_ALPHA_PREC_BITS: u32 = 15; +pub const GM_ABS_TRANS_ONLY_BITS: u32 = 9; +pub const GM_TRANS_ONLY_PREC_BITS: u32 = 3; +pub const GM_ABS_TRANS_BITS: u32 = 12; +pub const GM_TRANS_PREC_BITS: u32 = 6; + +// Same as Segmentation_Feature_Bits in the specification. See 5.9.14 +pub const FEATURE_BITS: [u8; SEG_LVL_MAX] = [8, 6, 6, 6, 6, 3, 0, 0]; +// Same as Segmentation_Feature_Signed in the specification. See 5.9.14 +pub const FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, true, true, true, false, false, false]; +// Same as Segmentation_Feature_Max in the specification. See 5.9.14 +pub const FEATURE_MAX: [i32; SEG_LVL_MAX] = [255, 63, 63, 63, 63, 7, 0, 0]; + +/// Tells what should be done with the OBU after [`Parser::read_obu`] is called. +pub enum ObuAction<'a> { + /// We should process the OBU normally. + Process(Obu<'a>), + /// We should drop this OBU and advance to the next one. The u32 is how much + /// we should advance. + Drop(u32), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum ObuType { + #[default] + Reserved = 0, + SequenceHeader = 1, + TemporalDelimiter = 2, + FrameHeader = 3, + TileGroup = 4, + Metadata = 5, + Frame = 6, + RedundantFrameHeader = 7, + TileList = 8, + Reserved2 = 9, + Reserved3 = 10, + Reserved4 = 11, + Reserved5 = 12, + Reserved6 = 13, + Reserved7 = 14, + Padding = 15, +} + +impl TryFrom for ObuType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ObuType::Reserved), + 1 => Ok(ObuType::SequenceHeader), + 2 => Ok(ObuType::TemporalDelimiter), + 3 => Ok(ObuType::FrameHeader), + 4 => Ok(ObuType::TileGroup), + 5 => Ok(ObuType::Metadata), + 6 => Ok(ObuType::Frame), + 7 => Ok(ObuType::RedundantFrameHeader), + 8 => Ok(ObuType::TileList), + 9 => Ok(ObuType::Reserved2), + 10 => Ok(ObuType::Reserved3), + 11 => Ok(ObuType::Reserved4), + 12 => Ok(ObuType::Reserved5), + 13 => Ok(ObuType::Reserved6), + 14 => Ok(ObuType::Reserved7), + 15 => Ok(ObuType::Padding), + _ => Err(format!("Invalid ObuType {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum Profile { + #[default] + Profile0 = 0, + Profile1 = 1, + Profile2 = 2, +} + +impl TryFrom for Profile { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(Profile::Profile0), + 1 => Ok(Profile::Profile1), + 2 => Ok(Profile::Profile2), + _ => Err(format!("Invalid Profile {}", value)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ObuHeader { + pub obu_type: ObuType, + pub extension_flag: bool, + pub has_size_field: bool, + pub temporal_id: u32, + pub spatial_id: u32, +} + +impl ObuHeader { + /// Length in bytes + #[allow(clippy::len_without_is_empty)] + pub fn len(&self) -> usize { + if self.extension_flag { + 2 + } else { + 1 + } + } +} + +/// Contains the OBU header and a reference to its data. The OBU itself hasn't been parsed yet. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Obu<'a> { + /// The OBU header. + pub header: ObuHeader, + /// Amount of bytes from the input consumed to parse this OBU. + pub bytes_used: usize, + /// The slice backing the OBU. + data: Cow<'a, [u8]>, +} + +impl<'a> AsRef<[u8]> for Obu<'a> { + fn as_ref(&self) -> &[u8] { + self.data.as_ref() + } +} + +/// A fully parsed OBU, with additional data when relevant. +pub enum ParsedObu<'a> { + Reserved, + SequenceHeader(Rc), + TemporalDelimiter, + FrameHeader(FrameHeaderObu), + TileGroup(TileGroupObu<'a>), + Metadata, + Frame(FrameObu<'a>), + RedundantFrameHeader, + TileList, + Reserved2, + Reserved3, + Reserved4, + Reserved5, + Reserved6, + Reserved7, + Padding, +} + +impl<'a> ParsedObu<'a> { + pub fn obu_type(&self) -> ObuType { + match self { + ParsedObu::Reserved => ObuType::Reserved, + ParsedObu::SequenceHeader(_) => ObuType::SequenceHeader, + ParsedObu::TemporalDelimiter => ObuType::TemporalDelimiter, + ParsedObu::FrameHeader(_) => ObuType::FrameHeader, + ParsedObu::TileGroup(_) => ObuType::TileGroup, + ParsedObu::Metadata => ObuType::Metadata, + ParsedObu::Frame(_) => ObuType::Frame, + ParsedObu::RedundantFrameHeader => ObuType::RedundantFrameHeader, + ParsedObu::TileList => ObuType::TileList, + ParsedObu::Reserved2 => ObuType::Reserved2, + ParsedObu::Reserved3 => ObuType::Reserved3, + ParsedObu::Reserved4 => ObuType::Reserved4, + ParsedObu::Reserved5 => ObuType::Reserved5, + ParsedObu::Reserved6 => ObuType::Reserved6, + ParsedObu::Reserved7 => ObuType::Reserved7, + ParsedObu::Padding => ObuType::Padding, + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Tile { + /// Same as TileOffset in the specification. + pub tile_offset: u32, + /// Same as TileSize in the specification. + pub tile_size: u32, + /// Same as TileRow in the specification. + pub tile_row: u32, + /// Same as TileCol in the specification. + pub tile_col: u32, + // Same as MiRowStart in the specification. + pub mi_row_start: u32, + // Same as MiRowEnd in the specification. + pub mi_row_end: u32, + // Same as MiColStart in the specification. + pub mi_col_start: u32, + // Same as MiColEnd in the specification. + pub mi_col_end: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TileGroupObu<'a> { + /// The OBU backing this tile group. + pub obu: Obu<'a>, + /// Specifies whether tg_start and tg_end are present. If tg_start and + /// tg_end are not present, this tile group covers the entire frame. + pub tile_start_and_end_present_flag: bool, + /// Specifies the zero-based index of the first tile in the current tile + /// group. + pub tg_start: u32, + /// Specifies the zero-based index of the last tile in the current tile + /// group. + pub tg_end: u32, + /// Contains the tiles in this tile group. Use `tile_offset`to index into + /// the OBU data. + /// + /// The tiles in the Vec span from tg_start to tg_end. + pub tiles: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OperatingPoint { + /// Specifies the level that the coded video sequence conforms to when + /// operating point i is selected. + pub seq_level_idx: u8, + /// Specifies the tier that the coded video sequence conforms to when + /// operating point i is selected. + pub seq_tier: u8, + /// Specifies the value of operating_point_idc for the selected operating + /// point. + pub idc: u16, + /// If set, indicates that there is a decoder model associated with + /// operating point i. If not set, indicates that there is not a decoder + /// model associated with operating point i. + pub decoder_model_present_for_this_op: bool, + /// Specifies the time interval between the arrival of the first bit in the + /// smoothing buffer and the subsequent removal of the data that belongs to + /// the first coded frame for operating point op, measured in units of + /// 1/90000 seconds. The length of decoder_buffer_delay is specified by + /// buffer_delay_length_minus_1 + 1, in bits. + pub decoder_buffer_delay: u32, + /// Specifies, in combination with decoder_buffer_delay\[ op \] syntax + /// element, the first bit arrival time of frames to be decoded to the + /// smoothing buffer. encoder_buffer_delay is measured in units of 1/90000 + /// seconds. + pub encoder_buffer_delay: u32, + /// If set, indicates that the smoothing buffer operates in low-delay mode + /// for operating point op. In low-delay mode late decode times and buffer + /// underflow are both permitted. If not set, indicates that the smoothing + /// buffer operates in strict mode, where buffer underflow is not allowed. + pub low_delay_mode_flag: bool, + /// If set, indicates that initial_display_delay_minus_1 is specified for + /// operating point i. If not set, indicates that + /// initial_display_delay_minus_1 is not specified for operating point i. + pub initial_display_delay_present_for_this_op: bool, + /// Plus 1 specifies, for operating point i, the number of decoded frames + /// that should be present in the buffer pool before the first presentable + /// frame is displayed. This will ensure that all presentable frames in the + /// sequence can be decoded at or before the time that they are scheduled + /// for display. If not signaled then initial_display_delay_minus_1\[ i \] = + /// BUFFER_POOL_MAX_SIZE - 1. + pub initial_display_delay_minus_1: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TimingInfo { + /// The number of time units of a clock operating at the frequency + /// time_scale Hz that corresponds to one increment of a clock tick counter. + /// A display clock tick, in seconds, is equal to num_units_in_display_tick + /// divided by time_scale: + pub num_units_in_display_tick: u32, + /// The number of time units that pass in one second. + pub time_scale: u32, + /// If set, indicates that pictures should be displayed according to their + /// output order with the number of ticks between two consecutive pictures + /// (without dropping frames) specified by num_ticks_per_picture_minus_1 + + /// 1. If not set, indicates that the interval between two consecutive + /// pictures is not specified. + pub equal_picture_interval: bool, + /// Plus 1 specifies the number of clock ticks corresponding to output time + /// between two consecutive pictures in the output order. + pub num_ticks_per_picture_minus_1: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DecoderModelInfo { + /// Plus 1 specifies the length of the decoder_buffer_delay and the + /// encoder_buffer_delay syntax elements, in bits. + pub buffer_delay_length_minus_1: u8, + /// The number of time units of a decoding clock operating at the frequency + /// time_scale Hz that corresponds to one increment of a clock tick counter: + pub num_units_in_decoding_tick: u32, + /// Plus 1 specifies the length of the buffer_removal_time syntax element, + /// in bits. + pub buffer_removal_time_length_minus_1: u8, + /// Plus 1 specifies the length of the frame_presentation_time syntax + /// element, in bits. + pub frame_presentation_time_length_minus_1: u32, +} + +/// Defined by the “Color primaries” section of ISO/IEC 23091-4/ITU-T H.273 +/// See 6.4.2 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum ColorPrimaries { + Bt709 = 1, + #[default] + Unspecified = 2, + Bt470M = 4, + Bt470bg = 5, + Bt601 = 6, + Smpte240 = 7, + GenericFilm = 8, + Bt2020 = 9, + Xyz = 10, + Smpte431 = 11, + Smpte432 = 12, + Ebu3213 = 22, +} + +impl TryFrom for ColorPrimaries { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 1 => Ok(ColorPrimaries::Bt709), + 2 => Ok(ColorPrimaries::Unspecified), + 4 => Ok(ColorPrimaries::Bt470M), + 5 => Ok(ColorPrimaries::Bt470bg), + 6 => Ok(ColorPrimaries::Bt601), + 7 => Ok(ColorPrimaries::Smpte240), + 8 => Ok(ColorPrimaries::GenericFilm), + 9 => Ok(ColorPrimaries::Bt2020), + 10 => Ok(ColorPrimaries::Xyz), + 11 => Ok(ColorPrimaries::Smpte431), + 12 => Ok(ColorPrimaries::Smpte432), + 22 => Ok(ColorPrimaries::Ebu3213), + _ => Err(format!("Invalid ColorPrimaries {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum TransferCharacteristics { + Reserved0 = 0, + Bt709 = 1, + #[default] + Unspecified = 2, + Reserved3 = 3, + Bt470m = 4, + Bt470bg = 5, + Bt601 = 6, + Smpte240 = 7, + Linear = 8, + Log100 = 9, + Log100Sqrt10 = 10, + Iec61966 = 11, + Bt1361 = 12, + Srgb = 13, + Bt202010Bit = 14, + Bt202012Bit = 15, + Smpte2084 = 16, + Smpte428 = 17, + Hlg = 18, +} + +impl TryFrom for TransferCharacteristics { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(TransferCharacteristics::Reserved0), + 1 => Ok(TransferCharacteristics::Bt709), + 2 => Ok(TransferCharacteristics::Unspecified), + 3 => Ok(TransferCharacteristics::Reserved3), + 4 => Ok(TransferCharacteristics::Bt470m), + 5 => Ok(TransferCharacteristics::Bt470bg), + 6 => Ok(TransferCharacteristics::Bt601), + 7 => Ok(TransferCharacteristics::Smpte240), + 8 => Ok(TransferCharacteristics::Linear), + 9 => Ok(TransferCharacteristics::Log100), + 10 => Ok(TransferCharacteristics::Log100Sqrt10), + 11 => Ok(TransferCharacteristics::Iec61966), + 12 => Ok(TransferCharacteristics::Bt1361), + 13 => Ok(TransferCharacteristics::Srgb), + 14 => Ok(TransferCharacteristics::Bt202010Bit), + 15 => Ok(TransferCharacteristics::Bt202012Bit), + 16 => Ok(TransferCharacteristics::Smpte2084), + 17 => Ok(TransferCharacteristics::Smpte428), + 18 => Ok(TransferCharacteristics::Hlg), + _ => Err(format!("Invalid TransferCharacteristics {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum BitDepth { + #[default] + Depth8 = 0, + Depth10 = 1, + Depth12 = 2, +} + +impl TryFrom for BitDepth { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(BitDepth::Depth8), + 1 => Ok(BitDepth::Depth10), + 2 => Ok(BitDepth::Depth12), + _ => Err(format!("Invalid BitDepth {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum MatrixCoefficients { + Identity = 0, + Bt709 = 1, + #[default] + Unspecified = 2, + Reserved3 = 3, + Fcc = 4, + Bt470bg = 5, + Bt601 = 6, + Smpte240 = 7, + Ycgco = 8, + Bt2020Ncl = 9, + Bt2020Cl = 10, + Smpte2085 = 11, + ChromaDerivedNcl = 12, + ChromaDerivedCl = 13, + Ictcp = 14, +} + +impl TryFrom for MatrixCoefficients { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(MatrixCoefficients::Identity), + 1 => Ok(MatrixCoefficients::Bt709), + 2 => Ok(MatrixCoefficients::Unspecified), + 3 => Ok(MatrixCoefficients::Reserved3), + 4 => Ok(MatrixCoefficients::Fcc), + 5 => Ok(MatrixCoefficients::Bt470bg), + 6 => Ok(MatrixCoefficients::Bt601), + 7 => Ok(MatrixCoefficients::Smpte240), + 8 => Ok(MatrixCoefficients::Ycgco), + 9 => Ok(MatrixCoefficients::Bt2020Ncl), + 10 => Ok(MatrixCoefficients::Bt2020Cl), + 11 => Ok(MatrixCoefficients::Smpte2085), + 12 => Ok(MatrixCoefficients::ChromaDerivedNcl), + 13 => Ok(MatrixCoefficients::ChromaDerivedCl), + 14 => Ok(MatrixCoefficients::Ictcp), + _ => Err(format!("Invalid MatrixCoefficients {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum ChromaSamplePosition { + #[default] + Unknown = 0, + Vertical = 1, + Colocated = 2, + Reserved = 3, +} + +impl TryFrom for ChromaSamplePosition { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ChromaSamplePosition::Unknown), + 1 => Ok(ChromaSamplePosition::Vertical), + 2 => Ok(ChromaSamplePosition::Colocated), + 3 => Ok(ChromaSamplePosition::Reserved), + _ => Err(format!("Invalid ChromaSamplePosition {}", value)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ColorConfig { + /// Syntax elements which, together with seq_profile, determine the bit + /// depth. + pub high_bitdepth: bool, + /// Syntax elements which, together with seq_profile, determine the bit + /// depth. + pub twelve_bit: bool, + /// If set, indicates that the video does not contain U and V color planes. + /// If not set, indicates that the video contains Y, U, and V color planes. + pub mono_chrome: bool, + /// If set, specifies that color_primaries, transfer_characteristics, and + /// matrix_coefficients are present. If not set, specifies that + /// color_primaries, transfer_characteristics and matrix_coefficients are + /// not present. + pub color_description_present_flag: bool, + /// Defined by the “Color primaries” section of ISO/IEC 23091-4/ITU-T H.273. + pub color_primaries: ColorPrimaries, + /// Defined by the “Transfer characteristics” section of ISO/IEC + /// 23091-4/ITU-T H.273. + pub transfer_characteristics: TransferCharacteristics, + /// Defined by the “Matrix coefficients” section of ISO/IEC 23091-4/ITU-T + /// H.273. + pub matrix_coefficients: MatrixCoefficients, + /// Binary value that is associated with the VideoFullRangeFlag variable + /// specified in ISO/IEC 23091-4/ITU- T H.273. color range equal to 0 shall + /// be referred to as the studio swing representation and color range equal + /// to 1 shall be referred to as the full swing representation for all + /// intents relating to this specification. + pub color_range: bool, + /// Specify the chroma subsampling format + pub subsampling_x: bool, + /// Specify the chroma subsampling format + pub subsampling_y: bool, + /// Specifies the sample position for subsampled streams + pub chroma_sample_position: ChromaSamplePosition, + /// If set, indicates that the U and V planes may have separate delta + /// quantizer values. If not set, indicates that the U and V planes will + /// share the same delta quantizer value. + pub separate_uv_delta_q: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SequenceHeaderObu { + /// The OBU header from the OBU that generated this sequence. + pub obu_header: ObuHeader, + /// Specifies the features that can be used in the coded video sequence. + pub seq_profile: Profile, + /// If set, specifies that the coded video sequence contains only one coded + /// frame. If not set, specifies that the coded video sequence contains one + /// or more coded frames. + pub still_picture: bool, + /// Specifies that the syntax elements not needed by a still picture are + /// omitted. + pub reduced_still_picture_header: bool, + /// Specifies the number of bits minus 1 used for transmitting the frame + /// width syntax elements. + pub frame_width_bits_minus_1: u8, + /// Specifies the number of bits minus 1 used for transmitting the frame + /// height syntax elements. + pub frame_height_bits_minus_1: u8, + /// Specifies the maximum frame width minus 1 for the frames represented by + /// this sequence header. + pub max_frame_width_minus_1: u16, + /// Specifies the maximum frame height minus 1 for the frames represented by + /// this sequence header. + pub max_frame_height_minus_1: u16, + /// Specifies whether frame id numbers are present in the coded video + /// sequence. + pub frame_id_numbers_present_flag: bool, + /// Specifies the number of bits minus 2 used to encode delta_frame_id + /// syntax elements. + pub delta_frame_id_length_minus_2: u32, + /// Used to calculate the number of bits used to encode the frame_id syntax + /// element. + pub additional_frame_id_length_minus_1: u32, + /// When set, indicates that superblocks contain 128x128 luma samples. When + /// not set, it indicates that superblocks contain 64x64 luma samples. (The + /// number of contained chroma samples depends on subsampling_x and + /// subsampling_y.) + pub use_128x128_superblock: bool, + /// When set, specifies that the use_filter_intra syntax element may be + /// present. When not set, specifies that the use_filter_intra syntax + /// element will not be present. + pub enable_filter_intra: bool, + /// Specifies whether the intra edge filtering process should be enabled. + pub enable_intra_edge_filter: bool, + /// When set, specifies that the mode info for inter blocks may contain the + /// syntax element interintra. If not set, specifies that the syntax element + /// interintra will not be present. + pub enable_interintra_compound: bool, + /// When set, specifies that the mode info for inter blocks may contain the + /// syntax element compound_type. When not set, specifies that the syntax + /// element compound_type will not be present. + pub enable_masked_compound: bool, + /// When set, indicates that the allow_warped_motion syntax element may be + /// present. When not set, indicates that the allow_warped_motion syntax + /// element will not be present. + pub enable_warped_motion: bool, + /// When set, indicates that tools based on the values of order hints may be + /// used. When not set, indicates that tools based on order hints are + /// disabled. + pub enable_order_hint: bool, + /// When set, indicates that the inter prediction filter type may be + /// specified independently in the horizontal and vertical directions. If + /// the flag is not set, only one filter type may be specified, which is + /// then used in both directions. + pub enable_dual_filter: bool, + /// If set, indicates that the distance weights process may be used for + /// inter prediction. + pub enable_jnt_comp: bool, + /// If set, indicates that the use_ref_frame_mvs syntax element may be + /// present. If not set, indicates that the use_ref_frame_mvs syntax element + /// will not be present. + pub enable_ref_frame_mvs: bool, + /// If not set, indicates that the seq_force_screen_content_tools syntax + /// element will be present. If set, indicates that + /// seq_force_screen_content_tools should be set equal to + /// SELECT_SCREEN_CONTENT_TOOLS. + pub seq_choose_screen_content_tools: bool, + /// Equal to SELECT_SCREEN_CONTENT_TOOLS indicates that the + /// allow_screen_content_tools syntax element will be present in the frame + /// header. Otherwise, seq_force_screen_content_tools contains the value for + /// allow_screen_content_tools. + pub seq_force_screen_content_tools: u32, + /// If not set, indicates that the seq_force_integer_mv syntax element will + /// be present. If set, indicates that seq_force_integer_mv should be set + /// equal to SELECT_INTEGER_MV. + pub seq_choose_integer_mv: bool, + /// Equal to SELECT_INTEGER_MV indicates that the force_integer_mv syntax + /// element will be present in the frame header (providing + /// allow_screen_content_tools is equal to 1). Otherwise, + /// seq_force_integer_mv contains the value for force_integer_mv. + pub seq_force_integer_mv: u32, + /// Used to compute OrderHintBits. + pub order_hint_bits_minus_1: i32, + /// Specifies the number of bits used for the order_hint syntax element. + pub order_hint_bits: i32, + /// If set, specifies that the use_superres syntax element will be present + /// in the uncompressed header. If not set, specifies that the use_superres + /// syntax element will not be present (instead use_superres will be set to + /// 0 in the uncompressed header without being read). + pub enable_superres: bool, + /// If set, specifies that cdef filtering may be enabled. If not set, + /// specifies that cdef filtering is disabled. + pub enable_cdef: bool, + /// If set, specifies that loop restoration filtering may be enabled. If + /// not set, specifies that loop restoration filtering is disabled. + pub enable_restoration: bool, + /// Specifies whether film grain parameters are present in the coded video + /// sequence. + pub film_grain_params_present: bool, + /// Indicates the number of operating points minus 1 present in the coded + /// video sequence. An operating point specifies which spatial and temporal + /// layers should be decoded. + pub operating_points_cnt_minus_1: u32, + /// The set of operating points. + pub operating_points: [OperatingPoint; MAX_NUM_OPERATING_POINTS], + /// Specifies whether decoder model information is present in the coded + /// video sequence. + pub decoder_model_info_present_flag: bool, + /// The decoder model info. + pub decoder_model_info: DecoderModelInfo, + /// Specifies whether initial display delay information is present in the + /// coded video sequence. + pub initial_display_delay_present_flag: bool, + /// Specifies whether timing info is present in the coded video sequence. + pub timing_info_present_flag: bool, + /// The timing info. + pub timing_info: TimingInfo, + /// The color config. + pub color_config: ColorConfig, + + /* CamelCase variables in the specification */ + pub bit_depth: BitDepth, + pub num_planes: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StreamInfo { + pub seq_header: Rc, + pub render_width: u32, + pub render_height: u32, +} + +/// A TemporalDelimiterOBU +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TemporalDelimiterObu { + pub obu_header: ObuHeader, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum InterpolationFilter { + #[default] + EightTap = 0, + EightTapSmooth = 1, + EightTapSharp = 2, + Bilinear = 3, + Switchable = 4, +} + +impl TryFrom for InterpolationFilter { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(InterpolationFilter::EightTap), + 1 => Ok(InterpolationFilter::EightTapSmooth), + 2 => Ok(InterpolationFilter::EightTapSharp), + 3 => Ok(InterpolationFilter::Bilinear), + 4 => Ok(InterpolationFilter::Switchable), + _ => Err(format!("Invalid InterpolationFilter {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum TxModes { + #[default] + Only4x4 = 0, + Largest = 1, + Select = 2, +} + +impl TryFrom for TxModes { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(TxModes::Only4x4), + 1 => Ok(TxModes::Largest), + 2 => Ok(TxModes::Select), + _ => Err(format!("Invalid TxModes {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum FrameRestorationType { + #[default] + None = 0, + Wiener = 1, + Sgrproj = 2, + Switchable = 3, +} + +impl TryFrom for FrameRestorationType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(FrameRestorationType::None), + 1 => Ok(FrameRestorationType::Wiener), + 2 => Ok(FrameRestorationType::Sgrproj), + 3 => Ok(FrameRestorationType::Switchable), + _ => Err(format!("Invalid FrameRestorationType {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum ReferenceFrameType { + #[default] + Intra = 0, + Last = 1, + Last2 = 2, + Last3 = 3, + Golden = 4, + BwdRef = 5, + AltRef2 = 6, + AltRef = 7, +} + +impl TryFrom for ReferenceFrameType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ReferenceFrameType::Intra), + 1 => Ok(ReferenceFrameType::Last), + 2 => Ok(ReferenceFrameType::Last2), + 3 => Ok(ReferenceFrameType::Last3), + 4 => Ok(ReferenceFrameType::Golden), + 5 => Ok(ReferenceFrameType::BwdRef), + 6 => Ok(ReferenceFrameType::AltRef2), + 7 => Ok(ReferenceFrameType::AltRef), + _ => Err(format!("Invalid ReferenceFrameType {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum WarpModelType { + #[default] + Identity = 0, + Translation = 1, + RotZoom = 2, + Affine = 3, +} + +impl TryFrom for WarpModelType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(WarpModelType::Identity), + 1 => Ok(WarpModelType::Translation), + 2 => Ok(WarpModelType::RotZoom), + 3 => Ok(WarpModelType::Affine), + _ => Err(format!("Invalid WarpModelType {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum FrameType { + #[default] + KeyFrame = 0, + InterFrame = 1, + IntraOnlyFrame = 2, + SwitchFrame = 3, +} + +impl TryFrom for FrameType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(FrameType::KeyFrame), + 1 => Ok(FrameType::InterFrame), + 2 => Ok(FrameType::IntraOnlyFrame), + 3 => Ok(FrameType::SwitchFrame), + _ => Err(format!("Invalid FrameType {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum TxMode { + #[default] + Only4x4 = 0, + Largest = 1, + Select = 2, +} + +impl TryFrom for TxMode { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(TxMode::Only4x4), + 1 => Ok(TxMode::Largest), + 2 => Ok(TxMode::Select), + _ => Err(format!("Invalid TxMode {}", value)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FrameObu<'a> { + pub header: FrameHeaderObu, + pub tile_group: TileGroupObu<'a>, +} + +/// A FrameHeaderOBU +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FrameHeaderObu { + /// The original OBU header. This may be from a FrameOBU or a FrameHeaderOBU + /// directly. + pub obu_header: ObuHeader, + /// If set, indicates the frame indexed by frame_to_show_map_idx is to be + /// output; If not set, indicates that further processing is required. + pub show_existing_frame: bool, + /// Specifies the frame to be output. It is only available if + /// show_existing_frame is set. + pub frame_to_show_map_idx: u8, + /// Specifies the length of the frame_presentation_time syntax element, in + /// bits. + pub frame_presentation_time: u32, + /// Provides the frame id number for the frame to output. + pub display_frame_id: u32, + /// Specifies the type of the frame + pub frame_type: FrameType, + /// If set, specifies that this frame should be immediately output once + /// decoded. If not set specifies that this frame should not be + /// immediately output. (It may be output later if a later uncompressed + /// header uses show_existing_frame is set). + pub show_frame: bool, + /// When set, specifies that the frame may be output using the + /// show_existing_frame mechanism. When not set, specifies that this frame + /// will not be output using the show_existing_frame mechanism. + pub showable_frame: bool, + /// If set, indicates that error resilient mode is enabled; + /// error_resilient_mode equal to 0 indicates that error resilient mode is + /// disabled. + pub error_resilient_mode: bool, + /// Specifies whether the CDF update in the symbol decoding process should + /// be disabled. + pub disable_cdf_update: bool, + /// When set, indicates that intra blocks may use palette encoding; When not + /// set, indicates that palette encoding is never used. + pub allow_screen_content_tools: u32, + /// If set, specifies that motion vectors will always be integers. If not + /// set, specifies that motion vectors can contain fractional bits. + pub force_integer_mv: u32, + /// Specifies the frame id number for the current frame. Frame id numbers + /// are additional information that do not affect the decoding process, but + /// provide decoders with a way of detecting missing reference frames so + /// that appropriate action can be taken. + pub current_frame_id: u32, + /// If not set, specifies that the frame size is equal to the size in the + /// sequence header. If set, specifies that the frame size will either be + /// specified as the size of one of the reference frames, or computed from + /// the frame_width_minus_1 and frame_height_minus_1 syntax elements. + pub frame_size_override_flag: bool, + /// Specifies OrderHintBits least significant bits of the expected output + /// order for this frame. + pub order_hint: u32, + /// Specifies which reference frame contains the CDF values and other state + /// that should be loaded at the start of the frame. + pub primary_ref_frame: u32, + /// If set, specifies that buffer_removal_time is present. If not set, + /// specifies that buffer_removal_time is not present. + pub buffer_removal_time_present_flag: bool, + /// Specifies the frame removal time in units of DecCT clock ticks counted + /// from the removal time of the last random access point for operating + /// point opNum. buffer_removal_time is signaled as a fixed length unsigned + /// integer with a length in bits given by + /// buffer_removal_time_length_minus_1 + 1. + pub buffer_removal_time: Vec, + /// Contains a bitmask that specifies which reference frame slots will be + /// updated with the current frame after it is decoded. + pub refresh_frame_flags: u32, + /// Specifies the expected output order hint for each reference frame. + pub ref_order_hint: [u32; NUM_REF_FRAMES], + /// If set, indicates that intra block copy may be used in this frame. If + /// not set indicates that intra block copy is not allowed in this frame. + pub allow_intrabc: bool, + /// If set, indicates that only two reference frames are explicitly + /// signaled. If not set, indicates that all reference frames are explicitly + /// signaled. + pub frame_refs_short_signaling: bool, + /// Specifies the reference frame to use for LAST_FRAME. + pub last_frame_idx: u8, + /// Specifies the reference frame to use for GOLDEN_FRAME. + pub gold_frame_idx: u8, + /// Specifies which reference frames are used by inter frames + pub ref_frame_idx: [u8; REFS_PER_FRAME], + /// If not set, specifies that motion vectors are specified to quarter pel + /// precision; If set, specifies that motion vectors are specified to eighth + /// pel precision. + pub allow_high_precision_mv: bool, + /// If not set, specifies that only the SIMPLE motion mode will be used. + pub is_motion_mode_switchable: bool, + /// If set, specifies that motion vector information from a previous frame + /// can be used when decoding the current frame. If not set, specifies that + /// this information will not be used. + pub use_ref_frame_mvs: bool, + /// If set, indicates that the end of frame CDF update is disabled; If not + /// set, indicates that the end of frame CDF update is enabled. + pub disable_frame_end_update_cdf: bool, + /// If set, indicates that the syntax element motion_mode may be present. + /// If not set, indicates that the syntax element motion_mode will not be + /// present + pub allow_warped_motion: bool, + /// If set, specifies that the frame is restricted to a reduced subset of + /// the full set of transform types. + pub reduced_tx_set: bool, + /// If not set, means that the render width and height are inferred from the + /// frame width and height. If set, means that the render width and height + /// are explicitly coded. + pub render_and_frame_size_different: bool, + /// If not set, indicates that no upscaling is needed. If set, indicates + /// that upscaling is needed. + pub use_superres: bool, + /// If set indicates that the filter selection is signaled at the block + /// level; If not set, indicates that the filter selection is signaled at + /// the frame level. + pub is_filter_switchable: bool, + /// The interpolation filter parameters. + pub interpolation_filter: InterpolationFilter, + /// The loop filter parameters. + pub loop_filter_params: LoopFilterParams, + /// The quantization parameters. + pub quantization_params: QuantizationParams, + /// The segmentation parameters. + pub segmentation_params: SegmentationParams, + /// The tile info. + pub tile_info: TileInfo, + /// The CDEF parameters. + pub cdef_params: CdefParams, + /// The loop restoration parameters. + pub loop_restoration_params: LoopRestorationParams, + /// Used to compute TxMode. + pub tx_mode_select: u32, + /// If set specifies that the syntax element skip_mode will be present. If + /// not set, specifies that skip_mode will not be used for this frame. + pub skip_mode_present: bool, + /// If set, specifies that the mode info for inter blocks contains the + /// syntax element comp_mode that indicates whether to use single or + /// compound reference prediction. If not set, specifies that all inter + /// blocks will use single prediction. + pub reference_select: bool, + /// The global motion parameters. + pub global_motion_params: GlobalMotionParams, + /// The film grain parameters. + pub film_grain_params: FilmGrainParams, + + /* CamelCase variables */ + pub superres_denom: u32, + pub frame_is_intra: bool, + pub order_hints: [u32; NUM_REF_FRAMES], + pub ref_frame_sign_bias: [bool; NUM_REF_FRAMES], + pub coded_lossless: bool, + pub all_lossless: bool, + pub lossless_array: [bool; MAX_SEGMENTS], + pub seg_qm_level: [[u32; MAX_SEGMENTS]; 3], + pub upscaled_width: u32, + pub frame_width: u32, + pub frame_height: u32, + pub render_width: u32, + pub render_height: u32, + pub tx_mode: TxMode, + pub skip_mode_frame: [u32; 2], + pub mi_cols: u32, + pub mi_rows: u32, + pub header_bytes: usize, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LoopFilterParams { + /// An array containing loop filter strength values. Different loop filter + /// strength values from the array are used depending on the image plane + /// being filtered, and the edge direction (vertical or horizontal) being + /// filtered. + pub loop_filter_level: [u8; 4], + /// Indicates the sharpness level. The loop_filter_level and + /// loop_filter_sharpness together determine when a block edge is filtered, + /// and by how much the filtering can change the sample values. + pub loop_filter_sharpness: u8, + /// If set, means that the filter level depends on the mode and reference + /// frame used to predict a block. If not set, means that the filter level + /// does not depend on the mode and reference frame. + pub loop_filter_delta_enabled: bool, + /// If set, means that additional syntax elements are present that specify + /// which mode and reference frame deltas are to be updated. + /// loop_filter_delta_update equal to 0 means that these syntax elements are + /// not present. + pub loop_filter_delta_update: bool, + /// Contains the adjustment needed for the filter level based on the chosen + /// reference frame. If this syntax element is not present, it maintains + /// its previous value. + pub loop_filter_ref_deltas: [i8; TOTAL_REFS_PER_FRAME], + /// Contains the adjustment needed for the filter level based on the chosen + /// mode. If this syntax element is not present in the, it maintains its + /// previous value. + pub loop_filter_mode_deltas: [i8; 2], + /// Specifies whether loop filter delta values are present. + pub delta_lf_present: bool, + /// Specifies the left shift which should be applied to decoded loop filter + /// delta values. + pub delta_lf_res: u8, + /// If set, specifies that separate loop filter deltas are sent for + /// horizontal luma edges, vertical luma edges, the U edges, and the V + /// edges. If not set, specifies that the same loop filter delta is used for + /// all edges. + pub delta_lf_multi: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct QuantizationParams { + /// Indicates the base frame qindex. This is used for Y AC coefficients and + /// as the base value for the other quantizers. + pub base_q_idx: u32, + /// Indicates the base frame qindex. This is used for Y AC coefficients and + /// as the base value for the other quantizers. + pub diff_uv_delta: bool, + /// Specifies that the quantizer matrix will be used to compute quantizers. + pub using_qmatrix: bool, + /// Specifies the level in the quantizer matrix that should be used for luma + /// plane decoding. + pub qm_y: u32, + /// Specifies the level in the quantizer matrix that should be used for + /// chroma U plane decoding. + pub qm_u: u32, + /// Specifies the level in the quantizer matrix that should be used for + /// chroma V plane decoding. + pub qm_v: u32, + /// Specifies whether quantizer index delta values are present. + pub delta_q_present: bool, + /// Specifies the left shift which should be applied to decoded quantizer + /// index delta values. + pub delta_q_res: u32, + /// Same as DeltaQYDc + pub delta_q_y_dc: i32, + /// Same as DeltaQUDc + pub delta_q_u_dc: i32, + /// Same as DeltaQUAc + pub delta_q_u_ac: i32, + /// Same as DeltaQVDc + pub delta_q_v_dc: i32, + /// Same as DeltaQVAc + pub delta_q_v_ac: i32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SegmentationParams { + /// If set, indicates that this frame makes use of the segmentation tool; If + /// not set, indicates that the frame does not use segmentation. + pub segmentation_enabled: bool, + /// If set, indicates that the segmentation map are updated during the + /// decoding of this frame. If not set, means that the segmentation map from + /// the previous frame is used. + pub segmentation_update_map: bool, + /// If set, indicates that the updates to the segmentation map are coded + /// relative to the existing segmentation map. If not set, indicates that + /// the new segmentation map is coded without reference to the existing + /// segmentation map. + pub segmentation_temporal_update: bool, + /// If set, indicates that new parameters are about to be specified for each + /// segment. If not set, indicates that the segmentation parameters should + /// keep their existing values. + pub segmentation_update_data: bool, + /// If not set, indicates that the corresponding feature is unused and has + /// value equal to 0. If set, indicates that the feature value is coded. + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], + /// Specifies the feature data for a segment feature. + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], + /// Same as SegIdPreSkip + pub seg_id_pre_skip: bool, + /// Same as LastActiveSegId + pub last_active_seg_id: u8, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TileInfo { + /// If set, means that the tiles are uniformly spaced across the frame. (In + /// other words, all tiles are the same size except for the ones at the + /// right and bottom edge which can be smaller.) If not set, means that the + /// tile sizes are coded. + pub uniform_tile_spacing_flag: bool, + /// Used to compute TileColsLog2. + pub increment_tile_rows_log2: u32, + /// Specifies the width of a tile minus 1 in units of superblocks. + pub width_in_sbs_minus_1: [u32; MAX_TILE_COLS], + /// Specifies the height of a tile minus 1 in units of superblocks. + pub height_in_sbs_minus_1: [u32; MAX_TILE_ROWS], + /// Specifies which tile to use for the CDF update + pub context_update_tile_id: u32, + /// An array specifying the start column (in units of 4x4 luma samples) for + /// each tile across the image. + pub mi_col_starts: [u32; MAX_TILE_COLS + 1], + /// An array specifying the start row (in units of 4x4 luma samples) for + /// each tile down the image. + pub mi_row_starts: [u32; MAX_TILE_ROWS + 1], + /// Specifies the base 2 logarithm of the desired number of tiles down the + /// frame. + pub tile_cols_log2: u32, + /// Specifies the number of tiles across the frame. + pub tile_cols: u32, + /// Specifies the base 2 logarithm of the desired number of tiles down the + /// frame. + pub tile_rows_log2: u32, + /// Secifies the number of tiles down the frame + pub tile_rows: u32, + /// Specifies the number of bytes needed to code each tile size. + pub tile_size_bytes: u32, +} + +impl Default for TileInfo { + fn default() -> Self { + Self { + uniform_tile_spacing_flag: Default::default(), + increment_tile_rows_log2: Default::default(), + width_in_sbs_minus_1: [0; MAX_TILE_COLS], + height_in_sbs_minus_1: [0; MAX_TILE_ROWS], + context_update_tile_id: Default::default(), + mi_col_starts: [0; MAX_TILE_COLS + 1], + mi_row_starts: [0; MAX_TILE_ROWS + 1], + tile_cols_log2: Default::default(), + tile_cols: Default::default(), + tile_rows_log2: Default::default(), + tile_rows: Default::default(), + tile_size_bytes: Default::default(), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CdefParams { + /// Controls the amount of damping in the deringing filter. + pub cdef_damping: u32, + /// Specifies the number of bits needed to specify which CDEF filter to + /// apply. + pub cdef_bits: u32, + /// Specify the strength of the primary filter. + pub cdef_y_pri_strength: [u32; CDEF_MAX], + /// Specify the strength of the secondary filter. + pub cdef_y_sec_strength: [u32; CDEF_MAX], + /// Specify the strength of the primary filter. + pub cdef_uv_pri_strength: [u32; CDEF_MAX], + /// Specify the strength of the secondary filter. + pub cdef_uv_sec_strength: [u32; CDEF_MAX], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LoopRestorationParams { + /// Specifies if the luma restoration size should be halved. + pub lr_unit_shift: u8, + /// Only present for 4:2:0 formats and specifies if the chroma size should + /// be half the luma size. + pub lr_uv_shift: u8, + /// Same as FrameRestorationType in the specification. + pub frame_restoration_type: [FrameRestorationType; MAX_NUM_PLANES], + /// Same as LoopRestorationSize in the specification. + pub loop_restoration_size: [u16; MAX_NUM_PLANES], + /// Same as UsesLr in the specification. + pub uses_lr: bool, + /// Same as UsesChromaLr in the specification. + pub uses_chroma_lr: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GlobalMotionParams { + /// Specifies whether global motion parameters are present for a particular + /// reference frame. + pub is_global: [bool; NUM_REF_FRAMES], + /// Specifies whether a particular reference frame uses rotation and zoom + /// global motion. + pub is_rot_zoom: [bool; NUM_REF_FRAMES], + /// Specifies whether a particular reference frame uses translation global + /// motion. + pub is_translation: [bool; NUM_REF_FRAMES], + /// gm_params\[ ref \]\[ j \] is set equal to SavedGmParams\[ + /// frame_to_show_map_idx \]\[ ref \]\[ j \] for ref = LAST_FRAME..ALTREF_FRAME, + /// for j = 0..5. + pub gm_params: [[i32; 6]; NUM_REF_FRAMES], + /// Whether the parameters are valid (see warpValid and section 7.11.3.6) + pub warp_valid: [bool; NUM_REF_FRAMES], + /// Same as GmType. + pub gm_type: [WarpModelType; NUM_REF_FRAMES], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FilmGrainParams { + /// If set, specifies that film grain should be added to this frame. If not + /// set, specifies that film grain should not be added. + pub apply_grain: bool, + /// Specifies the starting value for the pseudo-random numbers used during + /// film grain synthesis. + pub grain_seed: u16, + /// If set means that a new set of parameters should be sent. If not set, + /// means that the previous set of parameters should be used. + pub update_grain: bool, + /// Indicates which reference frame contains the film grain parameters to be + /// used for this frame. + pub film_grain_params_ref_idx: u8, + /// Specifies the number of points for the piece-wise linear scaling + /// function of the luma component. + pub num_y_points: u8, + /// Represents the x (luma value) coordinate for the i-th point of the + /// piecewise linear scaling function for luma component. The values are + /// signaled on the scale of 0..255. (In case of 10 bit video, these values + /// correspond to luma values divided by 4. In case of 12 bit video, these + /// values correspond to luma values divided by 16.) + pub point_y_value: [u8; MAX_NUM_Y_POINTS], + /// Pepresents the scaling (output) value for the i-th point of the + /// piecewise linear scaling function for luma component. + pub point_y_scaling: [u8; MAX_NUM_Y_POINTS], + /// Specifies that the chroma scaling is inferred from the luma scaling. + pub chroma_scaling_from_luma: bool, + /// Specifies the number of points for the piece-wise linear scaling + /// function of the cb component. + pub num_cb_points: u8, + /// Represents the x coordinate for the i-th point of the piece-wise linear + /// scaling function for cb component. The values are signaled on the scale + /// of 0..255. + pub point_cb_value: [u8; MAX_NUM_CB_POINTS], + /// Represents the scaling (output) value for the i-th point of the + /// piecewise linear scaling function for cb component. + pub point_cb_scaling: [u8; MAX_NUM_CB_POINTS], + /// Specifies represents the number of points for the piece-wise linear + /// scaling function of the cr component. + pub num_cr_points: u8, + /// Represents the x coordinate for the i-th point of the piece-wise linear + /// scaling function for cr component. The values are signaled on the scale + /// of 0..255. + pub point_cr_value: [u8; MAX_NUM_CR_POINTS], + /// Represents the scaling (output) value for the i-th point of the + /// piecewise linear scaling function for cr component. + pub point_cr_scaling: [u8; MAX_NUM_CR_POINTS], + /// Represents the shift – 8 applied to the values of the chroma component. + /// The grain_scaling_minus_8 can take values of 0..3 and determines the + /// range and quantization step of the standard deviation of film grain. + pub grain_scaling_minus_8: u8, + /// Specifies the number of auto-regressive coefficients for luma and chroma. + pub ar_coeff_lag: u32, + /// Specifies auto-regressive coefficients used for the Y plane. + pub ar_coeffs_y_plus_128: [u8; MAX_NUM_POS_LUMA], + /// Specifies auto-regressive coefficients used for the U plane. + pub ar_coeffs_cb_plus_128: [u8; MAX_NUM_POS_LUMA], + /// Specifies auto-regressive coefficients used for the V plane. + pub ar_coeffs_cr_plus_128: [u8; MAX_NUM_POS_LUMA], + /// Specifies the range of the auto-regressive coefficients. Values of 0, 1, + /// 2, and 3 correspond to the ranges for auto-regressive coefficients of + /// [-2, 2), [-1, 1), [-0.5, 0.5) and [-0.25, 0.25) respectively. + pub ar_coeff_shift_minus_6: u8, + /// Specifies how much the Gaussian random numbers should be scaled down + /// during the grain synthesis process. + pub grain_scale_shift: u8, + /// Represents a multiplier for the cb component used in derivation of the + /// input index to the cb component scaling function. + pub cb_mult: u8, + /// Represents a multiplier for the average luma component used in + /// derivation of the input index to the cb component scaling function. + pub cb_luma_mult: u8, + /// Represents an offset used in derivation of the input index to the cb + /// component scaling function. + pub cb_offset: u16, + /// Represents a multiplier for the cr component used in derivation of the + /// input index to the cr component scaling function. + pub cr_mult: u8, + /// Represents a multiplier for the average luma component used in + /// derivation of the input index to the cr component scaling function. + pub cr_luma_mult: u8, + /// Represents an offset used in derivation of the input index to the cr + /// component scaling function. + pub cr_offset: u16, + /// If set, indicates that the overlap between film grain blocks shall be + /// applied. If not set, indicates that the overlap between film grain + /// blocks shall not be applied. + pub overlap_flag: bool, + /// If set, indicates that clipping to the restricted (studio) range shall + /// be applied to the sample values after adding the film grain (see the + /// semantics for color_range for an explanation of studio swing). If not + /// set, indicates that clipping to the full range shall be applied to the + /// sample values after adding the film grain. + pub clip_to_restricted_range: bool, +} + +/// Keeps track of the state of the reference frames in the parser. All +/// variables are CamelCase. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct ReferenceFrameInfo { + /// An array which is indexed by a reference picture slot number. A value of + /// true in the array signifies that the corresponding reference picture + /// slot is valid for use as a reference picture, while a value of false + /// signifies that the corresponding reference picture slot is not valid for + /// use as a reference picture. + ref_valid: bool, + /// Specifies the frame id for each reference frame. + ref_frame_id: u32, + /// See 7.20 Reference Frame Update Process. + ref_upscaled_width: u32, + /// See 7.20 Reference Frame Update Process. + ref_frame_width: u32, + /// See 7.20 Reference Frame Update Process. + ref_frame_height: u32, + /// See 7.20 Reference Frame Update Process. + ref_render_width: u32, + /// See 7.20 Reference Frame Update Process. + ref_render_height: u32, + /// See 7.20 Reference Frame Update Process. + ref_mi_cols: u32, + /// See 7.20 Reference Frame Update Process. + ref_mi_rows: u32, + /// See 7.20 Reference Frame Update Process. + ref_frame_type: FrameType, + /// See 7.20 Reference Frame Update Process. + ref_subsampling_x: bool, + /// See 7.20 Reference Frame Update Process. + ref_subsampling_y: bool, + /// See 7.20 Reference Frame Update Process. + ref_bit_depth: BitDepth, + /// See 7.20 Reference Frame Update Process. + ref_order_hint: u32, + /// The saved segmentation parameters. + segmentation_params: SegmentationParams, + /// The saved global motion parameters. + global_motion_params: GlobalMotionParams, + /// The saved loop filter parameters. + loop_filter_params: LoopFilterParams, + /// The saved film grain parameters. + film_grain_params: FilmGrainParams, + /// The saved tile info parameters. + tile_info: TileInfo, + display_frame_id: u32, + showable_frame: bool, +} + +#[derive(Clone, Debug, Default)] +pub struct AnnexBState { + pub temporal_unit_size: u32, + pub frame_unit_size: u32, + pub temporal_unit_consumed: u32, + pub frame_unit_consumed: u32, +} + +#[derive(Clone, Debug)] +enum StreamFormat { + LowOverhead, + AnnexB(AnnexBState), +} + +#[derive(Debug)] +pub struct Parser { + stream_format: StreamFormat, + operating_point: u32, + /// Same as SeenFrameHeader in the specification + seen_frame_header: bool, + operating_point_idc: u16, + should_probe_for_annexb: bool, + is_first_frame: bool, + ref_info: [ReferenceFrameInfo; NUM_REF_FRAMES], + + /* CamelCase variables */ + mi_cols: u32, + mi_rows: u32, + prev_frame_id: u32, + current_frame_id: u32, + mi_col_starts: [u32; MAX_TILE_COLS + 1], + mi_row_starts: [u32; MAX_TILE_ROWS + 1], + tile_cols_log2: u32, + tile_cols: u32, + tile_rows_log2: u32, + tile_rows: u32, + tile_size_bytes: u32, + + /// We keep this to implement frame_header_copy() in the specification, and to fill in + /// StreamInfo render_width and render_height. + pub last_frame_header: Option, + /// The last SequenceHeaderObu parsed. + pub sequence_header: Option>, +} + +impl Parser { + /// Probes the input data for the Annex B format. Anything other than + /// Ok(true) refers to data in "low-overhead" format instead, as we are trying to parse + fn annexb_probe(data: &[u8]) -> Result { + let mut r = Reader::new(data); + let mut seen_sequence = false; + let mut seen_frame = false; + + // Try reading the first TU and frame unit size + let temporal_unit_size = r.read_leb128()?; + if temporal_unit_size == 0 { + return Ok(false); + } + + let frame_unit_size = r.read_leb128()?; + if frame_unit_size == 0 || frame_unit_size > temporal_unit_size { + return Ok(false); + } + + let obu_length = r.read_leb128()?; + if obu_length == 0 || obu_length > frame_unit_size { + return Ok(false); + } + + // The first OBU in the first frame_unit of each temporal_unit must + // be a temporal delimiter OBU (and this is the only place temporal + // delimiter OBUs can appear) + let header = Self::parse_obu_header(&mut r.clone())?; + if !matches!(header.obu_type, ObuType::TemporalDelimiter) { + return Ok(false); + } + + // Try identifying a sequence and a frame. + r.0.skip_bits(obu_length as usize * 8)?; + let mut num_bytes_read = 0; + + loop { + let obu_length = r.read_leb128()?; + let mut obu_reader = r.clone(); + + r.0.skip_bits(obu_length as usize * 8)?; + num_bytes_read += obu_length; + + if !seen_sequence { + let header = Self::parse_obu_header(&mut obu_reader)?; + seen_sequence = matches!(header.obu_type, ObuType::SequenceHeader); + } + + if !seen_frame { + let header = Self::parse_obu_header(&mut obu_reader)?; + seen_frame = matches!(header.obu_type, ObuType::Frame | ObuType::FrameHeader); + } + + if seen_sequence && seen_frame { + // OK, enough evidence of Annex B format. + return Ok(true); + } + + if num_bytes_read >= frame_unit_size { + // We read what we've identified as the first frame and yet no + // sequence and no actual frames were found. + return Ok(false); + } + } + } + + fn compute_image_size(&mut self, fh: &mut FrameHeaderObu) { + fh.mi_cols = 2 * ((fh.frame_width + 7) >> 3); + fh.mi_rows = 2 * ((fh.frame_height + 7) >> 3); + self.mi_cols = fh.mi_cols; + self.mi_rows = fh.mi_rows; + } + + // 5.9.8 + fn parse_superres_params( + fh: &mut FrameHeaderObu, + r: &mut Reader, + seq: &SequenceHeaderObu, + ) -> Result<(), String> { + if seq.enable_superres { + fh.use_superres = r.0.read_bit()?; + } else { + fh.use_superres = false; + } + + if fh.use_superres { + fh.superres_denom = + r.0.read_bits::(SUPERRES_DENOM_BITS)? + SUPERRES_DENOM_MIN as u32; + } else { + fh.superres_denom = SUPERRES_NUM as u32; + } + + fh.upscaled_width = fh.frame_width; + fh.frame_width = + (fh.upscaled_width * SUPERRES_NUM as u32 + (fh.superres_denom / 2)) / fh.superres_denom; + + Ok(()) + } + + // 7.8 verbatim. + fn set_frame_refs( + &self, + fh: &mut FrameHeaderObu, + ref_order_hint: &[u32; NUM_REF_FRAMES], + ) -> Result<(), String> { + let seq = self.sequence()?; + let mut ref_frame_idx = [-1i32; REFS_PER_FRAME]; + + ref_frame_idx[0] = fh.last_frame_idx.into(); + ref_frame_idx[ReferenceFrameType::Golden as usize - ReferenceFrameType::Last as usize] = + fh.gold_frame_idx.into(); + + let mut used_frame = [false; NUM_REF_FRAMES]; + used_frame[fh.last_frame_idx as usize] = true; + used_frame[fh.gold_frame_idx as usize] = true; + + let cur_frame_hint = 1 << (seq.order_hint_bits - 1); + let mut shifted_order_hints = [0; NUM_REF_FRAMES]; + for i in 0..NUM_REF_FRAMES { + shifted_order_hints[i] = cur_frame_hint + + helpers::get_relative_dist( + seq.enable_order_hint, + seq.order_hint_bits, + ref_order_hint[i].try_into().unwrap(), + fh.order_hint.try_into().unwrap(), + ); + } + + let mut latest_order_hint = shifted_order_hints[fh.last_frame_idx as usize]; + if latest_order_hint >= cur_frame_hint { + return Err("It is a requirement of bitstream conformance that last_order_hint < cur_frame_hint".into()); + } + + let mut earliest_order_hint = shifted_order_hints[fh.gold_frame_idx as usize]; + if earliest_order_hint >= cur_frame_hint { + return Err("It is a requirement of bitstream conformance that gold_order_hint < cur_frame_hint".into()); + } + + let ref_ = helpers::find_latest_backward( + &shifted_order_hints, + &used_frame, + cur_frame_hint, + &mut latest_order_hint, + ); + + if ref_ >= 0 { + ref_frame_idx + [ReferenceFrameType::AltRef as usize - ReferenceFrameType::Last as usize] = ref_; + used_frame[ref_ as usize] = true; + } + + let ref_ = helpers::find_earliest_backward( + &shifted_order_hints, + &used_frame, + cur_frame_hint, + &mut earliest_order_hint, + ); + + if ref_ >= 0 { + ref_frame_idx + [ReferenceFrameType::BwdRef as usize - ReferenceFrameType::Last as usize] = ref_; + used_frame[ref_ as usize] = true; + } + + let ref_ = helpers::find_earliest_backward( + &shifted_order_hints, + &used_frame, + cur_frame_hint, + &mut earliest_order_hint, + ); + + if ref_ >= 0 { + ref_frame_idx + [ReferenceFrameType::AltRef2 as usize - ReferenceFrameType::Last as usize] = ref_; + used_frame[ref_ as usize] = true; + } + + const REF_FRAME_LIST: [usize; 5] = [ + ReferenceFrameType::Last2 as usize - ReferenceFrameType::Last as usize, + ReferenceFrameType::Last3 as usize - ReferenceFrameType::Last as usize, + ReferenceFrameType::BwdRef as usize - ReferenceFrameType::Last as usize, + ReferenceFrameType::AltRef2 as usize - ReferenceFrameType::Last as usize, + ReferenceFrameType::AltRef as usize - ReferenceFrameType::Last as usize, + ]; + + #[allow(clippy::needless_range_loop)] + for i in 0..REFS_PER_FRAME - 2 { + let ref_frame = REF_FRAME_LIST[i]; + + if ref_frame_idx[ref_frame] < 0 { + let ref_ = helpers::find_latest_forward( + &shifted_order_hints, + &used_frame, + cur_frame_hint, + &mut latest_order_hint, + ); + + if ref_ >= 0 { + ref_frame_idx[ref_frame] = ref_; + used_frame[ref_ as usize] = true; + } + } + } + + let mut ref_ = 0; + earliest_order_hint = shifted_order_hints[0]; + #[allow(clippy::needless_range_loop)] + for i in 1..NUM_REF_FRAMES { + let hint = shifted_order_hints[i]; + if hint < earliest_order_hint { + ref_ = i as u8; + earliest_order_hint = hint; + } + } + + fh.ref_frame_idx + .iter_mut() + .zip(ref_frame_idx.iter().copied()) + .for_each(|(dest, src)| *dest = if src < 0 { ref_ } else { src as u8 }); + + Ok(()) + } + + // 5.9.5. + fn parse_frame_size(&mut self, fh: &mut FrameHeaderObu, r: &mut Reader) -> Result<(), String> { + let seq = self.sequence()?; + if fh.frame_size_override_flag { + let n = seq.frame_width_bits_minus_1 + 1; + fh.frame_width = r.0.read_bits::(n as usize)? + 1; + + let n = seq.frame_height_bits_minus_1 + 1; + fh.frame_height = r.0.read_bits::(n as usize)? + 1; + } else { + fh.frame_width = seq.max_frame_width_minus_1 as u32 + 1; + fh.frame_height = seq.max_frame_height_minus_1 as u32 + 1; + } + + Self::parse_superres_params(fh, r, seq)?; + self.compute_image_size(fh); + + Ok(()) + } + + fn parse_render_size(fh: &mut FrameHeaderObu, r: &mut Reader) -> Result<(), String> { + fh.render_and_frame_size_different = r.0.read_bit()?; + if fh.render_and_frame_size_different { + fh.render_width = r.0.read_bits::(16)? + 1; + fh.render_height = r.0.read_bits::(16)? + 1; + } else { + fh.render_width = fh.upscaled_width; + fh.render_height = fh.frame_height; + } + Ok(()) + } + + fn frame_size_with_refs( + &mut self, + fh: &mut FrameHeaderObu, + r: &mut Reader, + ) -> Result<(), String> { + let mut found_ref = false; + let seq = self.sequence()?; + + for i in 0..REFS_PER_FRAME { + found_ref = r.0.read_bit()?; + + if found_ref { + let rf = &self.ref_info[fh.ref_frame_idx[i] as usize]; + fh.upscaled_width = rf.ref_upscaled_width; + fh.frame_width = fh.upscaled_width; + fh.frame_height = rf.ref_frame_height; + fh.render_width = rf.ref_render_width; + fh.render_height = rf.ref_render_height; + break; + } + } + + if !found_ref { + self.parse_frame_size(fh, r)?; + Self::parse_render_size(fh, r)?; + } else { + Self::parse_superres_params(fh, r, seq)?; + self.compute_image_size(fh); + } + + Ok(()) + } + + /// Skip the padding bits, ensuring that they actually make sense. + fn skip_and_check_trailing_bits(r: &mut Reader, obu: &Obu) -> Result<(), String> { + // We can't have that in parse_obu as per the spec, because the reader + // is not initialized on our design at that point, so move the check to + // inside this function. + if obu.data.len() == 0 + || matches!( + obu.header.obu_type, + ObuType::TileList | ObuType::TileGroup | ObuType::Frame + ) + { + return Ok(()); + } + let num_trailing = obu.as_ref().len() as u64 * 8 - r.0.position(); + r.read_trailing_bits(num_trailing)?; + Ok(()) + } + + fn parse_obu_header(r: &mut Reader) -> Result { + let _obu_forbidden_bit = r.0.read_bit()?; + + let mut header = ObuHeader { + obu_type: ObuType::try_from(r.0.read_bits::(4)?)?, + extension_flag: r.0.read_bit()?, + has_size_field: r.0.read_bit()?, + temporal_id: Default::default(), + spatial_id: Default::default(), + }; + + let obu_reserved_1bit = r.0.read_bit()?; + assert!(!obu_reserved_1bit); // Must be set to zero as per spec. + + if header.extension_flag { + header.temporal_id = r.0.read_bits::(3)?; + header.spatial_id = r.0.read_bits::(2)?; + let _ = r.0.read_bits::(3)?; + } + + Ok(header) + } + + /// Parses one OBU from `data`, which can be in Annex B or low-overhead + /// format. + /// + /// `None` may eventually be returned if the OBU is to be dropped. + pub fn read_obu<'a>(&mut self, data: &'a [u8]) -> Result, String> { + if data.is_empty() { + return Err("Empty data".into()); + } + + let mut reader = Reader::new(data); + + if self.should_probe_for_annexb { + // Try probing for Annex B data. + self.stream_format = if matches!(Self::annexb_probe(data), Ok(true)) { + log::debug!("Parsing an Annex B stream"); + StreamFormat::AnnexB(AnnexBState::default()) + } else { + log::debug!("Parsing a low-overhead stream"); + StreamFormat::LowOverhead + }; + + self.should_probe_for_annexb = false; + } + + let obu_length: usize = if let StreamFormat::AnnexB(annexb_state) = &mut self.stream_format + { + // Read the length to skip to the start of the open_bitstream_unit() + // syntax element. + let obu_length = reader.current_annexb_obu_length(annexb_state)?; + match obu_length { + Some(length) => length, + None => return Ok(ObuAction::Drop(reader.consumed(0))), + } + } else { + 0 + }; + + let start_pos = reader.consumed(0); + + // Both "low-overhead" and Annex B are now at the same point, i.e.: a + // open_bitstream_unit() follows. + let header = Self::parse_obu_header(&mut reader)?; + if matches!(self.stream_format, StreamFormat::LowOverhead) { + assert!(header.has_size_field); + } + + let obu_size: usize = if header.has_size_field { + reader.read_leb128()? as usize + } else { + /* trap any bugs when computing the final length */ + obu_length + .checked_sub(1) + .ok_or::("obu_length must be greater than 0".into())? + .checked_sub(usize::from(header.extension_flag)) + .ok_or::("obu_length too short".into())? + }; + + let consumed = reader.consumed(start_pos); + + if let StreamFormat::AnnexB(annexb_state) = &mut self.stream_format { + annexb_state.temporal_unit_consumed += consumed; + annexb_state.frame_unit_consumed += consumed; + + annexb_state.temporal_unit_consumed += u32::try_from(obu_size).unwrap(); + annexb_state.frame_unit_consumed += u32::try_from(obu_size).unwrap(); + } + + assert!(reader.0.position() % 8 == 0); + let start_offset: usize = (reader.0.position() / 8).try_into().unwrap(); + + log::debug!( + "Identified OBU type {:?}, data size: {}, obu_size: {}", + header.obu_type, + start_offset + obu_size, + obu_size + ); + + if header.obu_type != ObuType::SequenceHeader + && header.obu_type != ObuType::TemporalDelimiter + && self.operating_point_idc != 0 + && header.extension_flag + { + let in_temporal_layer = ((self.operating_point_idc >> header.temporal_id) & 1) != 0; + let in_spatial_layer = ((self.operating_point_idc >> (header.spatial_id + 8)) & 1) != 0; + if !in_temporal_layer || !in_spatial_layer { + log::debug!("Dropping obu as per drop_obu() in the specification",); + return Ok(ObuAction::Drop(reader.consumed(0))); + } + } + + Ok(ObuAction::Process(Obu { + header, + data: Cow::from(&data[start_offset..start_offset + obu_size]), + bytes_used: start_offset + obu_size, + })) + } + + fn parse_color_config(s: &mut SequenceHeaderObu, r: &mut Reader) -> Result<(), String> { + let cc = &mut s.color_config; + + cc.high_bitdepth = r.0.read_bit()?; + if s.seq_profile as u32 == 2 && cc.high_bitdepth { + cc.twelve_bit = r.0.read_bit()?; + if cc.twelve_bit { + s.bit_depth = BitDepth::Depth12; + } else { + s.bit_depth = BitDepth::Depth10; + } + } else if s.seq_profile as u32 <= 2 { + s.bit_depth = if cc.high_bitdepth { BitDepth::Depth10 } else { BitDepth::Depth8 }; + } + + if s.seq_profile as u32 == 1 { + cc.mono_chrome = false; + } else { + cc.mono_chrome = r.0.read_bit()?; + } + + if cc.mono_chrome { + s.num_planes = 1; + } else { + s.num_planes = 3; + } + + cc.color_description_present_flag = r.0.read_bit()?; + if cc.color_description_present_flag { + cc.color_primaries = ColorPrimaries::try_from(r.0.read_bits::(8)?)?; + cc.transfer_characteristics = + TransferCharacteristics::try_from(r.0.read_bits::(8)?)?; + cc.matrix_coefficients = MatrixCoefficients::try_from(r.0.read_bits::(8)?)?; + } else { + cc.color_primaries = ColorPrimaries::Unspecified; + cc.transfer_characteristics = TransferCharacteristics::Unspecified; + cc.matrix_coefficients = MatrixCoefficients::Unspecified; + } + + if cc.mono_chrome { + cc.color_range = r.0.read_bit()?; + cc.subsampling_x = true; + cc.subsampling_y = true; + cc.chroma_sample_position = ChromaSamplePosition::Unknown; + cc.separate_uv_delta_q = false; + return Ok(()); + } else if matches!(cc.color_primaries, ColorPrimaries::Bt709) + && matches!(cc.transfer_characteristics, TransferCharacteristics::Srgb) + && matches!(cc.matrix_coefficients, MatrixCoefficients::Identity) + { + cc.color_range = true; + cc.subsampling_x = false; + cc.subsampling_y = false; + } else { + cc.color_range = r.0.read_bit()?; + if s.seq_profile as u32 == 0 { + cc.subsampling_x = true; + cc.subsampling_y = true; + } else if s.seq_profile as u32 == 1 { + cc.subsampling_x = false; + cc.subsampling_y = false; + } else if matches!(s.bit_depth, BitDepth::Depth12) { + cc.subsampling_x = r.0.read_bit()?; + if cc.subsampling_x { + cc.subsampling_y = r.0.read_bit()?; + } else { + cc.subsampling_y = false; + } + } else { + cc.subsampling_x = true; + cc.subsampling_y = false; + } + + if cc.subsampling_x && cc.subsampling_y { + cc.chroma_sample_position = + ChromaSamplePosition::try_from(r.0.read_bits::(2)?)?; + } + } + + cc.separate_uv_delta_q = r.0.read_bit()?; + + Ok(()) + } + + fn parse_operating_parameters_info( + opi: &mut OperatingPoint, + r: &mut Reader, + buffer_delay_length_minus_1: u8, + ) -> Result<(), String> { + let n = buffer_delay_length_minus_1 + 1; + opi.decoder_buffer_delay = r.0.read_bits::(n as usize)?; + opi.encoder_buffer_delay = r.0.read_bits::(n as usize)?; + opi.low_delay_mode_flag = r.0.read_bit()?; + Ok(()) + } + + fn parse_decoder_model_info(dmi: &mut DecoderModelInfo, r: &mut Reader) -> Result<(), String> { + dmi.buffer_delay_length_minus_1 = r.0.read_bits::(5)? as u8; + dmi.num_units_in_decoding_tick = r.0.read_bits::(32)?; + dmi.buffer_removal_time_length_minus_1 = r.0.read_bits::(5)? as u8; + dmi.frame_presentation_time_length_minus_1 = r.0.read_bits::(5)?; + Ok(()) + } + + fn parse_timing_info(ti: &mut TimingInfo, r: &mut Reader) -> Result<(), String> { + ti.num_units_in_display_tick = r.0.read_bits::(32)?; + ti.time_scale = r.0.read_bits::(32)?; + ti.equal_picture_interval = r.0.read_bit()?; + if ti.equal_picture_interval { + ti.num_ticks_per_picture_minus_1 = r.read_uvlc()?; + } + Ok(()) + } + + /// Selects an operating point. Only call this after the Sequence OBU for + /// which the operating point should apply has been parsed. + pub fn choose_operating_point(&mut self, operating_point: u32) -> Result<(), String> { + if operating_point > self.sequence()?.operating_points_cnt_minus_1 { + return Err(format!( + "Invalid operating point {} (max {})", + operating_point, + self.sequence()?.operating_points_cnt_minus_1 + )); + } + self.operating_point = operating_point; + self.operating_point_idc = self.sequence()?.operating_points[operating_point as usize].idc; + Ok(()) + } + + fn parse_temporal_delimiter_obu(&mut self) -> Result<(), String> { + self.seen_frame_header = false; + Ok(()) + } + + fn parse_sequence_header_obu(&mut self, obu: &Obu) -> Result, String> { + let mut s = SequenceHeaderObu { obu_header: obu.header.clone(), ..Default::default() }; + + let mut r = Reader::new(obu.as_ref()); + let profile = r.0.read_bits::(3)?; + + s.seq_profile = Profile::try_from(profile)?; + s.still_picture = r.0.read_bit()?; + s.reduced_still_picture_header = r.0.read_bit()?; + + if s.reduced_still_picture_header { + /* Default::default() already ensures a lot of this, but lets go verbatim */ + s.timing_info_present_flag = false; + s.decoder_model_info_present_flag = false; + s.initial_display_delay_present_flag = false; + s.operating_points_cnt_minus_1 = 0; + s.operating_points[0].idc = 0; + s.operating_points[0].seq_level_idx = r.0.read_bits::(5)? as u8; + s.operating_points[0].seq_tier = 0; + s.operating_points[0].decoder_model_present_for_this_op = false; + s.operating_points[0].initial_display_delay_present_for_this_op = false; + } else { + s.timing_info_present_flag = r.0.read_bit()?; + if s.timing_info_present_flag { + Self::parse_timing_info(&mut s.timing_info, &mut r)?; + s.decoder_model_info_present_flag = r.0.read_bit()?; + if s.decoder_model_info_present_flag { + Self::parse_decoder_model_info(&mut s.decoder_model_info, &mut r)?; + } + } else { + s.decoder_model_info_present_flag = false; + } + + s.initial_display_delay_present_flag = r.0.read_bit()?; + s.operating_points_cnt_minus_1 = r.0.read_bits::(5)?; + if s.operating_points_cnt_minus_1 > MAX_NUM_OPERATING_POINTS as u32 { + return Err(format!( + "Invalid operating_points_cnt_minus_1 {}", + s.operating_points_cnt_minus_1 + )); + } + + for i in 0..=s.operating_points_cnt_minus_1 as usize { + s.operating_points[i].idc = r.0.read_bits::(12)? as u16; + s.operating_points[i].seq_level_idx = r.0.read_bits::(5)? as u8; + if s.operating_points[i].seq_level_idx > 7 { + s.operating_points[i].seq_tier = r.0.read_bit()? as u8; + } else { + s.operating_points[i].seq_tier = 0; + } + if s.decoder_model_info_present_flag { + s.operating_points[i].decoder_model_present_for_this_op = r.0.read_bit()?; + if s.operating_points[i].decoder_model_present_for_this_op { + let buffer_delay_length_minus_1 = + s.decoder_model_info.buffer_delay_length_minus_1; + Self::parse_operating_parameters_info( + &mut s.operating_points[i], + &mut r, + buffer_delay_length_minus_1, + )?; + } + } else { + s.operating_points[i].decoder_model_present_for_this_op = false; + } + + if s.initial_display_delay_present_flag { + s.operating_points[i].initial_display_delay_present_for_this_op = + r.0.read_bit()?; + if s.operating_points[i].initial_display_delay_present_for_this_op { + s.operating_points[i].initial_display_delay_minus_1 = + r.0.read_bits::(4)?; + } + } + } + } + + s.frame_width_bits_minus_1 = r.0.read_bits::(4)? as u8; + s.frame_height_bits_minus_1 = r.0.read_bits::(4)? as u8; + // frame_width_bits_minus_1 has been read from 4 bits, meaning we can read 16 bits at most. + s.max_frame_width_minus_1 = + r.0.read_bits::(s.frame_width_bits_minus_1 as usize + 1)? as u16; + // frame_height_bits_minus_1 has been read from 4 bits, meaning we can read 16 bits at most. + s.max_frame_height_minus_1 = + r.0.read_bits::(s.frame_height_bits_minus_1 as usize + 1)? as u16; + if s.reduced_still_picture_header { + s.frame_id_numbers_present_flag = false; + } else { + s.frame_id_numbers_present_flag = r.0.read_bit()?; + } + if s.frame_id_numbers_present_flag { + s.delta_frame_id_length_minus_2 = r.0.read_bits::(4)?; + s.additional_frame_id_length_minus_1 = r.0.read_bits::(3)?; + let frame_id_length = + s.additional_frame_id_length_minus_1 + s.delta_frame_id_length_minus_2 + 3; + if frame_id_length > 16 { + return Err(format!("Invalid frame_id_length {}", frame_id_length)); + } + } + + s.use_128x128_superblock = r.0.read_bit()?; + s.enable_filter_intra = r.0.read_bit()?; + s.enable_intra_edge_filter = r.0.read_bit()?; + if s.reduced_still_picture_header { + s.enable_interintra_compound = false; + s.enable_masked_compound = false; + s.enable_warped_motion = false; + s.enable_dual_filter = false; + s.enable_order_hint = false; + s.enable_jnt_comp = false; + s.enable_ref_frame_mvs = false; + s.seq_force_screen_content_tools = SELECT_SCREEN_CONTENT_TOOLS as _; + s.seq_force_integer_mv = SELECT_INTEGER_MV as _; + s.order_hint_bits = 0; + s.order_hint_bits_minus_1 = -1; + } else { + s.enable_interintra_compound = r.0.read_bit()?; + s.enable_masked_compound = r.0.read_bit()?; + s.enable_warped_motion = r.0.read_bit()?; + s.enable_dual_filter = r.0.read_bit()?; + s.enable_order_hint = r.0.read_bit()?; + if s.enable_order_hint { + s.enable_jnt_comp = r.0.read_bit()?; + s.enable_ref_frame_mvs = r.0.read_bit()?; + } else { + s.enable_jnt_comp = false; + s.enable_ref_frame_mvs = false; + } + s.seq_choose_screen_content_tools = r.0.read_bit()?; + if s.seq_choose_screen_content_tools { + s.seq_force_screen_content_tools = SELECT_SCREEN_CONTENT_TOOLS as _; + } else { + s.seq_force_screen_content_tools = r.0.read_bit()? as _; + } + if s.seq_force_screen_content_tools > 0 { + s.seq_choose_integer_mv = r.0.read_bit()?; + if s.seq_choose_integer_mv { + s.seq_force_integer_mv = SELECT_INTEGER_MV as _; + } else { + s.seq_force_integer_mv = r.0.read_bit()? as _; + } + } else { + s.seq_force_integer_mv = SELECT_INTEGER_MV as _; + } + + if s.enable_order_hint { + s.order_hint_bits_minus_1 = r.0.read_bits::(3)?.try_into().unwrap(); + s.order_hint_bits = s.order_hint_bits_minus_1 + 1; + } else { + s.order_hint_bits_minus_1 = -1; + s.order_hint_bits = 0; + } + } + + s.enable_superres = r.0.read_bit()?; + s.enable_cdef = r.0.read_bit()?; + s.enable_restoration = r.0.read_bit()?; + + Self::parse_color_config(&mut s, &mut r)?; + + s.film_grain_params_present = r.0.read_bit()?; + + Self::skip_and_check_trailing_bits(&mut r, obu)?; + let rc = Rc::new(s); + self.sequence_header = Some(rc.clone()); + + /* Client is supposed to set the operating point through external means, + * here we just set 0 as default. */ + self.choose_operating_point(0)?; + + Ok(rc) + } + + /// Implements 7.21. Note that 7.20 will use the information from the + /// header, so we must save them now, as they will not be parsed from the + /// bitstream. We also save some internal parser state which will be useful + /// later. + fn load_reference_frame(&self, fh: &mut FrameHeaderObu) -> Result<(), String> { + let rf = &self.ref_info[fh.frame_to_show_map_idx as usize]; + + // Section 6.8.1: It is a requirement of bitstream conformance that a + // sequence header OBU has been received before a frame header OBU. + let seq = self.sequence()?; + + /* at least save the sizes and for both kf and non-kf */ + fh.frame_type = rf.ref_frame_type; + fh.upscaled_width = rf.ref_upscaled_width; + fh.frame_width = rf.ref_frame_width; + fh.frame_height = rf.ref_frame_height; + fh.render_width = rf.ref_render_width; + fh.render_height = rf.ref_render_height; + + /* Save into the frame header */ + if fh.frame_type == FrameType::KeyFrame { + fh.current_frame_id = rf.ref_frame_id; + /* We don't keep track of sequence information at the frame level */ + fh.mi_cols = rf.ref_mi_cols; + fh.mi_rows = rf.ref_mi_rows; + /* The accelerator is keeping track of CDF values, so that is skipped too */ + fh.global_motion_params = rf.global_motion_params.clone(); + + if seq.film_grain_params_present { + fh.film_grain_params = rf.film_grain_params.clone(); + } + fh.loop_filter_params = rf.loop_filter_params.clone(); + fh.segmentation_params = rf.segmentation_params.clone(); + } + + Ok(()) + } + + fn setup_past_independence(fh: &mut FrameHeaderObu) { + fh.segmentation_params.feature_enabled = Default::default(); + fh.segmentation_params.feature_data = Default::default(); + + for i in ReferenceFrameType::Last as usize..ReferenceFrameType::AltRef as usize { + fh.global_motion_params.gm_type[i] = WarpModelType::Identity; + } + + fh.loop_filter_params.loop_filter_delta_enabled = true; + fh.loop_filter_params.loop_filter_ref_deltas = [1, 0, 0, 0, -1, 0, -1, -1]; + fh.loop_filter_params.loop_filter_mode_deltas = Default::default(); + } + + fn parse_tile_info(&mut self, r: &mut Reader, ti: &mut TileInfo) -> Result<(), String> { + let seq = self.sequence()?; + + let sb_cols = if seq.use_128x128_superblock { + (self.mi_cols + 31) >> 5 + } else { + (self.mi_cols + 15) >> 4 + }; + + let sb_rows = if seq.use_128x128_superblock { + (self.mi_rows + 31) >> 5 + } else { + (self.mi_rows + 15) >> 4 + }; + + let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 }; + let sb_size = sb_shift + 2; + + let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size; + let mut max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size); + + let min_log2_tile_cols = helpers::tile_log2(max_tile_width_sb, sb_cols); + + let max_log2_tile_cols = + helpers::tile_log2(1, std::cmp::min(sb_cols, MAX_TILE_COLS as u32)); + + let max_log2_tile_rows = + helpers::tile_log2(1, std::cmp::min(sb_rows, MAX_TILE_ROWS as u32)); + + let min_log2_tiles = std::cmp::max( + min_log2_tile_cols, + helpers::tile_log2(max_tile_area_sb, sb_rows * sb_cols), + ); + + ti.uniform_tile_spacing_flag = r.0.read_bit()?; + + if ti.uniform_tile_spacing_flag { + self.tile_cols_log2 = min_log2_tile_cols; + while self.tile_cols_log2 < max_log2_tile_cols { + let increment_tile_cols_log_2 = r.0.read_bit()?; + if increment_tile_cols_log_2 { + self.tile_cols_log2 += 1; + } else { + break; + } + } + + let tile_width_sb = (sb_cols + (1 << self.tile_cols_log2) - 1) >> self.tile_cols_log2; + + let mut i = 0; + let mut start_sb = 0; + + while start_sb < sb_cols { + self.mi_col_starts[i] = start_sb << sb_shift; + i += 1; + start_sb += tile_width_sb; + } + + self.mi_col_starts[i] = self.mi_cols; + self.tile_cols = i as _; + + if self.tile_cols > MAX_TILE_COLS as u32 { + return Err(format!("Invalid tile_cols {}", self.tile_cols)); + } + + /* compute this anyways */ + while i >= 1 { + ti.width_in_sbs_minus_1[i - 1] = + ((self.mi_col_starts[i] - self.mi_col_starts[i - 1] + ((1 << sb_shift) - 1)) + >> sb_shift) + - 1; + i -= 1; + } + + let min_log2_tile_rows = + std::cmp::max(min_log2_tiles.saturating_sub(self.tile_cols_log2), 0); + self.tile_rows_log2 = min_log2_tile_rows; + + while self.tile_rows_log2 < max_log2_tile_rows { + let increment_tile_rows_log_2 = r.0.read_bit()?; + + if increment_tile_rows_log_2 { + self.tile_rows_log2 += 1; + } else { + break; + } + } + + let tile_height_sb = (sb_rows + (1 << self.tile_rows_log2) - 1) >> self.tile_rows_log2; + + let mut i = 0; + let mut start_sb = 0; + + while start_sb < sb_rows { + self.mi_row_starts[i] = start_sb << sb_shift; + i += 1; + start_sb += tile_height_sb; + } + + self.mi_row_starts[i] = self.mi_rows; + self.tile_rows = i as _; + + if self.tile_rows > MAX_TILE_ROWS as u32 { + return Err(format!("Invalid tile_rows {}", self.tile_cols)); + } + + /* compute this anyways */ + while i >= 1 { + ti.height_in_sbs_minus_1[i - 1] = + ((self.mi_row_starts[i] - self.mi_row_starts[i - 1] + ((1 << sb_shift) - 1)) + >> sb_shift) + - 1; + i -= 1; + } + } else { + let mut widest_tile_sb = 0; + let mut start_sb = 0; + let mut i = 0; + + while start_sb < sb_cols { + self.mi_col_starts[i] = start_sb << sb_shift; + + let max_width = std::cmp::min(sb_cols - start_sb, max_tile_width_sb); + ti.width_in_sbs_minus_1[i] = r.read_ns(max_width.try_into().unwrap())?; + + let size_sb = ti.width_in_sbs_minus_1[i] + 1; + widest_tile_sb = std::cmp::max(size_sb, widest_tile_sb); + + start_sb += size_sb; + i += 1; + } + + self.mi_col_starts[i] = self.mi_cols; + self.tile_cols = i as _; + self.tile_cols_log2 = helpers::tile_log2(1, self.tile_cols); + + if min_log2_tiles > 0 { + max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1); + } else { + max_tile_area_sb = sb_rows * sb_cols; + } + + let max_tile_height_sb = std::cmp::max(max_tile_area_sb / widest_tile_sb, 1); + let mut start_sb = 0; + let mut i = 0; + while start_sb < sb_rows { + self.mi_row_starts[i] = start_sb << sb_shift; + let max_height = std::cmp::min(sb_rows - start_sb, max_tile_height_sb); + ti.height_in_sbs_minus_1[i] = r.read_ns(max_height.try_into().unwrap())?; + + let size_sb = ti.height_in_sbs_minus_1[i] + 1; + start_sb += size_sb; + i += 1; + } + + self.mi_row_starts[i] = self.mi_rows; + self.tile_rows = i as _; + self.tile_rows_log2 = helpers::tile_log2(1, self.tile_rows); + } + + if self.tile_cols_log2 > 0 || self.tile_rows_log2 > 0 { + let num_bits: usize = (self.tile_rows_log2 + self.tile_cols_log2).try_into().unwrap(); + ti.context_update_tile_id = r.0.read_bits::(num_bits)?; + + if ti.context_update_tile_id >= self.tile_rows * self.tile_cols { + return Err(format!( + "Invalid context_update_tile_id {}", + ti.context_update_tile_id + )); + } + self.tile_size_bytes = r.0.read_bits::(2)? + 1; + } else { + ti.context_update_tile_id = 0; + } + + ti.mi_col_starts = self.mi_col_starts; + ti.mi_row_starts = self.mi_row_starts; + ti.tile_cols_log2 = self.tile_cols_log2; + ti.tile_cols = self.tile_cols; + ti.tile_rows_log2 = self.tile_rows_log2; + ti.tile_rows = self.tile_rows; + ti.tile_size_bytes = self.tile_size_bytes; + + Ok(()) + } + + fn parse_quantization_params( + r: &mut Reader, + q: &mut QuantizationParams, + num_planes: u32, + separate_uv_delta_q: bool, + ) -> Result<(), String> { + q.base_q_idx = r.0.read_bits::(8)?; + q.delta_q_y_dc = r.read_delta_q()?; + if num_planes > 1 { + if separate_uv_delta_q { + q.diff_uv_delta = r.0.read_bit()?; + } else { + q.diff_uv_delta = false; + } + + q.delta_q_u_dc = r.read_delta_q()?; + q.delta_q_u_ac = r.read_delta_q()?; + if q.diff_uv_delta { + q.delta_q_v_dc = r.read_delta_q()?; + q.delta_q_v_ac = r.read_delta_q()?; + } else { + q.delta_q_v_dc = q.delta_q_u_dc; + q.delta_q_v_ac = q.delta_q_u_ac; + } + } else { + q.delta_q_u_dc = 0; + q.delta_q_u_ac = 0; + q.delta_q_v_dc = 0; + q.delta_q_v_ac = 0; + } + + q.using_qmatrix = r.0.read_bit()?; + if q.using_qmatrix { + q.qm_y = r.0.read_bits::(4)?; + q.qm_u = r.0.read_bits::(4)?; + if !separate_uv_delta_q { + q.qm_v = q.qm_u; + } else { + q.qm_v = r.0.read_bits::(4)?; + } + } + Ok(()) + } + + fn parse_delta_q_params(r: &mut Reader, q: &mut QuantizationParams) -> Result<(), String> { + q.delta_q_res = 0; + q.delta_q_present = false; + if q.base_q_idx > 0 { + q.delta_q_present = r.0.read_bit()?; + } + if q.delta_q_present { + q.delta_q_res = r.0.read_bits::(2)?; + } + + Ok(()) + } + + fn parse_delta_lf_params( + r: &mut Reader, + lf: &mut LoopFilterParams, + delta_q_present: bool, + allow_intrabc: bool, + ) -> Result<(), String> { + lf.delta_lf_present = false; + lf.delta_lf_res = 0; + lf.delta_lf_multi = false; + if delta_q_present { + if !allow_intrabc { + lf.delta_lf_present = r.0.read_bit()?; + } + if lf.delta_lf_present { + lf.delta_lf_res = r.0.read_bits::(2)? as u8; + lf.delta_lf_multi = r.0.read_bit()?; + } + } + Ok(()) + } + + fn parse_segmentation_params( + &self, + r: &mut Reader, + fh: &mut FrameHeaderObu, + ) -> Result<(), String> { + let s = &mut fh.segmentation_params; + s.segmentation_enabled = r.0.read_bit()?; + if s.segmentation_enabled { + if fh.primary_ref_frame == PRIMARY_REF_NONE { + s.segmentation_update_map = true; + s.segmentation_temporal_update = false; + s.segmentation_update_data = true; + } else { + s.segmentation_update_map = r.0.read_bit()?; + if s.segmentation_update_map { + s.segmentation_temporal_update = r.0.read_bit()?; + } + s.segmentation_update_data = r.0.read_bit()?; + } + if s.segmentation_update_data { + for i in 0..MAX_SEGMENTS { + for j in 0..SEG_LVL_MAX { + let feature_enabled = r.0.read_bit()?; + s.feature_enabled[i][j] = feature_enabled; + if feature_enabled { + let bits_to_read = FEATURE_BITS[j]; + let limit = FEATURE_MAX[j]; + let signed = FEATURE_SIGNED[j]; + + if signed { + let feature_value = r.read_su(1 + bits_to_read as usize)?; + let clipped_value = helpers::clip3(-limit, limit, feature_value); + s.feature_data[i][j] = clipped_value as _; + } else { + let feature_value = r.0.read_bits::(bits_to_read as usize)?; + let clipped_value = helpers::clip3( + 0, + limit, + feature_value + .try_into() + .map_err(|_| "Invalid feature_value")?, + ); + s.feature_data[i][j] = clipped_value as _; + } + } + } + } + } else { + /* copy from prev_frame */ + let prev_frame = + &self.ref_info[fh.ref_frame_idx[fh.primary_ref_frame as usize] as usize]; + + if !prev_frame.ref_valid { + return Err("Reference is invalid".into()); + } + + s.feature_enabled = prev_frame.segmentation_params.feature_enabled; + s.feature_data = prev_frame.segmentation_params.feature_data; + } + } else { + for i in 0..MAX_SEGMENTS { + for j in 0..SEG_LVL_MAX { + s.feature_enabled[i][j] = false; + s.feature_data[i][j] = 0; + } + } + } + + s.seg_id_pre_skip = false; + s.last_active_seg_id = 0; + for i in 0..MAX_SEGMENTS { + for j in 0..SEG_LVL_MAX { + if s.feature_enabled[i][j] { + s.last_active_seg_id = i as u8; + if j >= SEG_LVL_REF_FRAME { + s.seg_id_pre_skip = true; + } + } + } + } + + Ok(()) + } + + fn parse_loop_filter_parameters( + r: &mut Reader, + fh: &mut FrameHeaderObu, + num_planes: u32, + ) -> Result<(), String> { + let lf = &mut fh.loop_filter_params; + if fh.coded_lossless || fh.allow_intrabc { + lf.loop_filter_level[0] = 0; + lf.loop_filter_level[1] = 0; + lf.loop_filter_ref_deltas = [1, 0, 0, 0, -1, 0, -1, -1]; + + lf.loop_filter_mode_deltas = Default::default(); + + return Ok(()); + } + + lf.loop_filter_level[0] = r.0.read_bits::(6)? as u8; + lf.loop_filter_level[1] = r.0.read_bits::(6)? as u8; + if num_planes > 1 && (lf.loop_filter_level[0] > 0 || lf.loop_filter_level[1] > 0) { + lf.loop_filter_level[2] = r.0.read_bits::(6)? as u8; + lf.loop_filter_level[3] = r.0.read_bits::(6)? as u8; + } + + lf.loop_filter_sharpness = r.0.read_bits::(3)? as u8; + lf.loop_filter_delta_enabled = r.0.read_bit()?; + if lf.loop_filter_delta_enabled { + lf.loop_filter_delta_update = r.0.read_bit()?; + if lf.loop_filter_delta_update { + for i in 0..TOTAL_REFS_PER_FRAME { + let update_ref_delta = r.0.read_bit()?; + if update_ref_delta { + lf.loop_filter_ref_deltas[i] = r.read_su(7)? as i8; + } + } + + for i in 0..2 { + let update_mode_delta = r.0.read_bit()?; + if update_mode_delta { + lf.loop_filter_mode_deltas[i] = r.read_su(7)? as i8; + } + } + } + } + + Ok(()) + } + + fn parse_cdef_params( + r: &mut Reader, + fh: &mut FrameHeaderObu, + enable_cdef: bool, + num_planes: u32, + ) -> Result<(), String> { + let cdef = &mut fh.cdef_params; + + if fh.coded_lossless || fh.allow_intrabc || !enable_cdef { + cdef.cdef_bits = 0; + cdef.cdef_y_pri_strength[0] = 0; + cdef.cdef_y_sec_strength[0] = 0; + cdef.cdef_uv_pri_strength[0] = 0; + cdef.cdef_uv_sec_strength[0] = 0; + cdef.cdef_damping = 3; + return Ok(()); + } + + cdef.cdef_damping = r.0.read_bits::(2)? + 3; + cdef.cdef_bits = r.0.read_bits::(2)?; + for i in 0..(1 << cdef.cdef_bits) as usize { + cdef.cdef_y_pri_strength[i] = r.0.read_bits::(4)?; + cdef.cdef_y_sec_strength[i] = r.0.read_bits::(2)?; + if cdef.cdef_y_sec_strength[i] == 3 { + cdef.cdef_y_sec_strength[i] += 1; + } + if num_planes > 1 { + cdef.cdef_uv_pri_strength[i] = r.0.read_bits::(4)?; + cdef.cdef_uv_sec_strength[i] = r.0.read_bits::(2)?; + if cdef.cdef_uv_sec_strength[i] == 3 { + cdef.cdef_uv_sec_strength[i] += 1; + } + } + } + + Ok(()) + } + + fn parse_loop_restoration_params( + r: &mut Reader, + fh: &mut FrameHeaderObu, + enable_restoration: bool, + num_planes: u32, + use_128x128_superblock: bool, + subsampling_x: bool, + subsampling_y: bool, + ) -> Result<(), String> { + let lr = &mut fh.loop_restoration_params; + + if fh.all_lossless || fh.allow_intrabc || !enable_restoration { + lr.frame_restoration_type[0] = FrameRestorationType::None; + lr.frame_restoration_type[1] = FrameRestorationType::None; + lr.frame_restoration_type[2] = FrameRestorationType::None; + lr.uses_lr = false; + return Ok(()); + } + + lr.uses_lr = false; + lr.uses_chroma_lr = false; + + const REMAP_LR_TYPE: [FrameRestorationType; 4] = [ + FrameRestorationType::None, + FrameRestorationType::Switchable, + FrameRestorationType::Wiener, + FrameRestorationType::Sgrproj, + ]; + + for i in 0..num_planes as usize { + let lr_type = r.0.read_bits::(2)?; + lr.frame_restoration_type[i] = REMAP_LR_TYPE[lr_type as usize]; + if lr.frame_restoration_type[i] != FrameRestorationType::None { + lr.uses_lr = true; + if i > 0 { + lr.uses_chroma_lr = true; + } + } + } + + if lr.uses_lr { + if use_128x128_superblock { + lr.lr_unit_shift = r.0.read_bits::(1)? as u8 + 1; + } else { + lr.lr_unit_shift = r.0.read_bits::(1)? as u8; + if lr.lr_unit_shift > 0 { + lr.lr_unit_shift += r.0.read_bits::(1)? as u8; + } + } + + lr.loop_restoration_size[0] = RESTORATION_TILESIZE_MAX >> (2 - lr.lr_unit_shift); + if subsampling_x && subsampling_y && lr.uses_chroma_lr { + lr.lr_uv_shift = r.0.read_bits::(1)? as u8; + } else { + lr.lr_uv_shift = 0; + } + + lr.loop_restoration_size[1] = lr.loop_restoration_size[0] >> lr.lr_uv_shift; + lr.loop_restoration_size[2] = lr.loop_restoration_size[0] >> lr.lr_uv_shift; + } + + Ok(()) + } + + fn read_tx_mode(r: &mut Reader, fh: &mut FrameHeaderObu) -> Result<(), String> { + if fh.coded_lossless { + fh.tx_mode = TxMode::Only4x4; + } else { + let tx_mode_select = r.0.read_bit()?; + + if tx_mode_select { + fh.tx_mode = TxMode::Select; + } else { + fh.tx_mode = TxMode::Largest; + } + } + + Ok(()) + } + + fn parse_skip_mode_params( + &self, + r: &mut Reader, + fh: &mut FrameHeaderObu, + enable_order_hint: bool, + order_hint_bits: i32, + ) -> Result<(), String> { + let skip_mode_allowed; + + if fh.frame_is_intra || !fh.reference_select || !enable_order_hint { + skip_mode_allowed = false; + } else { + let mut forward_idx = -1; + let mut backward_idx = -1; + let mut forward_hint = 0; + let mut backward_hint = 0; + for i in 0..REFS_PER_FRAME { + let ref_hint = self.ref_info[fh.ref_frame_idx[i] as usize].ref_order_hint; + if helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + fh.order_hint.try_into().unwrap(), + ) < 0 + && (forward_idx < 0 + || helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + forward_hint, + ) > 0) + { + forward_idx = i32::try_from(i).unwrap(); + forward_hint = ref_hint.try_into().unwrap(); + } else if helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + fh.order_hint.try_into().unwrap(), + ) > 0 + && (backward_idx < 0 || { + helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + backward_hint, + ) < 0 + }) + { + backward_idx = i32::try_from(i).unwrap(); + backward_hint = ref_hint.try_into().unwrap(); + } + } + + if forward_idx < 0 { + skip_mode_allowed = false; + } else if backward_idx >= 0 { + skip_mode_allowed = true; + fh.skip_mode_frame[0] = ReferenceFrameType::Last as u32 + + u32::try_from(std::cmp::min(forward_idx, backward_idx)).unwrap(); + fh.skip_mode_frame[1] = ReferenceFrameType::Last as u32 + + u32::try_from(std::cmp::max(forward_idx, backward_idx)).unwrap(); + } else { + let mut second_forward_idx = -1; + let mut second_forward_hint = 0; + for i in 0..REFS_PER_FRAME { + let ref_hint = self.ref_info[fh.ref_frame_idx[i] as usize].ref_order_hint; + if helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + forward_hint, + ) < 0 + && (second_forward_idx < 0 + || helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + ref_hint.try_into().unwrap(), + second_forward_hint, + ) > 0) + { + second_forward_idx = i32::try_from(i).unwrap(); + second_forward_hint = ref_hint.try_into().unwrap(); + } + } + + if second_forward_idx < 0 { + skip_mode_allowed = false; + } else { + skip_mode_allowed = true; + fh.skip_mode_frame[0] = ReferenceFrameType::Last as u32 + + u32::try_from(std::cmp::min(forward_idx, second_forward_idx)).unwrap(); + fh.skip_mode_frame[1] = ReferenceFrameType::Last as u32 + + u32::try_from(std::cmp::max(forward_idx, second_forward_idx)).unwrap(); + } + } + } + + if skip_mode_allowed { + fh.skip_mode_present = r.0.read_bit()?; + } else { + fh.skip_mode_present = false; + } + + Ok(()) + } + + fn parse_frame_reference_mode(r: &mut Reader, fh: &mut FrameHeaderObu) -> Result<(), String> { + if fh.frame_is_intra { + fh.reference_select = false; + } else { + fh.reference_select = r.0.read_bit()?; + } + Ok(()) + } + + fn seg_feature_active_idx(seg: &SegmentationParams, idx: u32, feature: u32) -> bool { + seg.segmentation_enabled && seg.feature_enabled[idx as usize][feature as usize] + } + + fn get_qindex(fh: &FrameHeaderObu, ignore_deltaq: bool, segment_id: u32) -> i32 { + let base_q_idx = i32::try_from(fh.quantization_params.base_q_idx).unwrap(); + if Self::seg_feature_active_idx(&fh.segmentation_params, segment_id, SEG_LVL_ALT_Q as u32) { + let data = fh.segmentation_params.feature_data[segment_id as usize][SEG_LVL_ALT_Q]; + let mut qindex = base_q_idx + i32::from(data); + if !ignore_deltaq && fh.quantization_params.delta_q_present { + qindex += i32::try_from(fh.quantization_params.delta_q_res).unwrap(); + } + helpers::clip3(0, 255, qindex) + } else { + base_q_idx + } + } + + fn setup_shear(warp_params: &[i32; 6]) -> Result { + let mut default = true; + for (i, param) in warp_params.iter().enumerate() { + let default_value = if i % 3 == 2 { 1 << WARPEDMODEL_PREC_BITS } else { 0 }; + if *param != default_value { + default = false; + break; + } + } + + /* assume the default params to be valid */ + if default { + return Ok(true); + } + + let alpha0 = helpers::clip3(-32768, 32767, warp_params[2] - (1 << WARPEDMODEL_PREC_BITS)); + let beta0 = helpers::clip3(-32768, 32767, warp_params[3]); + + let (div_shift, div_factor) = helpers::resolve_divisor(warp_params[2])?; + + let v = i64::from(warp_params[4] << WARPEDMODEL_PREC_BITS); + let v = (v * i64::from(div_factor)) as i32; + let gamma0 = helpers::clip3(-32678, 32767, helpers::round2signed(v, div_shift)?); + + let w = warp_params[3] * warp_params[4]; + + let delta0 = helpers::clip3( + -32768, + 32767, + warp_params[5] + - helpers::round2signed(w * div_factor, div_shift)? + - (1 << WARPEDMODEL_PREC_BITS), + ); + + let alpha = + helpers::round2signed(alpha0, WARP_PARAM_REDUCE_BITS)? << WARP_PARAM_REDUCE_BITS; + let beta = helpers::round2signed(beta0, WARP_PARAM_REDUCE_BITS)? << WARP_PARAM_REDUCE_BITS; + let gamma = + helpers::round2signed(gamma0, WARP_PARAM_REDUCE_BITS)? << WARP_PARAM_REDUCE_BITS; + let delta = + helpers::round2signed(delta0, WARP_PARAM_REDUCE_BITS)? << WARP_PARAM_REDUCE_BITS; + + #[allow(clippy::needless_bool)] + let warp_valid = if 4 * alpha.abs() + 7 * beta.abs() >= (1 << WARPEDMODEL_PREC_BITS) + || 4 * gamma.abs() + 4 * delta.abs() >= (1 << WARPEDMODEL_PREC_BITS) + { + false + } else { + true + }; + + Ok(warp_valid) + } + + fn read_global_param( + reader: &mut Reader, + type_: WarpModelType, + ref_frame: usize, + idx: usize, + allow_high_precision_mv: bool, + prev_gm_params: &[[i32; 6]; NUM_REF_FRAMES], + gm_params: &mut [[i32; 6]; NUM_REF_FRAMES], + ) -> Result<(), String> { + let mut abs_bits = GM_ABS_ALPHA_BITS; + let mut prec_bits = GM_ALPHA_PREC_BITS; + if idx < 2 { + if type_ == WarpModelType::Translation { + abs_bits = GM_ABS_TRANS_ONLY_BITS - !allow_high_precision_mv as u32; + prec_bits = GM_TRANS_ONLY_PREC_BITS - !allow_high_precision_mv as u32; + } else { + abs_bits = GM_ABS_TRANS_BITS; + prec_bits = GM_TRANS_PREC_BITS; + } + } + + let prec_diff = WARPEDMODEL_PREC_BITS - prec_bits; + + let (round, sub) = + if (idx % 3) == 2 { (1 << WARPEDMODEL_PREC_BITS, 1 << prec_bits) } else { (0, 0) }; + + let mx = 1 << abs_bits; + let r = (prev_gm_params[ref_frame][idx] >> prec_diff) - sub; + gm_params[ref_frame][idx] = + (reader.decode_signed_subexp_with_ref(-mx, mx + 1, r)? << prec_diff) + round; + + Ok(()) + } + + fn parse_global_motion_params( + &mut self, + r: &mut Reader, + fh: &mut FrameHeaderObu, + ) -> Result<(), String> { + let gm = &mut fh.global_motion_params; + let mut type_; + let mut prev_gm_params: [[i32; 6]; NUM_REF_FRAMES] = Default::default(); + + for ref_frame in ReferenceFrameType::Last as usize..=ReferenceFrameType::AltRef as usize { + gm.gm_type[ref_frame] = WarpModelType::Identity; + for i in 0..6 { + gm.gm_params[ref_frame][i] = if i % 3 == 2 { 1 << WARPEDMODEL_PREC_BITS } else { 0 } + } + gm.warp_valid[ref_frame] = true; + } + + if fh.frame_is_intra { + return Ok(()); + } + + // Following libgav1: implement part of setup_past_independence() and + // load_previous(), i.e.: the parts that refer to the global motion + // parameters. + if fh.primary_ref_frame == PRIMARY_REF_NONE { + // setup_past_independence() + #[allow(clippy::needless_range_loop)] + for ref_frame in ReferenceFrameType::Last as usize..ReferenceFrameType::AltRef as usize + { + for i in 0..5 { + prev_gm_params[ref_frame][i] = + if i % 3 == 2 { 1 << WARPEDMODEL_PREC_BITS } else { 0 } + } + } + } else { + // load_previous(): + // 1. The variable prevFrame is set equal to ref_frame_idx[ primary_ref_frame ]. + // 2. PrevGmParams is set equal to SavedGmParams[ prevFrame ]. + let prev_frame = fh.ref_frame_idx[fh.primary_ref_frame as usize]; + prev_gm_params = self.ref_info[prev_frame as usize].global_motion_params.gm_params; + } + + for ref_frame in ReferenceFrameType::Last as usize..=ReferenceFrameType::AltRef as usize { + gm.is_global[ref_frame] = r.0.read_bit()?; + if gm.is_global[ref_frame] { + gm.is_rot_zoom[ref_frame] = r.0.read_bit()?; + if gm.is_rot_zoom[ref_frame] { + type_ = WarpModelType::RotZoom; + } else { + gm.is_translation[ref_frame] = r.0.read_bit()?; + if gm.is_translation[ref_frame] { + type_ = WarpModelType::Translation; + } else { + type_ = WarpModelType::Affine; + } + } + } else { + type_ = WarpModelType::Identity; + } + + gm.gm_type[ref_frame] = type_; + if gm.gm_type[ref_frame] as u32 >= WarpModelType::RotZoom as u32 { + Self::read_global_param( + r, + type_, + ref_frame, + 2, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + + Self::read_global_param( + r, + type_, + ref_frame, + 3, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + + if type_ == WarpModelType::Affine { + Self::read_global_param( + r, + type_, + ref_frame, + 4, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + + Self::read_global_param( + r, + type_, + ref_frame, + 5, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + } else { + gm.gm_params[ref_frame][4] = -gm.gm_params[ref_frame][3]; + gm.gm_params[ref_frame][5] = gm.gm_params[ref_frame][2]; + } + } + + if gm.gm_type[ref_frame] as u32 >= WarpModelType::Translation as u32 { + Self::read_global_param( + r, + type_, + ref_frame, + 0, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + + Self::read_global_param( + r, + type_, + ref_frame, + 1, + fh.allow_high_precision_mv, + &prev_gm_params, + &mut gm.gm_params, + )?; + } + + gm.warp_valid[ref_frame] = Self::setup_shear(&gm.gm_params[ref_frame])?; + } + + Ok(()) + } + + fn parse_film_grain_parameters( + &self, + r: &mut Reader, + fh: &mut FrameHeaderObu, + film_grain_params_present: bool, + mono_chrome: bool, + subsampling_x: bool, + subsampling_y: bool, + ) -> Result<(), String> { + let fg = &mut fh.film_grain_params; + + if !film_grain_params_present || (!fh.show_frame && !fh.showable_frame) { + *fg = Default::default(); + return Ok(()); + } + + fg.apply_grain = r.0.read_bit()?; + if !fg.apply_grain { + *fg = Default::default(); + return Ok(()); + } + + fg.grain_seed = r.0.read_bits::(16)? as u16; + if fh.frame_type == FrameType::InterFrame { + fg.update_grain = r.0.read_bit()?; + } else { + fg.update_grain = true; + } + + if !fg.update_grain { + fg.film_grain_params_ref_idx = r.0.read_bits::(3)? as u8; + let temp_grain_seed = fg.grain_seed; + + if !fh + .ref_frame_idx + .iter() + .any(|&ref_frame_idx| ref_frame_idx == fg.film_grain_params_ref_idx) + { + return Err("Invalid film_grain_params_ref_idx".into()); + } + + // load_grain_params() + *fg = self.ref_info[fg.film_grain_params_ref_idx as usize].film_grain_params.clone(); + + fg.grain_seed = temp_grain_seed; + + return Ok(()); + } + + fg.num_y_points = r.0.read_bits::(4)? as u8; + fg.point_y_value + .iter_mut() + .zip(fg.point_y_scaling.iter_mut()) + .take(fg.num_y_points as usize) + .try_for_each(|(point_y_value, point_y_scaling)| { + *point_y_value = r.0.read_bits::(8)? as u8; + *point_y_scaling = r.0.read_bits::(8)? as u8; + Ok::<_, String>(()) + })?; + + if mono_chrome { + fg.chroma_scaling_from_luma = false; + } else { + fg.chroma_scaling_from_luma = r.0.read_bit()?; + } + + if mono_chrome + || fg.chroma_scaling_from_luma + || (subsampling_x && subsampling_y && fg.num_y_points == 0) + { + fg.num_cb_points = 0; + fg.num_cr_points = 0; + } else { + fg.num_cb_points = r.0.read_bits::(4)? as u8; + if fg.num_cb_points > 10 { + return Err(format!("Invalid num_cb_points {}", fg.num_cb_points)); + } + + for i in 0..fg.num_cb_points as usize { + fg.point_cb_value[i] = r.0.read_bits::(8)? as u8; + if i > 0 && fg.point_cb_value[i - 1] >= fg.point_cb_value[i] { + return Err(format!("Invalid point_cb_value[{}] {}", i, fg.point_cb_value[i])); + } + fg.point_cb_scaling[i] = r.0.read_bits::(8)? as u8; + } + + fg.num_cr_points = r.0.read_bits::(4)? as u8; + for i in 0..fg.num_cr_points as usize { + fg.point_cr_value[i] = r.0.read_bits::(8)? as u8; + if i > 0 && fg.point_cr_value[i - 1] >= fg.point_cr_value[i] { + return Err(format!("Invalid point_cr_value[{}] {}", i, fg.point_cr_value[i])); + } + fg.point_cr_scaling[i] = r.0.read_bits::(8)? as u8; + } + } + + fg.grain_scaling_minus_8 = r.0.read_bits::(2)? as u8; + fg.ar_coeff_lag = r.0.read_bits::(2)?; + + let num_pos_luma = 2 * fg.ar_coeff_lag * (fg.ar_coeff_lag + 1); + let num_pos_chroma = if fg.num_y_points > 0 { + for i in 0..num_pos_luma as usize { + fg.ar_coeffs_y_plus_128[i] = r.0.read_bits::(8)? as u8; + } + num_pos_luma + 1 + } else { + num_pos_luma + }; + + if fg.chroma_scaling_from_luma || fg.num_cb_points > 0 { + for i in 0..num_pos_chroma as usize { + fg.ar_coeffs_cb_plus_128[i] = r.0.read_bits::(8)? as u8; + } + } + + if fg.chroma_scaling_from_luma || fg.num_cr_points > 0 { + for i in 0..num_pos_chroma as usize { + fg.ar_coeffs_cr_plus_128[i] = r.0.read_bits::(8)? as u8; + } + } + + fg.ar_coeff_shift_minus_6 = r.0.read_bits::(2)? as u8; + fg.grain_scale_shift = r.0.read_bits::(2)? as u8; + + if fg.num_cb_points > 0 { + fg.cb_mult = r.0.read_bits::(8)? as u8; + fg.cb_luma_mult = r.0.read_bits::(8)? as u8; + fg.cb_offset = r.0.read_bits::(9)? as u16; + } + + if fg.num_cr_points > 0 { + fg.cr_mult = r.0.read_bits::(8)? as u8; + fg.cr_luma_mult = r.0.read_bits::(8)? as u8; + fg.cr_offset = r.0.read_bits::(9)? as u16; + } + + fg.overlap_flag = r.0.read_bit()?; + fg.clip_to_restricted_range = r.0.read_bit()?; + + Ok(()) + } + + fn sequence(&self) -> Result<&SequenceHeaderObu, String> { + let Some(seq) = self.sequence_header.as_ref() else { + return Err("No sequence header parsed yet".into()); + }; + + Ok(seq) + } + + fn parse_uncompressed_frame_header(&mut self, obu: &Obu) -> Result { + let mut r = Reader::new(obu.as_ref()); + + let mut fh = FrameHeaderObu { obu_header: obu.header.clone(), ..Default::default() }; + + // Section 6.8.1: It is a requirement of bitstream conformance that a + // sequence header OBU has been received before a frame header OBU. + let &SequenceHeaderObu { + operating_points_cnt_minus_1, + seq_force_integer_mv, + additional_frame_id_length_minus_1, + delta_frame_id_length_minus_2, + decoder_model_info_present_flag, + reduced_still_picture_header, + frame_id_numbers_present_flag, + use_128x128_superblock, + enable_order_hint, + seq_force_screen_content_tools, + order_hint_bits, + enable_cdef, + enable_restoration, + enable_warped_motion, + color_config: + ColorConfig { subsampling_x, subsampling_y, separate_uv_delta_q, mono_chrome, .. }, + timing_info: TimingInfo { equal_picture_interval, .. }, + decoder_model_info: + DecoderModelInfo { + frame_presentation_time_length_minus_1, + buffer_removal_time_length_minus_1, + .. + }, + num_planes, + film_grain_params_present, + .. + } = self.sequence()?; + + let mut id_len = 0; + + if frame_id_numbers_present_flag { + id_len = additional_frame_id_length_minus_1 + delta_frame_id_length_minus_2 + 3; + } + + const ALL_FRAMES: u32 = (1 << NUM_REF_FRAMES) - 1; + + if reduced_still_picture_header { + fh.show_existing_frame = false; + fh.frame_type = FrameType::KeyFrame; + fh.frame_is_intra = true; + fh.show_frame = true; + fh.showable_frame = false; + } else { + fh.show_existing_frame = r.0.read_bit()?; + if matches!(obu.header.obu_type, ObuType::Frame) && fh.show_existing_frame { + return Err("If obu_type is equal to OBU_FRAME, it is a requirement of bitstream conformance that show_existing_frame is equal to 0.".into()); + } + if fh.show_existing_frame { + fh.frame_to_show_map_idx = r.0.read_bits::(3)? as u8; + + if decoder_model_info_present_flag && !equal_picture_interval { + fh.frame_presentation_time = + r.0.read_bits::(frame_presentation_time_length_minus_1 as usize + 1)?; + } + + let ref_frame = &self.ref_info[fh.frame_to_show_map_idx as usize]; + + fh.refresh_frame_flags = 0; + if frame_id_numbers_present_flag { + if id_len == 0 { + return Err(format!("Invalid id_len {}", id_len)); + } + fh.display_frame_id = r.0.read_bits::(id_len.try_into().unwrap())?; + if ref_frame.display_frame_id != fh.display_frame_id || !ref_frame.ref_valid { + return Err("Invalid display_frame_id".into()); + } + } + + if !ref_frame.showable_frame { + return Err("Invalid bitstream: can't show this past frame".into()); + } + + // In decode_frame_wrapup(): + // + // Otherwise (show_existing_frame is equal to 1), if frame_type + // is equal to KEY_FRAME, the reference frame loading process as + // specified in section 7.21 is invoked (this process loads + // frame state from the reference frames into the current frame + // state variables) + // + // The following ordered steps now apply: + // + // 1. The reference frame update process as specified in section + // 7.20 is invoked (this process saves the current frame state + // into the reference frames). + // + // 2. If show_frame is equal to 1 or show_existing_frame is + // equal to 1, the output process as specified in section 7.18 + // is invoked (this will output the current frame or a saved + // frame). + // + // We implement 1. here while 2. is left to the actual decoder + self.load_reference_frame(&mut fh)?; + if fh.frame_type == FrameType::KeyFrame { + fh.refresh_frame_flags = ALL_FRAMES; + } + + if film_grain_params_present { + // load_grain_params() + fh.film_grain_params = + self.ref_info[fh.frame_to_show_map_idx as usize].film_grain_params.clone(); + } + + // See 5.10. + if matches!(obu.header.obu_type, ObuType::Frame) { + r.byte_alignment()?; + } + + fh.header_bytes = usize::try_from(r.0.position() / 8).unwrap(); + return Ok(fh); + } + + fh.frame_type = FrameType::try_from(r.0.read_bits::(2)?)?; + fh.frame_is_intra = + matches!(fh.frame_type, FrameType::IntraOnlyFrame | FrameType::KeyFrame); + + fh.show_frame = r.0.read_bit()?; + + if fh.show_frame && decoder_model_info_present_flag && equal_picture_interval { + fh.frame_presentation_time = + r.0.read_bits::(frame_presentation_time_length_minus_1 as usize + 1)?; + } + + if fh.show_frame { + fh.showable_frame = !matches!(fh.frame_type, FrameType::KeyFrame); + } else { + fh.showable_frame = r.0.read_bit()?; + } + + if fh.frame_type == FrameType::SwitchFrame + || (fh.frame_type == FrameType::KeyFrame && fh.show_frame) + { + fh.error_resilient_mode = true; + } else { + fh.error_resilient_mode = r.0.read_bit()?; + } + } + + if fh.frame_type == FrameType::KeyFrame && fh.show_frame { + for i in 0..NUM_REF_FRAMES { + self.ref_info[i].ref_valid = false; + self.ref_info[i].ref_order_hint = 0; + } + for i in 0..REFS_PER_FRAME { + fh.order_hints[ReferenceFrameType::Last as usize + i] = 0; + } + } + + fh.disable_cdf_update = r.0.read_bit()?; + if seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS as u32 { + fh.allow_screen_content_tools = r.0.read_bit()? as u32; + } else { + fh.allow_screen_content_tools = seq_force_screen_content_tools; + } + + if fh.allow_screen_content_tools > 0 { + if seq_force_integer_mv == SELECT_INTEGER_MV as u32 { + fh.force_integer_mv = r.0.read_bit()? as u32; + } else { + fh.force_integer_mv = seq_force_integer_mv; + } + } else { + fh.force_integer_mv = 0; + } + + if fh.frame_is_intra { + fh.force_integer_mv = 1; + } + + if frame_id_numbers_present_flag { + self.prev_frame_id = self.current_frame_id; + self.current_frame_id = r.0.read_bits::(id_len.try_into().unwrap())?; + fh.current_frame_id = self.current_frame_id; + + /* conformance checking, as per aom */ + let have_prev_frame_id = + !(self.is_first_frame || fh.frame_type == FrameType::KeyFrame && fh.show_frame); + + if have_prev_frame_id { + let frame_id_length = + additional_frame_id_length_minus_1 + delta_frame_id_length_minus_2 + 3; + + let diff_frame_id = if self.current_frame_id > self.prev_frame_id { + self.current_frame_id - self.prev_frame_id + } else { + if frame_id_length > 16 { + return Err(format!("Invalid frame_id_length {}", frame_id_length)); + } + (1 << frame_id_length) + self.current_frame_id - self.prev_frame_id + }; + + if self.prev_frame_id == self.current_frame_id + || diff_frame_id >= (1 << (frame_id_length - 1)) + { + return Err(format!( + "Invalid frame_id: prev_frame_id = {}, current_frame_id = {}", + self.prev_frame_id, self.current_frame_id + )); + } + } + + /* mark_ref_frames (idLen) */ + let diff_len = delta_frame_id_length_minus_2 + 2; + let shifted_diff_len = 1 << diff_len; + let shifted_id_len = 1 << id_len; + + for i in 0..NUM_REF_FRAMES { + if self.current_frame_id > shifted_diff_len { + if self.ref_info[i].ref_frame_id > self.current_frame_id + || self.ref_info[i].ref_frame_id + < (self.current_frame_id - shifted_diff_len) + { + self.ref_info[i].ref_valid = false; + } + } else if self.ref_info[i].ref_frame_id > self.current_frame_id + && self.ref_info[i].ref_frame_id + < shifted_id_len + self.current_frame_id - shifted_diff_len + { + self.ref_info[i].ref_valid = false; + } + } + } else { + self.current_frame_id = 0; + self.prev_frame_id = self.current_frame_id; + fh.current_frame_id = self.current_frame_id; + } + + if fh.frame_type == FrameType::SwitchFrame { + fh.frame_size_override_flag = true; + } else if reduced_still_picture_header { + fh.frame_size_override_flag = false; + } else { + fh.frame_size_override_flag = r.0.read_bit()?; + } + + fh.order_hint = r.0.read_bits::(order_hint_bits.try_into().unwrap())?; + + if fh.frame_is_intra || fh.error_resilient_mode { + fh.primary_ref_frame = PRIMARY_REF_NONE; + } else { + fh.primary_ref_frame = r.0.read_bits::(3)?; + } + + let operating_points = &self.sequence()?.operating_points; + if decoder_model_info_present_flag { + fh.buffer_removal_time_present_flag = r.0.read_bit()?; + if fh.buffer_removal_time_present_flag { + #[allow(clippy::needless_range_loop)] + for op_num in 0..=operating_points_cnt_minus_1 as usize { + if operating_points[op_num].decoder_model_present_for_this_op { + let op_pt_idc = operating_points[op_num].idc; + let in_temporal_layer = (op_pt_idc >> fh.obu_header.temporal_id) & 1 != 0; + let in_spatial_layer = + (op_pt_idc >> (fh.obu_header.spatial_id + 8)) & 1 != 0; + + if op_pt_idc == 0 || (in_temporal_layer && in_spatial_layer) { + let n = buffer_removal_time_length_minus_1 + 1; + fh.buffer_removal_time[op_num] = r.0.read_bits::(n as usize)?; + } + } + } + } + } + + fh.allow_high_precision_mv = false; + fh.use_ref_frame_mvs = false; + fh.allow_intrabc = false; + if fh.frame_type == FrameType::SwitchFrame + || (fh.frame_type == FrameType::KeyFrame && fh.show_frame) + { + fh.refresh_frame_flags = ALL_FRAMES; + } else { + fh.refresh_frame_flags = r.0.read_bits::(8)?; + } + + /* equivalent boolean expression */ + if (!fh.frame_is_intra || fh.refresh_frame_flags != ALL_FRAMES) + && fh.error_resilient_mode + && enable_order_hint + { + for i in 0..NUM_REF_FRAMES { + fh.ref_order_hint[i] = r.0.read_bits::(order_hint_bits.try_into().unwrap())?; + if fh.ref_order_hint[i] != self.ref_info[i].ref_order_hint { + self.ref_info[i].ref_valid = false; + } + } + } + + if fh.frame_is_intra { + self.parse_frame_size(&mut fh, &mut r)?; + Self::parse_render_size(&mut fh, &mut r)?; + if fh.allow_screen_content_tools > 0 && fh.upscaled_width == fh.frame_width { + fh.allow_intrabc = r.0.read_bit()?; + } + } else { + if !enable_order_hint { + fh.frame_refs_short_signaling = false; + } else { + fh.frame_refs_short_signaling = r.0.read_bit()?; + if fh.frame_refs_short_signaling { + fh.last_frame_idx = r.0.read_bits::(3)? as u8; + fh.gold_frame_idx = r.0.read_bits::(3)? as u8; + let ref_order_hints = self + .ref_info + .iter() + .map(|i| i.ref_order_hint) + .collect::>() + .try_into() + .unwrap(); + self.set_frame_refs(&mut fh, &ref_order_hints)?; + } + } + + let mut expected_frame_id = [0; REFS_PER_FRAME]; + #[allow(clippy::needless_range_loop)] + for i in 0..REFS_PER_FRAME { + if !fh.frame_refs_short_signaling { + fh.ref_frame_idx[i] = r.0.read_bits::(3)?.try_into().unwrap(); + } + + if frame_id_numbers_present_flag { + /* DeltaFrameId */ + let delta_frame_id = + r.0.read_bits::(delta_frame_id_length_minus_2 as usize + 2)? + 1; + + if id_len == 0 { + return Err(format!("Invalid id_len {}", id_len)); + } + + let shifted_id_len = 1 << id_len; + + expected_frame_id[i] = + (self.current_frame_id + shifted_id_len - delta_frame_id) % shifted_id_len; + + let actual_frame_id = self.ref_info[fh.ref_frame_idx[i] as usize].ref_frame_id; + + if expected_frame_id[i] != actual_frame_id { + return Err(format!( + "Invalid frame id, expected {} got {}", + expected_frame_id[i], actual_frame_id + )); + } + } + } + + if fh.frame_size_override_flag && !fh.error_resilient_mode { + self.frame_size_with_refs(&mut fh, &mut r)?; + } else { + self.parse_frame_size(&mut fh, &mut r)?; + Self::parse_render_size(&mut fh, &mut r)?; + } + + if fh.force_integer_mv > 0 { + fh.allow_high_precision_mv = false; + } else { + fh.allow_high_precision_mv = r.0.read_bit()?; + } + + /* read_interpolation_filter */ + fh.is_filter_switchable = r.0.read_bit()?; + if fh.is_filter_switchable { + fh.interpolation_filter = InterpolationFilter::Switchable; + } else { + fh.interpolation_filter = InterpolationFilter::try_from(r.0.read_bits::(2)?)?; + } + + fh.is_motion_mode_switchable = r.0.read_bit()?; + + if fh.error_resilient_mode || !self.sequence()?.enable_ref_frame_mvs { + fh.use_ref_frame_mvs = false; + } else { + fh.use_ref_frame_mvs = r.0.read_bit()?; + } + + for i in 0..REFS_PER_FRAME { + let ref_frame = ReferenceFrameType::Last as usize + i; + let hint = self.ref_info[fh.ref_frame_idx[i] as usize].ref_order_hint; + fh.order_hints[ref_frame] = hint; + + if !enable_order_hint { + fh.ref_frame_sign_bias[i] = false; + } else { + fh.ref_frame_sign_bias[i] = helpers::get_relative_dist( + enable_order_hint, + order_hint_bits, + hint.try_into().unwrap(), + fh.order_hint.try_into().unwrap(), + ) > 0; + } + } + } + + if reduced_still_picture_header || fh.disable_cdf_update { + fh.disable_frame_end_update_cdf = true; + } else { + fh.disable_frame_end_update_cdf = r.0.read_bit()?; + } + + if fh.primary_ref_frame == PRIMARY_REF_NONE { + Self::setup_past_independence(&mut fh); + } else { + /* load from the past reference */ + let prev_frame = + &self.ref_info[fh.ref_frame_idx[fh.primary_ref_frame as usize] as usize]; + + if !prev_frame.ref_valid { + return Err("Reference is invalid".into()); + } + + /* load_loop_filter_params: load ref_deltas and mode_deltas */ + fh.loop_filter_params.loop_filter_ref_deltas = + prev_frame.loop_filter_params.loop_filter_ref_deltas; + fh.loop_filter_params.loop_filter_mode_deltas = + prev_frame.loop_filter_params.loop_filter_mode_deltas; + + /* load_segmentation_params: load feature_enabled and feature_data */ + fh.segmentation_params.feature_enabled = prev_frame.segmentation_params.feature_enabled; + fh.segmentation_params.feature_data = prev_frame.segmentation_params.feature_data; + } + + // TODO: we can live without this for now. + // if fh.use_ref_frame_mvs { + // // motion_field_estimators() + // } + + self.parse_tile_info(&mut r, &mut fh.tile_info)?; + Self::parse_quantization_params( + &mut r, + &mut fh.quantization_params, + num_planes, + separate_uv_delta_q, + )?; + self.parse_segmentation_params(&mut r, &mut fh)?; + Self::parse_delta_q_params(&mut r, &mut fh.quantization_params)?; + Self::parse_delta_lf_params( + &mut r, + &mut fh.loop_filter_params, + fh.quantization_params.delta_q_present, + fh.allow_intrabc, + )?; + + fh.coded_lossless = true; + for segment_id in 0..MAX_SEGMENTS { + let q_index = Self::get_qindex(&fh, true, segment_id as _); + let q = &fh.quantization_params; + fh.lossless_array[segment_id] = q_index == 0 + && q.delta_q_y_dc == 0 + && q.delta_q_u_ac == 0 + && q.delta_q_u_dc == 0 + && q.delta_q_v_ac == 0 + && q.delta_q_v_dc == 0; + if !fh.lossless_array[segment_id] { + fh.coded_lossless = false; + } + if q.using_qmatrix { + if fh.lossless_array[segment_id] { + fh.seg_qm_level[0][segment_id] = 15; + fh.seg_qm_level[1][segment_id] = 15; + fh.seg_qm_level[2][segment_id] = 15; + } else { + fh.seg_qm_level[0][segment_id] = q.qm_y; + fh.seg_qm_level[1][segment_id] = q.qm_u; + fh.seg_qm_level[2][segment_id] = q.qm_v; + } + } + } + + fh.all_lossless = fh.coded_lossless && fh.frame_width == fh.upscaled_width; + Self::parse_loop_filter_parameters(&mut r, &mut fh, num_planes)?; + Self::parse_cdef_params(&mut r, &mut fh, enable_cdef, num_planes)?; + Self::parse_loop_restoration_params( + &mut r, + &mut fh, + enable_restoration, + num_planes, + use_128x128_superblock, + subsampling_x, + subsampling_y, + )?; + Self::read_tx_mode(&mut r, &mut fh)?; + Self::parse_frame_reference_mode(&mut r, &mut fh)?; + self.parse_skip_mode_params(&mut r, &mut fh, enable_order_hint, order_hint_bits)?; + + if fh.frame_is_intra || fh.error_resilient_mode || !enable_warped_motion { + fh.allow_warped_motion = false; + } else { + fh.allow_warped_motion = r.0.read_bit()?; + } + + fh.reduced_tx_set = r.0.read_bit()?; + self.parse_global_motion_params(&mut r, &mut fh)?; + self.parse_film_grain_parameters( + &mut r, + &mut fh, + film_grain_params_present, + mono_chrome, + subsampling_x, + subsampling_y, + )?; + + Self::skip_and_check_trailing_bits(&mut r, obu)?; + + // See 5.10 + if matches!(obu.header.obu_type, ObuType::Frame) { + r.byte_alignment()?; + } + + fh.header_bytes = usize::try_from(r.0.position() / 8).unwrap(); + Ok(fh) + } + + fn parse_tile_group_obu<'a>(&mut self, obu: Obu<'a>) -> Result, String> { + let mut tg = TileGroupObu { obu, ..Default::default() }; + + let mut r = Reader::new(tg.obu.as_ref()); + + if r.0.num_bits_left() % 8 != 0 { + return Err("Bitstream is not byte aligned".into()); + } + + let mut sz: u64 = r.0.num_bits_left() as u64 / 8; + + let num_tiles = self.tile_rows * self.tile_cols; + let start_bit_pos = r.0.position(); + + if num_tiles > 1 { + tg.tile_start_and_end_present_flag = r.0.read_bit()?; + } + + if num_tiles == 1 || !tg.tile_start_and_end_present_flag { + tg.tg_start = 0; + tg.tg_end = num_tiles - 1; + } else { + let tile_bits = (self.tile_cols_log2 + self.tile_rows_log2) as usize; + tg.tg_start = r.0.read_bits::(tile_bits)?; + tg.tg_end = r.0.read_bits::(tile_bits)?; + } + + r.byte_alignment()?; + + let end_bit_pos = r.0.position(); + let header_bytes = (end_bit_pos - start_bit_pos) / 8; + sz -= header_bytes; + + let mut tile_num = tg.tg_start; + while tile_num <= tg.tg_end { + let tile_row = tile_num / self.tile_cols; + let tile_col = tile_num % self.tile_cols; + let last_tile = tile_num == tg.tg_end; + let tile_size; + + if last_tile { + tile_size = u32::try_from(sz).unwrap(); + } else { + tile_size = r.0.read_le::(self.tile_size_bytes.try_into().unwrap())? + 1; + sz -= u64::from(tile_size + self.tile_size_bytes); + } + + let tile = Tile { + tile_offset: u32::try_from(r.0.position()).unwrap() / 8, + tile_size, + tile_row, + tile_col, + mi_row_start: self.mi_row_starts[tile_row as usize], + mi_row_end: self.mi_row_starts[tile_row as usize + 1], + mi_col_start: self.mi_row_starts[tile_col as usize], + mi_col_end: self.mi_row_starts[tile_col as usize + 1], + }; + + tg.tiles.push(tile); + + // init_symbol, decode_tile() and exit_symbol() left to the accelerator. + + // Skip the actual tile data + if tile_num < tg.tg_end { + r.0.skip_bits(tile_size as usize * 8)?; + } + + tile_num += 1; + } + + if tg.tg_end == num_tiles - 1 { + // left to the accelerator: + // if ( !disable_frame_end_update_cdf ) { + // frame_end_update_cdf( ) + // } + // decode_frame_wrapup( ) + self.seen_frame_header = false; + } + + Ok(tg) + } + + fn parse_frame_obu<'a>(&mut self, obu: Obu<'a>) -> Result, String> { + if !matches!(obu.header.obu_type, ObuType::Frame) { + return Err(format!("Expected a FrameOBU, got {:?}", obu.header.obu_type)); + } + + let frame_header_obu = self.parse_frame_header_obu(&obu)?; + let obu = Obu { + header: obu.header, + data: match obu.data { + Cow::Borrowed(d) => Cow::Borrowed(&d[frame_header_obu.header_bytes..]), + Cow::Owned(d) => Cow::Owned(d[frame_header_obu.header_bytes..].to_owned()), + }, + bytes_used: obu.bytes_used, + }; + let tile_group_obu = self.parse_tile_group_obu(obu)?; + + Ok(FrameObu { header: frame_header_obu, tile_group: tile_group_obu }) + } + + pub fn parse_frame_header_obu(&mut self, obu: &Obu) -> Result { + if !matches!(obu.header.obu_type, ObuType::FrameHeader | ObuType::Frame) { + return Err(format!("Expected a FrameHeaderOBU, got {:?}", obu.header.obu_type)); + } + + if self.seen_frame_header { + Ok(self + .last_frame_header + .clone() + .take() + .ok_or::("Broken stream: no previous frame header to copy".into())?) + } else { + self.seen_frame_header = true; + let header = self.parse_uncompressed_frame_header(obu)?; + if header.show_existing_frame { + self.last_frame_header = None; + self.seen_frame_header = false; + } else { + /* TileNum = 0 */ + self.seen_frame_header = true; + self.last_frame_header = Some(header.clone()); + } + + Ok(header) + } + } + + /// Implements 7.20. This function should be called right after decoding a + /// frame. + pub fn ref_frame_update(&mut self, fh: &FrameHeaderObu) -> Result<(), String> { + // This was found as a bug otherwise by Nicolas Dufresne in GStreamer's + // av1parse. + if fh.show_existing_frame && !matches!(fh.frame_type, FrameType::KeyFrame) { + return Ok(()); + } + + if matches!(fh.frame_type, FrameType::IntraOnlyFrame) && fh.refresh_frame_flags == 0xff { + return Err("Intra-only frames cannot refresh all of the DPB as per the spec.".into()); + } + + let &SequenceHeaderObu { + color_config: ColorConfig { subsampling_x, subsampling_y, .. }, + film_grain_params_present, + bit_depth, + .. + } = self.sequence()?; + + for (i, ref_info) in self.ref_info.iter_mut().enumerate() { + if ((fh.refresh_frame_flags >> i) & 1) != 0 { + ref_info.ref_valid = true; + + ref_info.ref_frame_id = fh.current_frame_id; + ref_info.ref_frame_type = fh.frame_type; + ref_info.ref_upscaled_width = fh.upscaled_width; + ref_info.ref_frame_width = fh.frame_width; + ref_info.ref_frame_height = fh.frame_height; + ref_info.ref_render_width = fh.render_width; + ref_info.ref_render_height = fh.render_height; + ref_info.ref_order_hint = fh.order_hint; + ref_info.ref_mi_cols = self.mi_cols; + ref_info.ref_mi_rows = self.mi_rows; + ref_info.ref_subsampling_x = subsampling_x; + ref_info.ref_subsampling_y = subsampling_y; + ref_info.ref_bit_depth = bit_depth; + ref_info.segmentation_params = fh.segmentation_params.clone(); + ref_info.global_motion_params = fh.global_motion_params.clone(); + ref_info.loop_filter_params = fh.loop_filter_params.clone(); + ref_info.tile_info = fh.tile_info.clone(); + ref_info.display_frame_id = fh.display_frame_id; + ref_info.showable_frame = fh.showable_frame; + + if film_grain_params_present { + ref_info.film_grain_params = fh.film_grain_params.clone(); + } + } + } + + Ok(()) + } + + pub fn highest_operating_point(&self) -> Option { + if self.operating_point_idc == 0 { + /* No scalability information, all OBUs must be decoded */ + None + } else { + Some(helpers::floor_log2((self.operating_point_idc >> 8) as u32)) + } + } + + /// Fully parse an OBU. + pub fn parse_obu<'a>(&mut self, obu: Obu<'a>) -> Result, String> { + match obu.header.obu_type { + ObuType::Reserved => Ok(ParsedObu::Reserved), + ObuType::SequenceHeader => { + self.parse_sequence_header_obu(&obu).map(ParsedObu::SequenceHeader) + } + ObuType::TemporalDelimiter => { + self.parse_temporal_delimiter_obu().map(|_| ParsedObu::TemporalDelimiter) + } + ObuType::FrameHeader => self.parse_frame_header_obu(&obu).map(ParsedObu::FrameHeader), + ObuType::TileGroup => self.parse_tile_group_obu(obu).map(ParsedObu::TileGroup), + ObuType::Metadata => Ok(ParsedObu::Metadata), + ObuType::Frame => self.parse_frame_obu(obu).map(ParsedObu::Frame), + ObuType::RedundantFrameHeader => Ok(ParsedObu::RedundantFrameHeader), + ObuType::TileList => Ok(ParsedObu::TileList), + ObuType::Reserved2 => Ok(ParsedObu::Reserved2), + ObuType::Reserved3 => Ok(ParsedObu::Reserved3), + ObuType::Reserved4 => Ok(ParsedObu::Reserved4), + ObuType::Reserved5 => Ok(ParsedObu::Reserved5), + ObuType::Reserved6 => Ok(ParsedObu::Reserved6), + ObuType::Reserved7 => Ok(ParsedObu::Reserved7), + ObuType::Padding => Ok(ParsedObu::Padding), + } + } +} + +impl Default for Parser { + fn default() -> Self { + Self { + stream_format: StreamFormat::LowOverhead, + operating_point: Default::default(), + seen_frame_header: Default::default(), + last_frame_header: Default::default(), + operating_point_idc: Default::default(), + should_probe_for_annexb: true, + is_first_frame: Default::default(), + mi_cols: Default::default(), + mi_rows: Default::default(), + prev_frame_id: Default::default(), + current_frame_id: Default::default(), + ref_info: Default::default(), + mi_col_starts: [0; MAX_TILE_COLS + 1], + mi_row_starts: [0; MAX_TILE_ROWS + 1], + tile_cols_log2: Default::default(), + tile_cols: Default::default(), + tile_rows_log2: Default::default(), + tile_rows: Default::default(), + tile_size_bytes: Default::default(), + sequence_header: Default::default(), + } + } +} + +impl Clone for Parser { + fn clone(&self) -> Self { + let sequence_header = self.sequence_header.as_ref().map(|s| Rc::new((**s).clone())); + + Self { + stream_format: self.stream_format.clone(), + operating_point: self.operating_point, + seen_frame_header: self.seen_frame_header, + last_frame_header: self.last_frame_header.clone(), + operating_point_idc: self.operating_point_idc, + should_probe_for_annexb: self.should_probe_for_annexb, + is_first_frame: self.is_first_frame, + ref_info: self.ref_info.clone(), + mi_cols: self.mi_cols, + mi_rows: self.mi_rows, + prev_frame_id: self.prev_frame_id, + current_frame_id: self.current_frame_id, + mi_col_starts: self.mi_col_starts, + mi_row_starts: self.mi_row_starts, + tile_cols_log2: self.tile_cols_log2, + tile_cols: self.tile_cols, + tile_rows_log2: self.tile_rows_log2, + tile_rows: self.tile_rows, + tile_size_bytes: self.tile_size_bytes, + sequence_header, + } + } +} + +#[cfg(test)] +mod tests { + use crate::bitstream_utils::IvfIterator; + use crate::codec::av1::parser::{ObuAction, Parser, StreamFormat}; + + use super::ObuType; + + /// Same as test-25fps.av1.ivf from Chromium + const STREAM_TEST_25_FPS: &[u8] = include_bytes!("test_data/test-25fps.ivf.av1"); + + /// Encoded with + /// + /// gst-launch-1.0 videotestsrc num-buffers=1 ! + /// video/x-raw,format=I420,width=64,height=64 ! filesink + /// location=aom_input.yuv + /// + /// And: + /// + /// aomenc -p 1 --ivf -w 64 -h 64 -o av1-annexb.ivf.av1 aom_input.yuv --annexb=1 + const STREAM_ANNEXB: &[u8] = include_bytes!("test_data/av1-annexb.ivf.av1"); + + #[test] + fn parse_test25fps() { + let mut parser = Parser::default(); + let ivf_iter = IvfIterator::new(STREAM_TEST_25_FPS); + let mut num_obus = 0; + + for packet in ivf_iter { + let mut consumed = 0; + + while let Ok(obu) = parser.read_obu(&packet[consumed..]) { + let obu = match obu { + ObuAction::Process(obu) => obu, + // This OBU should be dropped. + ObuAction::Drop(length) => { + consumed += usize::try_from(length).unwrap(); + continue; + } + }; + consumed += obu.bytes_used; + num_obus += 1; + } + } + + // Manually checked with GStreamer under GDB by using a hitcount on + // "gst_av1_parse_identify_one_obu" *after* the stream format has been + // detected. + assert_eq!(num_obus, 525); + } + + #[test] + /// Test that we can correctly identify streams in both "low-overhead" and + /// Annex B formats. + fn parse_annexb() { + let mut parser = Parser::default(); + let mut ivf_iter = IvfIterator::new(STREAM_TEST_25_FPS); + let packet = ivf_iter.next().unwrap(); + + parser.read_obu(packet).unwrap(); + assert!(matches!(parser.stream_format, StreamFormat::LowOverhead)); + + let mut parser = Parser::default(); + let mut ivf_iter = IvfIterator::new(STREAM_ANNEXB); + let packet = ivf_iter.next().unwrap(); + + parser.read_obu(packet).unwrap(); + assert!(matches!(parser.stream_format, StreamFormat::AnnexB { .. })); + } + + #[test] + /// Test that we can correctly identify streams in both "low-overhead" and + /// Annex B formats and identify all the OBUs in the stream until the end. + fn parse_annexb_full() { + let mut parser = Parser::default(); + let ivf_iter = IvfIterator::new(STREAM_TEST_25_FPS); + + for packet in ivf_iter { + let mut consumed = 0; + + while let Ok(obu) = parser.read_obu(&packet[consumed..]) { + let obu = match obu { + ObuAction::Process(obu) => obu, + // This OBU should be dropped. + ObuAction::Drop(length) => { + consumed += usize::try_from(length).unwrap(); + continue; + } + }; + assert!(matches!(parser.stream_format, StreamFormat::LowOverhead)); + consumed += obu.bytes_used; + } + } + + let mut parser = Parser::default(); + let ivf_iter = IvfIterator::new(STREAM_ANNEXB); + let mut num_obus = 0; + + for packet in ivf_iter { + let mut consumed = 0; + + while let Ok(obu) = parser.read_obu(&packet[consumed..]) { + let obu = match obu { + ObuAction::Process(obu) => obu, + // This OBU should be dropped. + ObuAction::Drop(length) => { + consumed += usize::try_from(length).unwrap(); + continue; + } + }; + assert!(matches!(parser.stream_format, StreamFormat::AnnexB { .. })); + consumed += obu.bytes_used; + num_obus += 1; + } + } + + assert_eq!(num_obus, 3); + let annexb_state = match parser.stream_format { + StreamFormat::AnnexB(annexb_state) => annexb_state, + _ => panic!("Wrong StreamFormat, expected AnnexB"), + }; + assert_eq!(annexb_state.temporal_unit_consumed, annexb_state.temporal_unit_size); + assert_eq!(annexb_state.frame_unit_consumed, annexb_state.frame_unit_size); + } + + #[test] + fn parse_test25fps_obus() { + let mut parser = Parser::default(); + let ivf_iter = IvfIterator::new(STREAM_TEST_25_FPS); + + for packet in ivf_iter { + let mut consumed = 0; + + while let Ok(obu) = parser.read_obu(&packet[consumed..]) { + let obu = match obu { + ObuAction::Process(obu) => obu, + // This OBU should be dropped. + ObuAction::Drop(length) => { + consumed += usize::try_from(length).unwrap(); + continue; + } + }; + + let data_len = obu.bytes_used; + + match obu.header.obu_type { + ObuType::SequenceHeader => { + parser.parse_sequence_header_obu(&obu).unwrap(); + } + ObuType::FrameHeader | ObuType::RedundantFrameHeader => { + let fh = parser.parse_frame_header_obu(&obu).unwrap(); + parser.ref_frame_update(&fh).unwrap(); + } + ObuType::TileGroup => { + parser.parse_tile_group_obu(obu).unwrap(); + } + ObuType::Frame => { + let frame = parser.parse_frame_obu(obu).unwrap(); + parser.ref_frame_update(&frame.header).unwrap(); + } + _ => {} + }; + + consumed += data_len; + } + } + } +} diff --git a/vendor/cros-codecs/src/codec/av1/reader.rs b/vendor/cros-codecs/src/codec/av1/reader.rs new file mode 100644 index 0000000..38a9626 --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1/reader.rs @@ -0,0 +1,249 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::bitstream_utils::BitReader; + +use crate::codec::av1::helpers; + +use super::parser::AnnexBState; + +pub(crate) struct Reader<'a>(pub BitReader<'a>); + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Self(BitReader::new(data, false)) + } + + /// Implements uvlc(): Variable length unsigned n-bit number appearing + /// directly in the bitstream. See 4.10.3 + pub fn read_uvlc(&mut self) -> Result { + let mut leading_zeroes = 0; + loop { + let done = self.0.read_bit()?; + + if done { + break; + } + + leading_zeroes += 1; + } + + if leading_zeroes >= 32 { + return Ok(u32::MAX); + } + + let value = self.0.read_bits::(leading_zeroes)?; + Ok(value + (1 << leading_zeroes) - 1) + } + + /// Implements leb128(): Unsigned integer represented by a variable number + /// of little-endian bytes. See 4.10.5 + pub fn read_leb128(&mut self) -> Result { + let mut value = 0u64; + + for i in 0..8 { + let byte = u64::from(self.0.read_bits_aligned::(8)?); + value |= (byte & 0x7f) << (i * 7); + + if byte & 0x80 == 0 { + break; + } + } + + Ok(value as u32) + } + + /// Implements su(n): Signed integer converted from an n bits unsigned + /// integer in the bitstream. (The unsigned integer corresponds to the + /// bottom n bits of the signed integer.). See 4.10.6 + pub fn read_su(&mut self, num_bits: usize) -> Result { + let mut value: i32 = self + .0 + .read_bits::(num_bits)? + .try_into() + .map_err(|_| String::from("Read more than 31 signed bits!"))?; + let sign_mask = 1 << (num_bits - 1); + + if (value & sign_mask) != 0 { + value -= 2 * sign_mask; + } + + Ok(value) + } + + /// Implements ns(n): Unsigned encoded integer with maximum number of values + /// n (i.e. output in range 0..n-1). See 4.10.7 + pub fn read_ns(&mut self, num_bits: usize) -> Result { + let w = helpers::floor_log2(num_bits as u32) + 1; + let m = (1 << w) - num_bits as u32; + let v = self.0.read_bits::( + usize::try_from(w).map_err(|_| String::from("Invalid num_bits"))? - 1, + )?; + + if v < m.into() { + return Ok(v); + } + + let extra_bit = self.0.read_bit()?; + Ok((v << 1) - u32::from(m) + u32::from(extra_bit)) + } + + /// Implements 5.9.13: Delta quantizer syntax. + pub fn read_delta_q(&mut self) -> Result { + let delta_coded = self.0.read_bit()?; + + if delta_coded { + self.read_su(7) + } else { + Ok(0) + } + } + + pub fn more_data_in_bitstream(&mut self) -> bool { + self.0.num_bits_left() > 0 + } + + pub(crate) fn consumed(&self, start_pos: u32) -> u32 { + (self.0.position() / 8) as u32 - start_pos + } + + /// Get the length of the current OBU in AnnexB format. + pub fn current_annexb_obu_length( + &mut self, + annexb_state: &mut AnnexBState, + ) -> Result, String> { + if !self.more_data_in_bitstream() { + return Ok(None); + } + + #[allow(clippy::comparison_chain)] + if annexb_state.temporal_unit_consumed == annexb_state.temporal_unit_size { + annexb_state.temporal_unit_size = 0; + } else if annexb_state.temporal_unit_consumed > annexb_state.temporal_unit_size { + return Err(format!( + "temporal_unit_size is {} but we consumed {} bytes", + annexb_state.temporal_unit_size, annexb_state.temporal_unit_consumed, + )); + } + + if annexb_state.temporal_unit_size == 0 { + annexb_state.temporal_unit_size = self.read_leb128()?; + if annexb_state.temporal_unit_size == 0 { + return Ok(None); + } + } + + let start_pos = self.consumed(0); + + #[allow(clippy::comparison_chain)] + if annexb_state.frame_unit_consumed == annexb_state.frame_unit_size { + annexb_state.frame_unit_size = 0; + } else if annexb_state.frame_unit_consumed > annexb_state.frame_unit_size { + return Err(format!( + "frame_unit_size is {} but we consumed {} bytes", + annexb_state.frame_unit_size, annexb_state.frame_unit_consumed, + )); + } + + if annexb_state.frame_unit_size == 0 { + annexb_state.frame_unit_size = self.read_leb128()?; + if annexb_state.frame_unit_size == 0 { + return Ok(None); + } + annexb_state.temporal_unit_consumed += self.consumed(start_pos); + } + + let start_pos = self.consumed(0); + let obu_length = self.read_leb128()?; + let consumed = self.consumed(start_pos); + + annexb_state.temporal_unit_consumed += consumed; + annexb_state.frame_unit_consumed += consumed; + + Ok(Some(obu_length.try_into().unwrap())) + } + + /// Implements 5.3.4. + pub fn read_trailing_bits(&mut self, mut num_bits: u64) -> Result<(), String> { + let trailing_one_bit = self.0.read_bit()?; + num_bits -= 1; + + if !trailing_one_bit { + return Err("bad padding: trailing_one_bit is not set".into()); + } + + while num_bits > 0 { + let trailing_zero_bit = self.0.read_bit()?; + if trailing_zero_bit { + return Err("bad padding: trailing_zero_bit is set".into()); + } + num_bits -= 1; + } + + Ok(()) + } + + fn decode_subexp(&mut self, num_syms: i32) -> Result { + let mut i = 0; + let mut mk = 0; + let k = 3; + + loop { + let b2 = if i != 0 { k + i - 1 } else { k }; + let a = 1 << b2; + if num_syms <= mk + 3 * a { + let num_bits = num_syms - mk; + let subexp_final_bits = self.read_ns(num_bits as usize)?; + return Ok(subexp_final_bits); + } else { + let subexp_more_bits = self.0.read_bit()?; + if subexp_more_bits { + i += 1; + mk += a; + } else { + let num_bits = b2 as usize; + let subexp_bits = self.0.read_bits::(num_bits)?; + return Ok(subexp_bits + mk as u32); + } + } + } + } + + /// Implements 5.9.27. + pub fn decode_unsigned_subexp_with_ref(&mut self, mx: i32, r: i32) -> Result { + let v = self.decode_subexp(mx)?; + if (r << 1) <= mx { + Ok(helpers::inverse_recenter(r, v.try_into().unwrap()).try_into().unwrap()) + } else { + let res = mx - 1 - helpers::inverse_recenter(mx - 1 - r, v.try_into().unwrap()); + Ok(res.try_into().unwrap()) + } + } + + /// Implements 5.9.26. + pub fn decode_signed_subexp_with_ref( + &mut self, + low: i32, + high: i32, + r: i32, + ) -> Result { + let x = self.decode_unsigned_subexp_with_ref(high - low, r - low)?; + Ok(i32::try_from(x).unwrap() + low) + } + + /// Implements 5.3.5 Byte alignment syntax + pub fn byte_alignment(&mut self) -> Result<(), String> { + while (self.0.position() & 7) != 0 { + self.0.read_bit()?; + } + + Ok(()) + } +} + +impl<'a> Clone for Reader<'a> { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} diff --git a/vendor/cros-codecs/src/codec/av1/synthesizer.rs b/vendor/cros-codecs/src/codec/av1/synthesizer.rs new file mode 100644 index 0000000..ba5bf10 --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1/synthesizer.rs @@ -0,0 +1,1796 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::fmt; +use std::io::Write; +use std::num::TryFromIntError; + +use crate::codec::av1::helpers::clip3; +use crate::codec::av1::parser::BitDepth; +use crate::codec::av1::parser::ChromaSamplePosition; +use crate::codec::av1::parser::ColorPrimaries; +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::FrameRestorationType; +use crate::codec::av1::parser::FrameType; +use crate::codec::av1::parser::InterpolationFilter; +use crate::codec::av1::parser::MatrixCoefficients; +use crate::codec::av1::parser::ObuHeader; +use crate::codec::av1::parser::ObuType; +use crate::codec::av1::parser::Profile; +use crate::codec::av1::parser::ReferenceFrameType; +use crate::codec::av1::parser::SequenceHeaderObu; +use crate::codec::av1::parser::TemporalDelimiterObu; +use crate::codec::av1::parser::TransferCharacteristics; +use crate::codec::av1::parser::TxMode; +use crate::codec::av1::parser::WarpModelType; +use crate::codec::av1::parser::FEATURE_BITS; +use crate::codec::av1::parser::FEATURE_MAX; +use crate::codec::av1::parser::FEATURE_SIGNED; +use crate::codec::av1::parser::MAX_NUM_OPERATING_POINTS; +use crate::codec::av1::parser::MAX_NUM_PLANES; +use crate::codec::av1::parser::MAX_SEGMENTS; +use crate::codec::av1::parser::NUM_REF_FRAMES; +use crate::codec::av1::parser::PRIMARY_REF_NONE; +use crate::codec::av1::parser::REFS_PER_FRAME; +use crate::codec::av1::parser::SEG_LVL_MAX; +use crate::codec::av1::parser::SELECT_INTEGER_MV; +use crate::codec::av1::parser::SELECT_SCREEN_CONTENT_TOOLS; +use crate::codec::av1::parser::SUPERRES_DENOM_BITS; +use crate::codec::av1::parser::SUPERRES_DENOM_MIN; +use crate::codec::av1::parser::SUPERRES_NUM; +use crate::codec::av1::parser::TOTAL_REFS_PER_FRAME; +use crate::codec::av1::writer::ObuWriter; +use crate::codec::av1::writer::ObuWriterError; + +mod private { + pub trait ObuStruct {} +} + +impl private::ObuStruct for SequenceHeaderObu {} + +impl private::ObuStruct for TemporalDelimiterObu {} + +impl private::ObuStruct for FrameHeaderObu {} + +#[derive(Debug)] +pub enum SynthesizerError { + Unsupported, + InvalidSyntaxElementValue(&'static str), + ConversionError(TryFromIntError), + ObuWriter(ObuWriterError), + Io(std::io::Error), +} + +impl fmt::Display for SynthesizerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SynthesizerError::Unsupported => write!(f, "tried to synthesize unsupported settings"), + SynthesizerError::InvalidSyntaxElementValue(x) => { + write!(f, "invalid syntax element for value {}", x) + } + SynthesizerError::ConversionError(x) => write!(f, "{}", x.to_string()), + SynthesizerError::ObuWriter(x) => write!(f, "{}", x.to_string()), + SynthesizerError::Io(x) => write!(f, "{}", x.to_string()), + } + } +} + +impl From for SynthesizerError { + fn from(err: TryFromIntError) -> Self { + SynthesizerError::ConversionError(err) + } +} + +impl From for SynthesizerError { + fn from(err: ObuWriterError) -> Self { + SynthesizerError::ObuWriter(err) + } +} + +impl From for SynthesizerError { + fn from(err: std::io::Error) -> Self { + SynthesizerError::Io(err) + } +} + +pub type SynthesizerResult = Result; + +pub struct Synthesizer<'o, O: private::ObuStruct, W: Write> { + writer: ObuWriter, + obu: &'o O, +} + +impl<'o, O, W> Synthesizer<'o, O, W> +where + O: private::ObuStruct, + W: Write, +{ + fn new(writer: W, obu: &'o O) -> Self { + Self { writer: ObuWriter::new(writer), obu } + } + + fn f>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { + let value: u32 = value.into(); + self.writer.write_f(bits, value)?; + Ok(()) + } + + fn leb128>(&mut self, value: T) -> SynthesizerResult<()> { + let value: u32 = value.into(); + self.writer.write_leb128(value, 0)?; + Ok(()) + } + + fn uvlc>(&mut self, value: T) -> SynthesizerResult<()> { + self.writer.write_uvlc(value)?; + Ok(()) + } + + fn su>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { + self.writer.write_su(bits, value)?; + Ok(()) + } + + #[cfg(any(test, debug_assertions))] + fn invalid_element_value(&mut self, element: &'static str) -> SynthesizerResult<()> { + Err(SynthesizerError::InvalidSyntaxElementValue(element)) + } + + #[cfg(not(any(test, debug_assertions)))] + fn invalid_element_value(&mut self, element: &'static str) -> SynthesizerResult<()> { + log::error!("Invalid syntax element value: '{element}', expect corrupted bitstream"); + Ok(()) + } + + /// Writes 5.3.2. OBU header syntax + fn obu_header(&mut self, obu: &ObuHeader) -> SynthesizerResult<()> { + self.f(1, /* obu_forbidden_bit */ 0u32)?; + self.f(4, obu.obu_type as u32)?; + self.f(1, obu.extension_flag)?; + self.f(1, obu.has_size_field)?; + self.f(1, /* obu_reserved_1bit */ 0u32)?; + + if obu.extension_flag { + self.obu_extension_header(obu)?; + } + + Ok(()) + } + + /// Writes AV1 5.3.3. OBU extension header syntax + fn obu_extension_header(&mut self, obu: &ObuHeader) -> SynthesizerResult<()> { + // AV1 5.3.3 + self.f(3, obu.temporal_id)?; + self.f(2, obu.spatial_id)?; + self.f(3, /* extension_header_reserved_3bits */ 0u32)?; + + Ok(()) + } + + fn obu_size(&mut self, size: u32) -> SynthesizerResult<()> { + self.leb128(size) + } + + /// Writes AV1 5.3.4. Trailing bits syntax + fn trailing_bits(&mut self) -> SynthesizerResult<()> { + self.f(1, /* trailing_one_bit */ 1u32)?; + while !self.writer.aligned() { + self.f(1, /* trailing_zero_bit */ 0u32)?; + } + + Ok(()) + } +} + +impl<'o, W> Synthesizer<'o, TemporalDelimiterObu, W> +where + W: Write, +{ + pub fn synthesize(obu: &'o TemporalDelimiterObu, writer: W) -> SynthesizerResult<()> { + let mut s = Self::new(writer, obu); + + if obu.obu_header.obu_type != ObuType::TemporalDelimiter { + s.invalid_element_value("obu_type")?; + } + + s.obu_header(&obu.obu_header)?; + + if obu.obu_header.has_size_field { + s.obu_size(0u32)?; + } + + Ok(()) + } +} + +impl<'o, W> Synthesizer<'o, SequenceHeaderObu, W> +where + W: Write, +{ + pub fn synthesize(obu: &'o SequenceHeaderObu, mut writer: W) -> SynthesizerResult<()> { + let mut s = Synthesizer::new(&mut writer, obu); + + if obu.obu_header.obu_type != ObuType::SequenceHeader { + s.invalid_element_value("obu_type")?; + } + + s.obu_header(&obu.obu_header)?; + + if !obu.obu_header.has_size_field { + s.sequence_header_obu()?; + s.trailing_bits()?; + return Ok(()); + } + + let mut buf = Vec::::new(); + let mut buffered = Synthesizer::new(&mut buf, obu); + buffered.sequence_header_obu()?; + buffered.trailing_bits()?; + drop(buffered); + + s.obu_size(buf.len() as u32)?; + drop(s); + + writer.write_all(&buf)?; + + Ok(()) + } + + /// Writes AV1 5.5.1. General sequence header OBU syntax + fn sequence_header_obu(&mut self) -> SynthesizerResult<()> { + self.f(3, self.obu.seq_profile as u32)?; + self.f(1, self.obu.still_picture)?; + self.f(1, self.obu.reduced_still_picture_header)?; + + if self.obu.reduced_still_picture_header { + if self.obu.timing_info_present_flag { + self.invalid_element_value("reduced_still_picture_header")? + } + if self.obu.timing_info_present_flag { + self.invalid_element_value("timing_info_present_flag")? + } + if self.obu.initial_display_delay_present_flag { + self.invalid_element_value("initial_display_delay_present_flag")? + } + if self.obu.operating_points_cnt_minus_1 != 0 { + self.invalid_element_value("operating_points_cnt_minus_1")? + } + if self.obu.operating_points[0].idc != 0 { + self.invalid_element_value("operating_point_idc")? + } + + self.f(5, self.obu.operating_points[0].seq_level_idx)?; + + if self.obu.operating_points[0].decoder_model_present_for_this_op { + self.invalid_element_value("decoder_model_present_for_this_op")? + } + if self.obu.operating_points[0].initial_display_delay_present_for_this_op { + self.invalid_element_value("initial_display_delay_present_for_this_op")? + } + } else { + self.f(1, self.obu.timing_info_present_flag)?; + if self.obu.timing_info_present_flag { + self.timing_info()?; + self.f(1, self.obu.decoder_model_info_present_flag)?; + if self.obu.decoder_model_info_present_flag { + self.decoder_model_info()?; + } + } else if self.obu.decoder_model_info_present_flag { + self.invalid_element_value("decoder_model_info_present_flag")?; + } + + self.f(1, self.obu.initial_display_delay_present_flag)?; + + if self.obu.operating_points_cnt_minus_1 > MAX_NUM_OPERATING_POINTS as u32 { + self.invalid_element_value("operating_points_cnt_minus_1")?; + } + self.f(5, self.obu.operating_points_cnt_minus_1)?; + for i in 0..=self.obu.operating_points_cnt_minus_1 { + let op = &self.obu.operating_points[i as usize]; + + self.f(12, op.idc)?; + self.f(5, op.seq_level_idx)?; + if op.seq_level_idx > 7 { + self.f(1, op.seq_tier)?; + } else if op.seq_tier != 0 { + self.invalid_element_value("seq_tier")?; + } + + if self.obu.decoder_model_info_present_flag { + self.f(1, op.decoder_model_present_for_this_op)?; + if op.decoder_model_present_for_this_op { + self.operating_parameters_info(i as usize)?; + } + } else if op.decoder_model_present_for_this_op { + self.invalid_element_value("decoder_model_present_for_this_op")?; + } + + if self.obu.initial_display_delay_present_flag { + self.f(1, op.initial_display_delay_present_for_this_op)?; + if op.initial_display_delay_present_for_this_op { + self.f(4, op.initial_display_delay_minus_1)?; + } + } + } + } + + let bits = u16::BITS - self.obu.max_frame_width_minus_1.leading_zeros(); + if self.obu.frame_width_bits_minus_1 as u32 + 1 < bits { + self.invalid_element_value("frame_width_bits_minus_1")?; + } + + let bits = u16::BITS - self.obu.max_frame_height_minus_1.leading_zeros(); + if self.obu.frame_height_bits_minus_1 as u32 + 1 < bits { + self.invalid_element_value("frame_height_bits_minus_1")?; + } + + self.f(4, self.obu.frame_width_bits_minus_1)?; + self.f(4, self.obu.frame_height_bits_minus_1)?; + + let n = self.obu.frame_width_bits_minus_1 as usize + 1; + if (n as u32) < u16::BITS - self.obu.max_frame_width_minus_1.leading_zeros() { + self.invalid_element_value("max_frame_width_minus_1")?; + } + self.f(n, self.obu.max_frame_width_minus_1)?; + + let n = self.obu.frame_height_bits_minus_1 as usize + 1; + if (n as u32) < u16::BITS - self.obu.max_frame_height_minus_1.leading_zeros() { + self.invalid_element_value("max_frame_height_minus_1")?; + } + self.f(n, self.obu.max_frame_height_minus_1)?; + + if self.obu.reduced_still_picture_header { + if self.obu.frame_id_numbers_present_flag { + self.invalid_element_value("frame_id_numbers_present_flag")?; + } + } else { + self.f(1, self.obu.frame_id_numbers_present_flag)?; + } + + if self.obu.frame_id_numbers_present_flag { + self.f(4, self.obu.delta_frame_id_length_minus_2)?; + self.f(3, self.obu.additional_frame_id_length_minus_1)?; + } + + self.f(1, self.obu.use_128x128_superblock)?; + self.f(1, self.obu.enable_filter_intra)?; + self.f(1, self.obu.enable_intra_edge_filter)?; + + if self.obu.reduced_still_picture_header { + if self.obu.enable_interintra_compound { + self.invalid_element_value("enable_interintra_compound")?; + } + if self.obu.enable_masked_compound { + self.invalid_element_value("enable_masked_compound")?; + } + if self.obu.enable_warped_motion { + self.invalid_element_value("enable_warped_motion")?; + } + if self.obu.enable_dual_filter { + self.invalid_element_value("enable_dual_filter")?; + } + if self.obu.enable_order_hint { + self.invalid_element_value("enable_order_hint")?; + } + if self.obu.enable_jnt_comp { + self.invalid_element_value("enable_jnt_comp")?; + } + if self.obu.enable_ref_frame_mvs { + self.invalid_element_value("enable_ref_frame_mvs")?; + } + if self.obu.seq_force_screen_content_tools != SELECT_SCREEN_CONTENT_TOOLS as u32 { + self.invalid_element_value("seq_force_screen_content_tools")?; + } + if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 { + self.invalid_element_value("seq_force_integer_mv")?; + } + if self.obu.order_hint_bits != 0 { + self.invalid_element_value("OrderHintBits")?; + } + } else { + self.f(1, self.obu.enable_interintra_compound)?; + self.f(1, self.obu.enable_masked_compound)?; + self.f(1, self.obu.enable_warped_motion)?; + self.f(1, self.obu.enable_dual_filter)?; + self.f(1, self.obu.enable_order_hint)?; + + if self.obu.enable_order_hint { + self.f(1, self.obu.enable_jnt_comp)?; + self.f(1, self.obu.enable_ref_frame_mvs)?; + } else { + if self.obu.enable_jnt_comp { + self.invalid_element_value("enable_jnt_comp")?; + } + if self.obu.enable_ref_frame_mvs { + self.invalid_element_value("enable_ref_frame_mvs")?; + } + } + + self.f(1, self.obu.seq_choose_screen_content_tools)?; + if self.obu.seq_choose_screen_content_tools { + if self.obu.seq_force_screen_content_tools != SELECT_SCREEN_CONTENT_TOOLS as u32 { + self.invalid_element_value("seq_force_screen_content_tools")?; + } + } else { + self.f(1, self.obu.seq_force_screen_content_tools)?; + } + + if self.obu.seq_force_screen_content_tools > 0 { + self.f(1, self.obu.seq_choose_integer_mv)?; + if self.obu.seq_choose_integer_mv { + if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 { + self.invalid_element_value("seq_force_integer_mv")?; + } + } else { + self.f(1, self.obu.seq_force_integer_mv)?; + } + } else if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 { + self.invalid_element_value("seq_force_integer_mv")?; + } + + if self.obu.enable_order_hint { + self.f(3, self.obu.order_hint_bits_minus_1 as u32)?; + if self.obu.order_hint_bits != self.obu.order_hint_bits_minus_1 + 1 { + self.invalid_element_value("OrderHintBits")?; + } + } else if self.obu.order_hint_bits != 0 { + self.invalid_element_value("OrderHintBits")?; + } + } + + self.f(1, self.obu.enable_superres)?; + self.f(1, self.obu.enable_cdef)?; + self.f(1, self.obu.enable_restoration)?; + self.color_config()?; + self.f(1, self.obu.film_grain_params_present)?; + + Ok(()) + } + + /// Writes AV1 5.5.2. Color config syntax + fn color_config(&mut self) -> SynthesizerResult<()> { + let cc = &self.obu.color_config; + + self.f(1, cc.high_bitdepth)?; + if matches!(self.obu.seq_profile, Profile::Profile2) && cc.high_bitdepth { + self.f(1, cc.twelve_bit)?; + + if (cc.twelve_bit && self.obu.bit_depth != BitDepth::Depth12) + || (!cc.twelve_bit && self.obu.bit_depth != BitDepth::Depth10) + { + self.invalid_element_value("BitDepth")?; + } + } else if self.obu.seq_profile <= Profile::Profile2 + && ((cc.high_bitdepth && self.obu.bit_depth != BitDepth::Depth10) + || (!cc.high_bitdepth && self.obu.bit_depth != BitDepth::Depth8)) + { + self.invalid_element_value("BitDepth")?; + } + + if matches!(self.obu.seq_profile, Profile::Profile1) { + if cc.mono_chrome { + self.invalid_element_value("mono_chrome")?; + } + } else { + self.f(1, cc.mono_chrome)?; + } + + if (cc.mono_chrome && self.obu.num_planes != 1) + || (!cc.mono_chrome && self.obu.num_planes != 3) + { + self.invalid_element_value("NumPlanes")?; + } + + self.f(1, cc.color_description_present_flag)?; + if cc.color_description_present_flag { + self.f(8, cc.color_primaries as u32)?; + self.f(8, cc.transfer_characteristics as u32)?; + self.f(8, cc.matrix_coefficients as u32)?; + } else { + if !matches!(cc.color_primaries, ColorPrimaries::Unspecified) { + self.invalid_element_value("color_primaries")?; + } + if !matches!(cc.transfer_characteristics, TransferCharacteristics::Unspecified) { + self.invalid_element_value("transfer_characteristics")?; + } + if !matches!(cc.matrix_coefficients, MatrixCoefficients::Unspecified) { + self.invalid_element_value("matrix_coefficients")?; + } + } + + if cc.mono_chrome { + self.f(1, cc.color_range)?; + + if !cc.subsampling_x { + self.invalid_element_value("subsampling_x")?; + } + if !cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + if !matches!(cc.chroma_sample_position, ChromaSamplePosition::Unknown) { + self.invalid_element_value("chroma_sample_position")?; + } + if !matches!(cc.chroma_sample_position, ChromaSamplePosition::Unknown) { + self.invalid_element_value("chroma_sample_position")?; + } + if cc.separate_uv_delta_q { + self.invalid_element_value("separate_uv_delta_q")?; + } + + return Ok(()); + } else if matches!(cc.color_primaries, ColorPrimaries::Bt709) + && matches!(cc.transfer_characteristics, TransferCharacteristics::Srgb) + && matches!(cc.matrix_coefficients, MatrixCoefficients::Identity) + { + if !cc.color_range { + self.invalid_element_value("color_range")?; + } + if cc.subsampling_x { + self.invalid_element_value("subsampling_x")?; + } + if cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + } else { + self.f(1, cc.color_range)?; + + match self.obu.seq_profile { + Profile::Profile0 => { + if !cc.subsampling_x { + self.invalid_element_value("subsampling_x")?; + } + if !cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + } + Profile::Profile1 => { + if cc.subsampling_x { + self.invalid_element_value("subsampling_x")?; + } + if cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + } + _ => { + if matches!(self.obu.bit_depth, BitDepth::Depth12) { + self.f(1, cc.subsampling_x)?; + if cc.subsampling_x { + self.f(1, cc.subsampling_y)?; + } else if cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + } else { + if !cc.subsampling_x { + self.invalid_element_value("subsampling_x")?; + } + if cc.subsampling_y { + self.invalid_element_value("subsampling_y")?; + } + } + } + } + + if cc.subsampling_x && cc.subsampling_y { + self.f(2, cc.chroma_sample_position as u32)?; + } + } + + self.f(1, cc.separate_uv_delta_q)?; + + Ok(()) + } + + /// Writes AV1 5.5.3. Timing info syntax + fn timing_info(&mut self) -> SynthesizerResult<()> { + // AV1 5.5.3 + let ti = &self.obu.timing_info; + + self.f(32, ti.num_units_in_display_tick)?; + self.f(32, ti.time_scale)?; + self.f(1, ti.equal_picture_interval)?; + if ti.equal_picture_interval { + self.uvlc(ti.num_ticks_per_picture_minus_1)?; + } + + Ok(()) + } + + /// Writes AV1 5.5.4. Decoder model info syntax + fn decoder_model_info(&mut self) -> SynthesizerResult<()> { + let dm = &self.obu.decoder_model_info; + + self.f(5, dm.buffer_delay_length_minus_1)?; + self.f(32, dm.num_units_in_decoding_tick)?; + self.f(5, dm.buffer_removal_time_length_minus_1)?; + self.f(5, dm.frame_presentation_time_length_minus_1)?; + + Ok(()) + } + + /// Writes AV1 5.5.5. Operating parameters info syntax + fn operating_parameters_info(&mut self, i: usize) -> SynthesizerResult<()> { + let op = &self.obu.operating_points[i]; + + let n = usize::from(self.obu.decoder_model_info.buffer_delay_length_minus_1) + 1; + self.f(n, op.decoder_buffer_delay)?; + self.f(n, op.encoder_buffer_delay)?; + self.f(1, op.low_delay_mode_flag)?; + + Ok(()) + } +} + +impl<'o, W> Synthesizer<'o, FrameHeaderObu, W> +where + W: Write, +{ + pub fn synthesize( + obu: &'o FrameHeaderObu, + sequence: &'o SequenceHeaderObu, + mut writer: W, + ) -> SynthesizerResult<()> { + let mut s = Synthesizer::new(&mut writer, obu); + + if obu.obu_header.obu_type != ObuType::FrameHeader { + s.invalid_element_value("obu_type")?; + } + + s.obu_header(&obu.obu_header)?; + + if !obu.obu_header.has_size_field { + s.frame_header_obu(sequence)?; + s.trailing_bits()?; + return Ok(()); + } + + let mut buf = Vec::::new(); + let mut buffered = Synthesizer::new(&mut buf, obu); + buffered.frame_header_obu(sequence)?; + buffered.trailing_bits()?; + drop(buffered); + + s.obu_size(buf.len() as u32)?; + drop(s); + + writer.write_all(&buf)?; + + Ok(()) + } + + /// Writes AV1 5.9.1. General frame header OBU syntax + fn frame_header_obu(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + self.uncompressed_header(sequence) + } + + /// Writes AV1 5.9.2. Uncompressed header syntax + fn uncompressed_header(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + const ALL_FRAMES: u32 = (1 << NUM_REF_FRAMES) - 1; + + // idLen + let id_len = usize::try_from( + sequence.additional_frame_id_length_minus_1 + + sequence.delta_frame_id_length_minus_2 + + 3, + )?; + + if sequence.reduced_still_picture_header { + if !self.obu.show_existing_frame { + self.invalid_element_value("show_existing_frame")?; + } + if !matches!(self.obu.frame_type, FrameType::KeyFrame) { + self.invalid_element_value("frame_type")?; + } + if !self.obu.show_frame { + self.invalid_element_value("show_frame")?; + } + if !self.obu.showable_frame { + self.invalid_element_value("showable_frame")?; + } + if !self.obu.frame_is_intra { + self.invalid_element_value("FrameIsIntra")?; + } + } else { + self.f(1, self.obu.show_existing_frame)?; + if self.obu.show_existing_frame { + self.f(3, self.obu.frame_to_show_map_idx)?; + + if sequence.decoder_model_info_present_flag + && !sequence.timing_info.equal_picture_interval + { + self.temporal_point_info(sequence)?; + } + + if sequence.frame_id_numbers_present_flag { + self.f(id_len, self.obu.display_frame_id)?; + } + return Ok(()); + } + + self.f(2, self.obu.frame_type as u32)?; + if self.obu.frame_is_intra + ^ matches!(self.obu.frame_type, FrameType::IntraOnlyFrame | FrameType::KeyFrame) + { + self.invalid_element_value("FrameIsIntra")?; + } + + self.f(1, self.obu.show_frame)?; + if self.obu.show_frame + && sequence.decoder_model_info_present_flag + && !sequence.timing_info.equal_picture_interval + { + self.temporal_point_info(sequence)?; + } + + if self.obu.show_frame { + if self.obu.showable_frame ^ !matches!(self.obu.frame_type, FrameType::KeyFrame) { + self.invalid_element_value("showable_frame")?; + } + } else { + self.f(1, self.obu.showable_frame)?; + } + + if matches!(self.obu.frame_type, FrameType::SwitchFrame) + || (matches!(self.obu.frame_type, FrameType::KeyFrame) && self.obu.show_frame) + { + if !self.obu.error_resilient_mode { + self.invalid_element_value("error_resilient_mode")?; + } + } else { + self.f(1, self.obu.error_resilient_mode)?; + } + } + + self.f(1, self.obu.disable_cdf_update)?; + if sequence.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS as u32 { + self.f(1, self.obu.allow_screen_content_tools)?; + } else if self.obu.allow_screen_content_tools != sequence.seq_force_screen_content_tools { + self.invalid_element_value("allow_screen_content_tools")?; + } + + if self.obu.allow_screen_content_tools != 0 { + if sequence.seq_force_integer_mv == SELECT_INTEGER_MV as u32 { + self.f(1, self.obu.force_integer_mv)?; + } else if self.obu.force_integer_mv != sequence.seq_force_integer_mv { + self.invalid_element_value("force_integer_mv")?; + } + } else if self.obu.force_integer_mv != 0 + && !(self.obu.frame_is_intra && self.obu.force_integer_mv != 1) + { + self.invalid_element_value("force_integer_mv")?; + } + + if sequence.frame_id_numbers_present_flag { + self.f(id_len, self.obu.current_frame_id)?; + } else if self.obu.current_frame_id != 0 { + self.invalid_element_value("current_frame_id")?; + } + + if matches!(self.obu.frame_type, FrameType::SwitchFrame) { + if !self.obu.frame_size_override_flag { + self.invalid_element_value("frame_size_override_flag")?; + } + } else if sequence.reduced_still_picture_header { + if self.obu.frame_size_override_flag { + self.invalid_element_value("frame_size_override_flag")?; + } + } else { + self.f(1, self.obu.frame_size_override_flag)?; + } + + if sequence.order_hint_bits != 0 { + if sequence.order_hint_bits != sequence.order_hint_bits_minus_1 + 1 { + self.invalid_element_value("order_hint_bits_minus_1")?; + } + + self.f(sequence.order_hint_bits as usize, self.obu.order_hint)?; + } + + if self.obu.frame_is_intra || self.obu.error_resilient_mode { + if self.obu.primary_ref_frame != PRIMARY_REF_NONE { + self.invalid_element_value("primary_ref_frame")?; + } + } else { + self.f(3, self.obu.primary_ref_frame)?; + } + + if sequence.decoder_model_info_present_flag { + self.f(1, self.obu.buffer_removal_time_present_flag)?; + + for op_num in 0..=sequence.operating_points_cnt_minus_1 { + let op = &sequence.operating_points[op_num as usize]; + if op.decoder_model_present_for_this_op { + let in_temporal_layer = (op.idc >> self.obu.obu_header.temporal_id) & 1 != 0; + let in_spatial_layer = + (op.idc >> (self.obu.obu_header.spatial_id + 8)) & 1 != 0; + + if op.idc == 0 || (in_temporal_layer && in_spatial_layer) { + let n = usize::from( + sequence.decoder_model_info.buffer_removal_time_length_minus_1 + 1, + ); + + self.f(n, op.decoder_buffer_delay)?; + } + } + } + } + + if matches!(self.obu.frame_type, FrameType::SwitchFrame) + || (matches!(self.obu.frame_type, FrameType::KeyFrame) && self.obu.show_frame) + { + if self.obu.refresh_frame_flags != ALL_FRAMES { + self.invalid_element_value("refresh_frame_flags")?; + } + } else { + self.f(8, self.obu.refresh_frame_flags)?; + } + + if (!self.obu.frame_is_intra || self.obu.refresh_frame_flags != ALL_FRAMES) + && self.obu.error_resilient_mode + && sequence.enable_order_hint + { + for i in 0..NUM_REF_FRAMES { + self.f(sequence.order_hint_bits as usize, self.obu.ref_order_hint[i])?; + } + } + + if self.obu.frame_is_intra { + self.frame_size(sequence)?; + self.render_size()?; + + if self.obu.allow_screen_content_tools != 0 + && self.obu.upscaled_width == self.obu.frame_width + { + self.f(1, self.obu.allow_intrabc)?; + } + } else { + if !sequence.enable_order_hint { + if self.obu.frame_refs_short_signaling { + self.invalid_element_value("frame_refs_short_signaling")?; + } + } else { + self.f(1, self.obu.frame_refs_short_signaling)?; + if self.obu.frame_refs_short_signaling { + self.f(3, self.obu.last_frame_idx)?; + self.f(3, self.obu.gold_frame_idx)?; + } + } + + for i in 0..REFS_PER_FRAME { + let ref_frame_idx = self.obu.ref_frame_idx[i] as u32; + if !self.obu.frame_refs_short_signaling { + self.f(3, ref_frame_idx)?; + } + + if sequence.frame_id_numbers_present_flag { + let n = usize::try_from(sequence.delta_frame_id_length_minus_2 + 2)?; + + let delta_frame_id_minus_1 = ((self.obu.current_frame_id - ref_frame_idx + + (1 << id_len)) + % (1 << id_len)) + - 1; + + self.f(n, delta_frame_id_minus_1)?; + } + } + + if self.obu.frame_size_override_flag && !self.obu.error_resilient_mode { + self.frame_size_with_refs()?; + } else { + self.frame_size(sequence)?; + self.render_size()?; + } + + if self.obu.force_integer_mv != 0 { + if !self.obu.allow_high_precision_mv { + self.invalid_element_value("allow_high_precision_mv")?; + } + } else { + self.f(1, self.obu.allow_high_precision_mv)?; + } + + self.read_interpolation_filter()?; + self.f(1, self.obu.is_motion_mode_switchable)?; + + if self.obu.error_resilient_mode || !sequence.enable_ref_frame_mvs { + if self.obu.use_ref_frame_mvs { + self.invalid_element_value("use_ref_frame_mvs")?; + } + } else { + self.f(1, self.obu.use_ref_frame_mvs)?; + } + } + + if sequence.reduced_still_picture_header || self.obu.disable_cdf_update { + if !self.obu.disable_frame_end_update_cdf { + self.invalid_element_value("disable_frame_end_update_cdf")? + } + } else { + self.f(1, self.obu.disable_frame_end_update_cdf)?; + } + + self.tile_info()?; + self.quantization_params(sequence)?; + self.segmentation_params()?; + + self.delta_q_params()?; + self.delta_lf_params()?; + + if self.obu.coded_lossless && self.obu.lossless_array != [true; MAX_SEGMENTS] { + self.invalid_element_value("CodedLossless")?; + } + + if self.obu.all_lossless + ^ (self.obu.coded_lossless && self.obu.frame_width == self.obu.upscaled_width) + { + self.invalid_element_value("AllLossless")?; + } + + self.loop_filter_params(sequence)?; + self.cdef_params(sequence)?; + self.lr_params(sequence)?; + self.read_tx_mode()?; + self.frame_reference_mode()?; + self.skip_mode_params()?; + + if self.obu.frame_is_intra + || self.obu.error_resilient_mode + || !sequence.enable_warped_motion + { + if self.obu.allow_warped_motion { + self.invalid_element_value("allow_warped_motion")?; + } + } else { + self.f(1, self.obu.allow_warped_motion)?; + } + + self.f(1, self.obu.reduced_tx_set)?; + + self.global_motion_params()?; + self.film_grain_params(sequence)?; + + Ok(()) + } + + /// Writes AV1 5.9.31. Temporal point info syntax + fn temporal_point_info(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + let n = usize::try_from( + sequence.decoder_model_info.frame_presentation_time_length_minus_1 + 1, + )?; + + self.f(n, self.obu.frame_presentation_time)?; + + Ok(()) + } + + /// Writes AV1 5.9.5. Frame size syntax + fn frame_size(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if self.obu.frame_size_override_flag { + let n = sequence.frame_width_bits_minus_1 as usize + 1; + self.f(n, self.obu.frame_width - 1)?; + let n = sequence.frame_height_bits_minus_1 as usize + 1; + self.f(n, self.obu.frame_height - 1)?; + } else { + if self.obu.frame_width != sequence.max_frame_width_minus_1 as u32 + 1 { + self.invalid_element_value("FrameWidth")?; + } + if self.obu.frame_height != sequence.max_frame_height_minus_1 as u32 + 1 { + self.invalid_element_value("FrameHeight")?; + } + + self.superres_params(sequence)?; + } + + Ok(()) + } + + /// Writes AV1 5.9.6. Render size syntax + fn render_size(&mut self) -> SynthesizerResult<()> { + self.f(1, self.obu.render_and_frame_size_different)?; + + if self.obu.render_and_frame_size_different { + self.f(16, self.obu.render_width - 1)?; + self.f(16, self.obu.render_height - 1)?; + } else { + if self.obu.render_width != self.obu.upscaled_width { + self.invalid_element_value("RenderWidth")?; + } + if self.obu.render_height != self.obu.frame_height { + self.invalid_element_value("RenderHeight")?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.7. Frame size with refs syntax + fn frame_size_with_refs(&mut self) -> SynthesizerResult<()> { + log::error!("Syntax element frame_size_with_refs is unsupported"); + Err(SynthesizerError::Unsupported) + } + + /// Writes AV1 5.9.8. Superres params syntax + fn superres_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if sequence.enable_superres { + self.f(1, self.obu.use_superres)?; + } else if self.obu.use_superres { + self.invalid_element_value("use_superres")?; + } + + if self.obu.use_superres { + let coded_denom = self.obu.superres_denom - SUPERRES_DENOM_MIN as u32; + + self.f(SUPERRES_DENOM_BITS, coded_denom)?; + } else if self.obu.superres_denom != SUPERRES_NUM as u32 { + self.invalid_element_value("superres_denom")?; + } + + Ok(()) + } + + /// Writes AV1 5.9.10. Interpolation filter syntax + fn read_interpolation_filter(&mut self) -> SynthesizerResult<()> { + self.f(1, self.obu.is_filter_switchable)?; + if self.obu.is_filter_switchable { + if !matches!(self.obu.interpolation_filter, InterpolationFilter::Switchable) { + self.invalid_element_value("interpolation_filter")?; + } + } else { + self.f(2, self.obu.interpolation_filter as u32)?; + } + + Ok(()) + } + + /// Writes AV1 5.9.11. Loop filter params syntax + fn loop_filter_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if self.obu.coded_lossless || self.obu.allow_intrabc { + if !matches!(self.obu.loop_filter_params.loop_filter_level, [0, 0, _, _]) { + self.invalid_element_value("loop_filter_level")?; + } + if self.obu.loop_filter_params.loop_filter_ref_deltas != [1, 0, 0, 0, 0, -1, -1, -1] { + self.invalid_element_value("loop_filter_ref_deltas")?; + } + if self.obu.loop_filter_params.loop_filter_mode_deltas != [0, 0] { + self.invalid_element_value("loop_filter_mode_deltas")?; + } + return Ok(()); + } + + self.f(6, self.obu.loop_filter_params.loop_filter_level[0])?; + self.f(6, self.obu.loop_filter_params.loop_filter_level[1])?; + if sequence.num_planes > 1 + && self.obu.loop_filter_params.loop_filter_level[0] != 0 + && self.obu.loop_filter_params.loop_filter_level[1] != 0 + { + self.f(6, self.obu.loop_filter_params.loop_filter_level[2])?; + self.f(6, self.obu.loop_filter_params.loop_filter_level[3])?; + } + + self.f(3, self.obu.loop_filter_params.loop_filter_sharpness)?; + self.f(1, self.obu.loop_filter_params.loop_filter_delta_enabled)?; + if self.obu.loop_filter_params.loop_filter_delta_enabled { + self.f(1, self.obu.loop_filter_params.loop_filter_delta_update)?; + if self.obu.loop_filter_params.loop_filter_delta_update { + for i in 0..TOTAL_REFS_PER_FRAME { + // NOTE: Currently we have no way of checking if the value changed between + // frames, always update the value to make sure the decoder will recreate + // the same state. + const UPDATE_REF_DELTA: bool = true; + if UPDATE_REF_DELTA { + self.su(1 + 6, self.obu.loop_filter_params.loop_filter_ref_deltas[i])?; + } + } + + for i in 0..2 { + // NOTE: Same as above + const UPDATE_MODE_DELTA: bool = true; + if UPDATE_MODE_DELTA { + self.su(1 + 6, self.obu.loop_filter_params.loop_filter_mode_deltas[i])?; + } + } + } + } + + Ok(()) + } + + /// Writes AV1 5.9.12. Quantization params syntax + fn quantization_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + self.f(8, self.obu.quantization_params.base_q_idx)?; + self.read_delta_q(self.obu.quantization_params.delta_q_y_dc)?; + if sequence.num_planes > 1 { + if sequence.color_config.separate_uv_delta_q { + self.f(1, self.obu.quantization_params.diff_uv_delta)?; + } else if self.obu.quantization_params.diff_uv_delta { + self.invalid_element_value("diff_uv_delta")?; + }; + + self.read_delta_q(self.obu.quantization_params.delta_q_u_dc)?; + self.read_delta_q(self.obu.quantization_params.delta_q_u_ac)?; + + if self.obu.quantization_params.diff_uv_delta { + self.read_delta_q(self.obu.quantization_params.delta_q_v_dc)?; + self.read_delta_q(self.obu.quantization_params.delta_q_v_ac)?; + } else { + if self.obu.quantization_params.delta_q_v_dc != 0 { + self.invalid_element_value("delta_q_v_dc")?; + } + if self.obu.quantization_params.delta_q_v_ac != 0 { + self.invalid_element_value("delta_q_v_ac")?; + } + } + } else { + if self.obu.quantization_params.delta_q_u_dc != 0 { + self.invalid_element_value("delta_q_u_dc")?; + } + if self.obu.quantization_params.delta_q_u_ac != 0 { + self.invalid_element_value("delta_q_u_ac")?; + } + if self.obu.quantization_params.delta_q_v_dc != 0 { + self.invalid_element_value("delta_q_v_dc")?; + } + if self.obu.quantization_params.delta_q_v_ac != 0 { + self.invalid_element_value("delta_q_v_ac")?; + } + } + + self.f(1, self.obu.quantization_params.using_qmatrix)?; + if self.obu.quantization_params.using_qmatrix { + self.f(4, self.obu.quantization_params.qm_y)?; + self.f(4, self.obu.quantization_params.qm_u)?; + + if !sequence.color_config.separate_uv_delta_q { + if self.obu.quantization_params.qm_v != self.obu.quantization_params.qm_u { + self.invalid_element_value("qm_v")?; + } + } else { + self.f(4, self.obu.quantization_params.qm_v)?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.13. Delta quantizer syntax + fn read_delta_q(&mut self, delta_q: i32) -> SynthesizerResult<()> { + self.f(1, delta_q != 0)?; + if delta_q != 0 { + self.su(1 + 6, delta_q)?; + } + Ok(()) + } + + /// Writes AV1 5.9.14. Segmentation params syntax + fn segmentation_params(&mut self) -> SynthesizerResult<()> { + self.f(1, self.obu.segmentation_params.segmentation_enabled)?; + if self.obu.segmentation_params.segmentation_enabled { + if self.obu.primary_ref_frame == PRIMARY_REF_NONE { + if !self.obu.segmentation_params.segmentation_update_map { + self.invalid_element_value("segmentation_update_map")?; + } + + if self.obu.segmentation_params.segmentation_temporal_update { + self.invalid_element_value("segmentation_temporal_update")?; + } + + if !self.obu.segmentation_params.segmentation_update_data { + self.invalid_element_value("segmentation_update_data")?; + } + } else { + self.f(1, self.obu.segmentation_params.segmentation_update_map)?; + if self.obu.segmentation_params.segmentation_update_map { + self.f(1, self.obu.segmentation_params.segmentation_temporal_update)?; + } + self.f(1, self.obu.segmentation_params.segmentation_temporal_update)?; + } + + if self.obu.segmentation_params.segmentation_update_data { + for i in 0..MAX_SEGMENTS { + for j in 0..SEG_LVL_MAX { + let feature_enabled = self.obu.segmentation_params.feature_enabled[i][j]; + self.f(1, feature_enabled)?; + + if feature_enabled { + let bits_to_read = FEATURE_BITS[j] as usize; + let limit = FEATURE_MAX[j]; + let signed = FEATURE_SIGNED[j]; + + let value = i32::from(self.obu.segmentation_params.feature_data[i][j]); + if signed { + let clipped_value = clip3(-limit, limit, value); + self.su(bits_to_read + 1, clipped_value)?; + } else { + let clipped_value = clip3(0, limit, value); + self.f(bits_to_read, u32::try_from(clipped_value)?)?; + } + } + } + } + } else { + if self.obu.segmentation_params.feature_enabled + != [[false; SEG_LVL_MAX]; MAX_SEGMENTS] + { + self.invalid_element_value("feature_enabled")?; + } + if self.obu.segmentation_params.feature_data != [[0; SEG_LVL_MAX]; MAX_SEGMENTS] { + self.invalid_element_value("feature_data")?; + } + } + } + + Ok(()) + } + + /// Writes AV1 5.9.15. Tile info syntax + fn tile_info(&mut self) -> SynthesizerResult<()> { + // From AV1 5.9.9. Compute image size function + self.f(1, self.obu.tile_info.uniform_tile_spacing_flag)?; + if self.obu.tile_info.uniform_tile_spacing_flag { + if self.obu.tile_info.tile_cols != 1 + && self.obu.tile_info.tile_cols_log2 != 0 + && self.obu.tile_info.tile_rows != 1 + && self.obu.tile_info.tile_rows_log2 != 0 + { + // TODO: Allow more then single tile + log::error!("Only 1x1 tiles frame is currently supported"); + return Err(SynthesizerError::Unsupported); + } + + const INCREMENT_TILE_COLS_LOG2: u32 = 0; + const INCREMENT_TILE_ROWS_LOG2: u32 = 0; + + self.f(1, INCREMENT_TILE_COLS_LOG2)?; + self.f(1, INCREMENT_TILE_ROWS_LOG2)?; + } else { + // TODO + log::error!("Only uniformly sized tiles are currently supported"); + return Err(SynthesizerError::Unsupported); + } + + Ok(()) + } + + /// Writes AV1 5.9.17. Quantizer index delta parameters syntax + fn delta_q_params(&mut self) -> SynthesizerResult<()> { + if self.obu.quantization_params.base_q_idx > 0 { + self.f(1, self.obu.quantization_params.delta_q_present)?; + + if self.obu.quantization_params.delta_q_present { + self.f(2, self.obu.quantization_params.delta_q_res)?; + } + } else if self.obu.quantization_params.delta_q_present { + self.invalid_element_value("delta_q_present")?; + } + + Ok(()) + } + + /// Writes AV1 5.9.18. Loop filter delta parameters syntax + fn delta_lf_params(&mut self) -> SynthesizerResult<()> { + if self.obu.quantization_params.delta_q_present { + if self.obu.allow_intrabc { + self.f(1, self.obu.loop_filter_params.delta_lf_present)?; + + if self.obu.loop_filter_params.delta_lf_present { + self.f(2, self.obu.loop_filter_params.delta_lf_res)?; + self.f(1, self.obu.loop_filter_params.delta_lf_multi)?; + } + } else if self.obu.loop_filter_params.delta_lf_present { + self.invalid_element_value("delta_lf_present")?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.19. CDEF params syntax + fn cdef_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if self.obu.coded_lossless || self.obu.allow_intrabc || !sequence.enable_cdef { + if self.obu.cdef_params.cdef_bits != 0 { + self.invalid_element_value("cdef_bits")?; + } + + if self.obu.cdef_params.cdef_y_pri_strength[0] != 0 { + self.invalid_element_value("cdef_y_pri_strength")?; + } + + if self.obu.cdef_params.cdef_y_sec_strength[0] != 0 { + self.invalid_element_value("cdef_y_sec_strength")?; + } + + if self.obu.cdef_params.cdef_uv_pri_strength[0] != 0 { + self.invalid_element_value("cdef_uv_pri_strength")?; + } + + if self.obu.cdef_params.cdef_uv_sec_strength[0] != 0 { + self.invalid_element_value("cdef_uv_sec_strength")?; + } + + if self.obu.cdef_params.cdef_damping != 3 { + self.invalid_element_value("cdef_damping")?; + } + + return Ok(()); + } + + self.f(2, self.obu.cdef_params.cdef_damping - 3)?; + self.f(2, self.obu.cdef_params.cdef_bits)?; + + for i in 0..(1 << self.obu.cdef_params.cdef_bits) { + self.f(4, self.obu.cdef_params.cdef_y_pri_strength[i])?; + + let mut cdef_y_sec_strength = self.obu.cdef_params.cdef_y_sec_strength[i]; + if cdef_y_sec_strength == 4 { + cdef_y_sec_strength -= 1; + } + + self.f(2, cdef_y_sec_strength)?; + + if sequence.num_planes > 1 { + self.f(4, self.obu.cdef_params.cdef_uv_pri_strength[i])?; + + let mut cdef_uv_sec_strength = self.obu.cdef_params.cdef_uv_sec_strength[i]; + if cdef_uv_sec_strength == 4 { + cdef_uv_sec_strength -= 1; + } + + self.f(2, cdef_uv_sec_strength)?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.20. Loop restoration params syntax + fn lr_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if self.obu.all_lossless || self.obu.allow_intrabc || !sequence.enable_restoration { + if self.obu.loop_restoration_params.frame_restoration_type + != [FrameRestorationType::None; MAX_NUM_PLANES] + { + self.invalid_element_value("frame_restoration_type")?; + } + + if self.obu.loop_restoration_params.uses_lr { + self.invalid_element_value("uses_lr")?; + } + + return Ok(()); + } + + let mut uses_lr = false; + let mut uses_chroma_lr = false; + for i in 0..MAX_NUM_PLANES { + let lr_type = self.obu.loop_restoration_params.frame_restoration_type[i]; + self.f(2, lr_type as u32)?; + + if lr_type != FrameRestorationType::None { + uses_lr = true; + + if i > 0 { + uses_chroma_lr = true; + } + } + } + + if uses_lr ^ self.obu.loop_restoration_params.uses_lr { + self.invalid_element_value("uses_lr")?; + } + if uses_chroma_lr ^ self.obu.loop_restoration_params.uses_chroma_lr { + self.invalid_element_value("uses_chroma_lr")?; + } + + if uses_lr { + if sequence.use_128x128_superblock { + if self.obu.loop_restoration_params.lr_unit_shift == 0 { + self.invalid_element_value("lr_unit_shift")?; + } + + self.f(1, self.obu.loop_restoration_params.lr_unit_shift - 1)?; + } else { + self.f(1, self.obu.loop_restoration_params.lr_unit_shift)?; + if self.obu.loop_restoration_params.lr_unit_shift != 0 { + self.f(1, self.obu.loop_restoration_params.lr_unit_shift > 1)?; + } + } + + if sequence.color_config.subsampling_x + && sequence.color_config.subsampling_y + && uses_chroma_lr + { + self.f(1, self.obu.loop_restoration_params.lr_uv_shift)?; + } else if self.obu.loop_restoration_params.lr_uv_shift != 0 { + self.invalid_element_value("lr_uv_shift")?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.21. TX mode syntax + fn read_tx_mode(&mut self) -> SynthesizerResult<()> { + if self.obu.coded_lossless { + if self.obu.tx_mode != TxMode::Only4x4 { + self.invalid_element_value("TxMode")?; + } + } else { + self.f(1, self.obu.tx_mode_select)?; + + if (self.obu.tx_mode_select != 0 && self.obu.tx_mode != TxMode::Select) + || (self.obu.tx_mode_select == 0 && self.obu.tx_mode != TxMode::Largest) + { + self.invalid_element_value("TxMode")?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.22. Skip mode params syntax + fn skip_mode_params(&mut self) -> SynthesizerResult<()> { + // TODO: Implement if needed + Ok(()) + } + + /// Writes AV1 5.9.23. Frame reference mode syntax + fn frame_reference_mode(&mut self) -> SynthesizerResult<()> { + if self.obu.frame_is_intra { + if self.obu.reference_select { + self.invalid_element_value("reference_select")?; + } + } else { + self.f(1, self.obu.reference_select)?; + } + + Ok(()) + } + + /// Writes AV1 5.9.23. Frame reference mode syntax + fn global_motion_params(&mut self) -> SynthesizerResult<()> { + if self.obu.frame_is_intra { + return Ok(()); + } + + for ref_ in ReferenceFrameType::Last as usize..=ReferenceFrameType::AltRef as usize { + let is_global = self.obu.global_motion_params.is_global[ref_]; + let is_rot_zoom = self.obu.global_motion_params.is_rot_zoom[ref_]; + let is_translation = self.obu.global_motion_params.is_translation[ref_]; + let gm_type = self.obu.global_motion_params.gm_type[ref_]; + + let expected_type = match (is_global, is_rot_zoom, is_translation) { + (false, _, _) => WarpModelType::Identity, + (true, true, _) => WarpModelType::RotZoom, + (true, false, true) => WarpModelType::Translation, + (true, false, false) => WarpModelType::Affine, + }; + + if expected_type != gm_type { + self.invalid_element_value("GmType")?; + } + + self.f(1, is_global)?; + if is_global { + self.f(1, is_rot_zoom)?; + if is_rot_zoom { + } else { + self.f(1, is_translation)?; + } + } + + if gm_type >= WarpModelType::RotZoom { + self.read_global_param(gm_type, ref_, 2)?; + self.read_global_param(gm_type, ref_, 3)?; + if gm_type == WarpModelType::Affine { + self.read_global_param(gm_type, ref_, 4)?; + self.read_global_param(gm_type, ref_, 5)?; + } + } + + if gm_type >= WarpModelType::Translation { + self.read_global_param(gm_type, ref_, 0)?; + self.read_global_param(gm_type, ref_, 1)?; + } + } + + Ok(()) + } + + /// Writes AV1 5.9.25. Global param syntax + fn read_global_param( + &mut self, + _gm_type: WarpModelType, + _ref_: usize, + _idx: u32, + ) -> SynthesizerResult<()> { + // TODO + log::warn!( + "Syntax element read_global_param() is not currently supported. Use GmType=IDENTITY" + ); + Err(SynthesizerError::Unsupported) + } + + /// Writes AV1 5.9.30. Film grain params syntax + fn film_grain_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> { + if !sequence.film_grain_params_present || (!self.obu.show_frame && !self.obu.showable_frame) + { + return Ok(()); + } + + self.f(1, self.obu.film_grain_params.apply_grain)?; + if !self.obu.film_grain_params.apply_grain { + return Ok(()); + } + + Err(SynthesizerError::Unsupported) + } +} + +#[cfg(test)] +mod tests { + + use super::*; + use crate::codec::av1::parser::CdefParams; + use crate::codec::av1::parser::ChromaSamplePosition; + use crate::codec::av1::parser::ColorConfig; + use crate::codec::av1::parser::TileInfo; + use crate::codec::av1::parser::MAX_TILE_COLS; + use crate::codec::av1::parser::MAX_TILE_ROWS; + + #[test] + fn sequence_header_obu_test25fps() { + // Extraced from ./src/codec/av1/test_data/test-25fps.ivf.av1 + const SEQ_HDR_RAW: [u8; 13] = + [0x0a, 0x0b, 0x00, 0x00, 0x00, 0x04, 0x3c, 0xff, 0xbd, 0xff, 0xf9, 0x80, 0x40]; + + let seq_hdr = SequenceHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::SequenceHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + seq_profile: Profile::Profile0, + num_planes: 3, + still_picture: false, + reduced_still_picture_header: false, + timing_info_present_flag: false, + initial_display_delay_present_flag: false, + operating_points_cnt_minus_1: 0, + frame_width_bits_minus_1: 8, + frame_height_bits_minus_1: 7, + max_frame_width_minus_1: 319, + max_frame_height_minus_1: 239, + frame_id_numbers_present_flag: false, + use_128x128_superblock: true, + enable_filter_intra: true, + enable_intra_edge_filter: true, + enable_interintra_compound: true, + enable_masked_compound: true, + enable_warped_motion: true, + enable_dual_filter: true, + enable_order_hint: true, + enable_jnt_comp: true, + enable_ref_frame_mvs: true, + seq_choose_screen_content_tools: true, + seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS as u32, + seq_choose_integer_mv: true, + seq_force_integer_mv: SELECT_INTEGER_MV as u32, + order_hint_bits_minus_1: 6, + order_hint_bits: 7, + enable_superres: false, + enable_cdef: true, + enable_restoration: true, + color_config: ColorConfig { + high_bitdepth: false, + mono_chrome: false, + color_description_present_flag: false, + color_range: false, + subsampling_x: true, + subsampling_y: true, + chroma_sample_position: ChromaSamplePosition::Unknown, + separate_uv_delta_q: false, + ..Default::default() + }, + film_grain_params_present: false, + + ..Default::default() + }; + + let mut buf = Vec::::new(); + Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq_hdr, &mut buf).unwrap(); + assert_eq!(buf, SEQ_HDR_RAW); + } + + #[test] + fn sequence_header_obu_av1_annexb() { + // Extraced from: ./src/codec/av1/test_data/av1-annexb.ivf.av1 + const SEQ_HDR_RAW: [u8; 12] = + [0x0a, 0x0a, 0x00, 0x00, 0x00, 0x02, 0xaf, 0xff, 0xbf, 0xff, 0x30, 0x08]; + + let seq_hdr = SequenceHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::SequenceHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + seq_profile: Profile::Profile0, + num_planes: 3, + still_picture: false, + reduced_still_picture_header: false, + timing_info_present_flag: false, + initial_display_delay_present_flag: false, + operating_points_cnt_minus_1: 0, + frame_width_bits_minus_1: 5, + frame_height_bits_minus_1: 5, + max_frame_width_minus_1: 63, + max_frame_height_minus_1: 63, + frame_id_numbers_present_flag: false, + use_128x128_superblock: true, + enable_filter_intra: true, + enable_intra_edge_filter: true, + enable_interintra_compound: true, + enable_masked_compound: true, + enable_warped_motion: true, + enable_dual_filter: true, + enable_order_hint: true, + enable_jnt_comp: true, + enable_ref_frame_mvs: true, + seq_choose_screen_content_tools: true, + seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS as u32, + seq_choose_integer_mv: true, + seq_force_integer_mv: SELECT_INTEGER_MV as u32, + order_hint_bits_minus_1: 6, + order_hint_bits: 7, + enable_superres: false, + enable_cdef: true, + enable_restoration: true, + color_config: ColorConfig { + high_bitdepth: false, + mono_chrome: false, + color_description_present_flag: false, + color_range: false, + subsampling_x: true, + subsampling_y: true, + chroma_sample_position: ChromaSamplePosition::Unknown, + separate_uv_delta_q: false, + ..Default::default() + }, + film_grain_params_present: false, + + ..Default::default() + }; + + let mut buf = Vec::::new(); + Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq_hdr, &mut buf).unwrap(); + assert_eq!(buf, SEQ_HDR_RAW); + } + + #[test] + fn temporal_delim_obu() { + const TD_RAW: [u8; 2] = [0x12, 0x00]; + + let td = TemporalDelimiterObu { + obu_header: ObuHeader { + obu_type: ObuType::TemporalDelimiter, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + }; + + let mut buf = Vec::::new(); + Synthesizer::<'_, TemporalDelimiterObu, _>::synthesize(&td, &mut buf).unwrap(); + + assert_eq!(buf, TD_RAW); + } + + #[test] + fn frame_header_obu() { + let _ = env_logger::try_init(); + + const WIDTH: u32 = 512; + const HEIGHT: u32 = 512; + + let seq = SequenceHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::SequenceHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + seq_profile: Profile::Profile0, + + frame_width_bits_minus_1: 16 - 1, + frame_height_bits_minus_1: 16 - 1, + max_frame_width_minus_1: (WIDTH - 1) as u16, + max_frame_height_minus_1: (HEIGHT - 1) as u16, + + seq_force_integer_mv: SELECT_INTEGER_MV as u32, + + enable_order_hint: true, + order_hint_bits: 8, + order_hint_bits_minus_1: 7, + num_planes: 3, + + color_config: ColorConfig { + subsampling_x: true, + subsampling_y: true, + ..Default::default() + }, + + ..Default::default() + }; + + let frame = FrameHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::FrameHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + frame_type: FrameType::KeyFrame, + frame_is_intra: true, + primary_ref_frame: PRIMARY_REF_NONE, + refresh_frame_flags: 0xff, + error_resilient_mode: true, + + reduced_tx_set: true, + tx_mode_select: 1, + tx_mode: TxMode::Select, + + tile_info: TileInfo { + uniform_tile_spacing_flag: true, + tile_cols: 1, + tile_rows: 1, + tile_cols_log2: 0, + tile_rows_log2: 0, + width_in_sbs_minus_1: { + let mut value = [0u32; MAX_TILE_COLS]; + value[0] = WIDTH / 64 - 1; + value + }, + height_in_sbs_minus_1: { + let mut value = [0u32; MAX_TILE_ROWS]; + value[0] = HEIGHT / 64 - 1; + value + }, + ..Default::default() + }, + + cdef_params: CdefParams { cdef_damping: 3, ..Default::default() }, + + superres_denom: SUPERRES_NUM as u32, + upscaled_width: WIDTH, + frame_width: WIDTH, + frame_height: HEIGHT, + render_width: WIDTH, + render_height: HEIGHT, + + ..Default::default() + }; + + let mut buf = Vec::::new(); + Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq, &mut buf).unwrap(); + + Synthesizer::<'_, FrameHeaderObu, _>::synthesize(&frame, &seq, &mut buf).unwrap(); + + // TODO actual test + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + let mut out = std::fs::File::create("frame_header_obu.av1").unwrap(); + out.write_all(&buf).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/codec/av1/writer.rs b/vendor/cros-codecs/src/codec/av1/writer.rs new file mode 100644 index 0000000..96cd32f --- /dev/null +++ b/vendor/cros-codecs/src/codec/av1/writer.rs @@ -0,0 +1,199 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::fmt; +use std::io::Write; + +use crate::bitstream_utils::BitWriter; +use crate::bitstream_utils::BitWriterError; + +#[derive(Debug)] +pub enum ObuWriterError { + BitWriterError(BitWriterError), + UnalignedLeb128, +} + +impl fmt::Display for ObuWriterError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ObuWriterError::BitWriterError(x) => write!(f, "{}", x.to_string()), + ObuWriterError::UnalignedLeb128 => { + write!(f, "attempted to write leb128 on unaligned position") + } + } + } +} + +impl From for ObuWriterError { + fn from(err: BitWriterError) -> Self { + ObuWriterError::BitWriterError(err) + } +} + +pub type ObuWriterResult = std::result::Result; + +pub struct ObuWriter(BitWriter); + +impl ObuWriter { + pub fn new(writer: W) -> Self { + Self(BitWriter::new(writer)) + } + + /// Writes fixed bit size integer. Corresponds to `f(n)` in AV1 spec defined in 4.10.2. + pub fn write_f>(&mut self, bits: usize, value: T) -> ObuWriterResult { + self.0.write_f(bits, value).map_err(ObuWriterError::BitWriterError) + } + + /// Writes variable length unsigned n-bit number. Corresponds to `uvlc()` in AV1 spec + /// defined in 4.10.3. + pub fn write_uvlc>(&mut self, value: T) -> ObuWriterResult { + let value: u32 = value.into(); + if value == u32::MAX { + return self.write_f(32, 0u32); + } + + let value = value + 1; + let leading_zeros = (32 - value.leading_zeros()) as usize; + + Ok(self.write_f(leading_zeros - 1, 0u32)? + self.write_f(leading_zeros, value)?) + } + + /// Writes unsigned little-endian n-byte integer. Corresponds to `le(n)` in AV1 spec + /// defined in 4.10.4. + pub fn write_le>(&mut self, n: usize, value: T) -> ObuWriterResult { + let value: u32 = value.into(); + let mut value = value.to_le(); + + for _ in 0..n { + self.write_f(4, value & 0xff)?; + value >>= 8; + } + + Ok(n) + } + + /// Writes unsigned integer represented by a variable number of little-endian bytes. + /// Corresponds to `leb128()` in AV1 spec defined in 4.10.4. + /// + /// Note: Despite the name, the AV1 4.10.4 limits the value to [`u32::MAX`] = (1 << 32) - 1. + pub fn write_leb128>( + &mut self, + value: T, + min_bytes: usize, + ) -> ObuWriterResult { + if !self.aligned() { + return Err(ObuWriterError::UnalignedLeb128); + } + + let value: u32 = value.into(); + let mut value: u32 = value.to_le(); + let mut bytes = 0; + + for _ in 0..8 { + bytes += 1; + + if value >= 0x7f || bytes < min_bytes { + self.write_f(8, 0x80 | (value & 0x7f))?; + value >>= 7; + } else { + self.write_f(8, value & 0x7f)?; + break; + } + } + + assert!(value < 0x7f); + + Ok(bytes) + } + + pub fn write_su>(&mut self, bits: usize, value: T) -> ObuWriterResult { + let mut value: i32 = value.into(); + if value < 0 { + value += 1 << bits; + } + + assert!(value >= 0); + self.write_f(bits, value.unsigned_abs()) + } + + pub fn aligned(&self) -> bool { + !self.0.has_data_pending() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::codec::av1::reader::Reader; + + const TEST_VECTOR: &[u32] = &[ + // some random test values + u32::MAX, + 1, + 2, + 3, + 4, + 10, + 20, + 7312, + 8832, + 10123, + 47457, + 21390213, + u32::MIN, + u32::MAX - 1, + ]; + + #[test] + fn test_uvlc() { + for &value in TEST_VECTOR { + let mut buf = Vec::::new(); + + ObuWriter::new(&mut buf).write_uvlc(value).unwrap(); + + if value == u32::MAX { + // force stop uvlc + buf.push(0x80); + } + + let read = Reader::new(&buf).read_uvlc().unwrap(); + + assert_eq!(read, value, "failed testing {}", value); + } + } + + #[test] + fn test_leb128() { + for &value in TEST_VECTOR { + let mut buf = Vec::::new(); + + ObuWriter::new(&mut buf).write_leb128(value, 0).unwrap(); + let read = Reader::new(&buf).read_leb128().unwrap(); + + assert_eq!(read, value, "failed testing {}", value); + } + } + + #[test] + fn test_su() { + let vector = + TEST_VECTOR.iter().map(|e| *e as i32).chain(TEST_VECTOR.iter().map(|e| -(*e as i32))); + + for value in vector { + let bits = 32 - value.abs().leading_zeros() as usize + 1; // For sign + if bits >= 32 { + // Skip too big nubmers + continue; + } + + let mut buf = Vec::::new(); + + ObuWriter::new(&mut buf).write_su(bits, value).unwrap(); + + let read = Reader::new(&buf).read_su(bits as usize).unwrap(); + + assert_eq!(read, value, "failed testing {}", value); + } + } +} diff --git a/vendor/cros-codecs/src/codec/h264.rs b/vendor/cros-codecs/src/codec/h264.rs new file mode 100644 index 0000000..fc13025 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264.rs @@ -0,0 +1,10 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +pub mod dpb; +pub mod nalu; +pub mod nalu_writer; +pub mod parser; +pub mod picture; +pub mod synthesizer; diff --git a/vendor/cros-codecs/src/codec/h264/dpb.rs b/vendor/cros-codecs/src/codec/h264/dpb.rs new file mode 100644 index 0000000..00bba0a --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/dpb.rs @@ -0,0 +1,1243 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::Ref; +use std::cell::RefMut; +use std::fmt; +use std::rc::Rc; + +use log::debug; + +use crate::codec::h264::parser::MaxLongTermFrameIdx; +use crate::codec::h264::parser::RefPicMarkingInner; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::Field; +use crate::codec::h264::picture::FieldRank; +use crate::codec::h264::picture::IsIdr; +use crate::codec::h264::picture::PictureData; +use crate::codec::h264::picture::RcPictureData; +use crate::codec::h264::picture::Reference; + +pub type DpbPicRefList<'a, H> = Vec<&'a DpbEntry>; + +/// All the reference picture lists used to decode a picture. +#[derive(Default)] +pub struct ReferencePicLists { + /// Reference picture list for P slices. Retains the same meaning as in the + /// specification. Points into the pictures stored in the DPB. Derived once + /// per picture. + pub ref_pic_list_p0: Vec, + /// Reference picture list 0 for B slices. Retains the same meaning as in + /// the specification. Points into the pictures stored in the DPB. Derived + /// once per picture. + pub ref_pic_list_b0: Vec, + /// Reference picture list 1 for B slices. Retains the same meaning as in + /// the specification. Points into the pictures stored in the DPB. Derived + /// once per picture. + pub ref_pic_list_b1: Vec, +} + +/// A single entry in the DPB. +#[derive(Clone)] +pub struct DpbEntry { + /// `PictureData` of the frame in this entry. + pub pic: RcPictureData, + /// Reference to the decoded frame, ensuring that it doesn't get reused while in the DPB. + pub reference: Option, + /// Decoded frame promise. It will be set when the frame enters the DPB, and taken during the + /// bump process. + pub decoded_frame: Option, + /// Whether the picture is still waiting to be bumped and displayed. + needed_for_output: bool, +} + +impl DpbEntry { + /// Returns `true` is the entry is eligible to be bumped. + /// + /// An entry can be bumped if its `needed_for_output` flag is true and it is the first field of + /// a frame which fields are all decoded. + fn is_bumpable(&self) -> bool { + if !self.needed_for_output { + return false; + } + + let pic = self.pic.borrow(); + match pic.field { + // Progressive frames in the DPB are fully decoded. + Field::Frame => true, + // Only return the first field of fully decoded interlaced frames. + Field::Top | Field::Bottom => matches!(pic.field_rank(), FieldRank::First(..)), + } + } +} + +pub struct Dpb { + /// List of `PictureData` and backend handles to decoded pictures. + entries: Vec>, + /// The maximum number of pictures that can be stored. + max_num_pics: usize, + /// Indicates an upper bound for the number of frames buffers, in the + /// decoded picture buffer (DPB), that are required for storing frames, + /// complementary field pairs, and non-paired fields before output. It is a + /// requirement of bitstream conformance that the maximum number of frames, + /// complementary field pairs, or non-paired fields that precede any frame, + /// complementary field pair, or non-paired field in the coded video + /// sequence in decoding order and follow it in output order shall be less + /// than or equal to max_num_reorder_frames. + max_num_reorder_frames: usize, + /// Whether we're decoding in interlaced mode. Interlaced support is + /// inspired by the GStreamer implementation, in which frames are split if + /// interlaced=1. This makes reference marking easier. We also decode both + /// fields to the same frame, and this frame with both fields is outputted + /// only once. + interlaced: bool, +} + +#[derive(Debug)] +pub enum StorePictureError { + DpbIsFull, +} + +impl fmt::Display for StorePictureError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "DPB is full") + } +} + +impl std::error::Error for StorePictureError {} + +#[derive(Debug)] +pub enum MmcoError { + NoShortTermPic, + ExpectedMarked, + ExpectedExisting, + UnknownMmco(u8), +} + +impl fmt::Display for MmcoError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + MmcoError::NoShortTermPic => { + write!(f, "could not find ShortTerm picture to mark in the DPB") + } + MmcoError::ExpectedMarked => { + write!(f, "a ShortTerm picture was expected to be marked for MMCO=3") + } + MmcoError::ExpectedExisting => { + write!(f, "picture cannot be marked as nonexisting for MMCO=3") + } + MmcoError::UnknownMmco(x) => write!(f, "unknown MMCO: {}", x), + } + } +} + +impl std::error::Error for MmcoError {} + +impl Dpb { + /// Returns an iterator over the underlying H264 pictures stored in the + /// DPB. + fn pictures(&self) -> impl Iterator> { + self.entries.iter().map(|h| h.pic.borrow()) + } + + /// Returns a mutable iterator over the underlying H264 pictures stored in + /// the DPB. + fn pictures_mut(&mut self) -> impl Iterator> { + self.entries.iter().map(|h| h.pic.borrow_mut()) + } + + /// Returns the length of the DPB. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Get a reference to the whole DPB entries. + pub fn entries(&self) -> &Vec> { + &self.entries + } + + /// Set the DPB's limits in terms of maximum number or pictures. + pub fn set_limits(&mut self, max_num_pics: usize, max_num_reorder_frames: usize) { + self.max_num_pics = max_num_pics; + self.max_num_reorder_frames = max_num_reorder_frames; + } + + /// Get a reference to the dpb's max num pics. + pub fn max_num_pics(&self) -> usize { + self.max_num_pics + } + + // Returns the number of reference frames, counting the first field only if + // dealing with interlaced content. + pub fn num_ref_frames(&self) -> usize { + self.pictures().filter(|p| p.is_ref() && !p.is_second_field()).count() + } + + /// Get a reference to the dpb's interlaced mode. + pub fn interlaced(&self) -> bool { + self.interlaced + } + + /// Set the dpb's interlaced mode. + pub fn set_interlaced(&mut self, interlaced: bool) { + self.interlaced = interlaced; + } + + /// Find the short term reference picture with the lowest `frame_num_wrap` + /// value. + pub fn find_short_term_lowest_frame_num_wrap(&self) -> Option<&DpbEntry> { + let lowest = self + .entries + .iter() + .filter(|h| { + let p = h.pic.borrow(); + matches!(p.reference(), Reference::ShortTerm) + }) + .min_by_key(|h| { + let p = h.pic.borrow(); + p.frame_num_wrap + }); + + lowest + } + + /// Mark all pictures in the DPB as unused for reference. + pub fn mark_all_as_unused_for_ref(&mut self) { + for mut picture in self.pictures_mut() { + picture.set_reference(Reference::None, false); + } + } + + /// Remove unused pictures from the DPB. A picture is not going to be used + /// anymore if it's a) not a reference and b) not needed for output + fn remove_unused(&mut self) { + self.entries.retain(|entry| { + let pic = entry.pic.borrow(); + let discard = !pic.is_ref() && !entry.needed_for_output; + + if discard { + log::debug!("Removing unused picture {:#?}", pic); + } + + !discard + }); + } + + /// Find a short term reference picture with the given `pic_num` value. + fn find_short_term_with_pic_num_pos(&self, pic_num: i32) -> Option { + let position = self + .pictures() + .position(|p| matches!(p.reference(), Reference::ShortTerm) && p.pic_num == pic_num); + + log::debug!("find_short_term_with_pic_num: {}, found position {:?}", pic_num, position); + + position + } + + /// Find a short term reference picture with the given `pic_num` value. + pub fn find_short_term_with_pic_num(&self, pic_num: i32) -> Option<&DpbEntry> { + let position = self.find_short_term_with_pic_num_pos(pic_num)?; + Some(&self.entries[position]) + } + + /// Find a long term reference picture with the given `long_term_pic_num` + /// value. + fn find_long_term_with_long_term_pic_num_pos(&self, long_term_pic_num: u32) -> Option { + let position = self.pictures().position(|p| { + matches!(p.reference(), Reference::LongTerm) && p.long_term_pic_num == long_term_pic_num + }); + + log::debug!( + "find_long_term_with_long_term_pic_num: {}, found position {:?}", + long_term_pic_num, + position + ); + + position + } + + /// Find a long term reference picture with the given `long_term_pic_num` + /// value. + pub fn find_long_term_with_long_term_pic_num( + &self, + long_term_pic_num: u32, + ) -> Option<&DpbEntry> { + let position = self.find_long_term_with_long_term_pic_num_pos(long_term_pic_num)?; + Some(&self.entries[position]) + } + + /// Store `picture` and its backend handle in the DPB. + pub fn store_picture( + &mut self, + picture: RcPictureData, + handle: Option, + ) -> Result<(), StorePictureError> { + let max_pics = if self.interlaced { self.max_num_pics * 2 } else { self.max_num_pics }; + + if self.entries.len() >= max_pics { + return Err(StorePictureError::DpbIsFull); + } + + let pic = picture.borrow(); + + // C.4.2. Decoding of gaps in frame_num and storage of "non-existing" + // pictures + let needed_for_output = !pic.nonexisting; + + debug!( + "Stored picture POC {:?}, field {:?}, the DPB length is {:?}", + pic.pic_order_cnt, + pic.field, + self.entries.len() + ); + drop(pic); + + self.entries.push(DpbEntry { + pic: picture, + reference: handle.clone(), + decoded_frame: handle, + needed_for_output, + }); + + Ok(()) + } + + /// Whether the DPB has an empty slot for a new picture. + pub fn has_empty_frame_buffer(&self) -> bool { + let count = if !self.interlaced { + self.entries.len() + } else { + self.pictures() + .filter(|pic| { + matches!(pic.field_rank(), FieldRank::First(..)) + || (matches!(pic.field_rank(), FieldRank::Single) + && pic.field == Field::Frame) + }) + .count() + }; + + count < self.max_num_pics + } + + /// Whether the DPB needs bumping, as described by clauses 1, 4, 5, 6 of + /// C.4.5.3 "Bumping" process. + pub fn needs_bumping(&self, to_insert: &PictureData) -> bool { + // In C.4.5.3 we handle clauses 2 and 3 separately. All other clauses + // check for an empty frame buffer first. Here we handle: + // - There is no empty frame buffer and a empty frame buffer is + // needed for storage of an inferred "non-existing" frame. + // + // - There is no empty frame buffer and an empty frame buffer is + // needed for storage of a decoded (non-IDR) reference picture. + // + // - There is no empty frame buffer and the current picture is a non- + // reference picture that is not the second field of a complementary + // non-reference field pair and there are pictures in the DPB that + // are marked as "needed for output" that precede the current + // non-reference picture in output order. + // + // Clauses 2 and 3 are handled by H264Codec::handle_picture and + // H264Codec::finish_picture, respectively. + if self.has_empty_frame_buffer() { + return false; + } + + if to_insert.nonexisting { + return true; + } + + let non_idr_ref = to_insert.is_ref() && matches!(to_insert.is_idr, IsIdr::No); + if non_idr_ref { + return true; + } + + let lowest_poc = match self.find_lowest_poc_for_bumping() { + Some(handle) => handle.pic.borrow().pic_order_cnt, + None => return false, + }; + + !to_insert.is_second_field_of_complementary_ref_pair() + && to_insert.pic_order_cnt > lowest_poc + } + + /// Find the lowest POC in the DPB that can be bumped. + fn find_lowest_poc_for_bumping(&self) -> Option<&DpbEntry> { + self.entries + .iter() + .filter(|entry| entry.is_bumpable()) + .min_by_key(|handle| handle.pic.borrow().pic_order_cnt) + } + + /// Find the lowest POC in the DPB that can be bumped and return a mutable reference. + fn find_lowest_poc_for_bumping_mut(&mut self) -> Option<&mut DpbEntry> { + self.entries + .iter_mut() + .filter(|entry| entry.is_bumpable()) + .min_by_key(|handle| handle.pic.borrow().pic_order_cnt) + } + + /// Bump the dpb, returning a picture as per the bumping process described in C.4.5.3. + /// Note that this picture will still be referenced by its pair, if any. + fn bump(&mut self) -> Option> { + let dpb_entry = self.find_lowest_poc_for_bumping_mut()?; + let handle = dpb_entry.decoded_frame.take(); + let pic = dpb_entry.pic.borrow(); + + debug!("Bumping picture {:#?} from the dpb", pic); + + dpb_entry.needed_for_output = false; + // Lookup the second field entry and flip as well. + // `find_lowest_poc_for_bumping_mut` always returns the first field, never the second. + if let FieldRank::First(second_field) = pic.field_rank() { + let second_field = second_field.upgrade(); + drop(pic); + if let Some(second_field) = + second_field.and_then(|f| self.entries.iter_mut().find(|e| Rc::ptr_eq(&f, &e.pic))) + { + second_field.needed_for_output = false; + } + } + + Some(handle) + } + + /// Drains the DPB by continuously invoking the bumping process. + pub fn drain(&mut self) -> Vec> { + debug!("Draining the DPB."); + + let mut pics = vec![]; + + while let Some(pic) = self.bump() { + pics.push(pic); + } + + self.clear(); + + pics + } + + /// Clears the DPB, dropping all the pictures. + pub fn clear(&mut self) { + debug!("Clearing the DPB"); + + let max_num_pics = self.max_num_pics; + let interlaced = self.interlaced; + + *self = Default::default(); + + self.max_num_pics = max_num_pics; + self.interlaced = interlaced; + } + + /// Returns an iterator of short term refs. + pub fn short_term_refs_iter(&self) -> impl Iterator> { + self.entries + .iter() + .filter(|&handle| matches!(handle.pic.borrow().reference(), Reference::ShortTerm)) + } + + /// Returns an iterator of long term refs. + pub fn long_term_refs_iter(&self) -> impl Iterator> { + self.entries + .iter() + .filter(|&handle| matches!(handle.pic.borrow().reference(), Reference::LongTerm)) + } + + pub fn update_pic_nums( + &mut self, + frame_num: u32, + max_frame_num: u32, + current_pic: &PictureData, + ) { + for mut pic in self.pictures_mut() { + if !pic.is_ref() { + continue; + } + + if *pic.reference() == Reference::LongTerm { + pic.long_term_pic_num = if current_pic.field == Field::Frame { + pic.long_term_frame_idx + } else if current_pic.field == pic.field { + 2 * pic.long_term_frame_idx + 1 + } else { + 2 * pic.long_term_frame_idx + }; + } else { + pic.frame_num_wrap = if pic.frame_num > frame_num { + pic.frame_num as i32 - max_frame_num as i32 + } else { + pic.frame_num as i32 + }; + + pic.pic_num = if current_pic.field == Field::Frame { + pic.frame_num_wrap + } else if pic.field == current_pic.field { + 2 * pic.frame_num_wrap + 1 + } else { + 2 * pic.frame_num_wrap + }; + } + } + } + + /// Bumps the DPB if needed. DPB bumping is described on C.4.5.3. + pub fn bump_as_needed(&mut self, current_pic: &PictureData) -> Vec> { + let mut pics = vec![]; + while self.needs_bumping(current_pic) && self.len() >= self.max_num_reorder_frames { + match self.bump() { + Some(pic) => pics.push(pic), + None => return pics, + } + self.remove_unused(); + } + + pics + } + + // 8.2.5.3 + pub fn sliding_window_marking(&mut self, pic: &mut PictureData, sps: &Sps) { + // If the current picture is a coded field that is the second field in + // decoding order of a complementary reference field pair, and the first + // field has been marked as "used for short-term reference", the current + // picture and the complementary reference field pair are also marked as + // "used for short-term reference". + if let FieldRank::Second(other_field) = pic.field_rank() { + if matches!(other_field.borrow().reference(), Reference::ShortTerm) { + pic.set_reference(Reference::ShortTerm, false); + return; + } + } + + let mut num_ref_pics = self.num_ref_frames(); + let max_num_ref_frames = std::cmp::max(1, sps.max_num_ref_frames as usize); + + if num_ref_pics < max_num_ref_frames { + return; + } + + while num_ref_pics >= max_num_ref_frames { + if let Some(to_unmark) = self.find_short_term_lowest_frame_num_wrap() { + to_unmark.pic.borrow_mut().set_reference(Reference::None, true); + num_ref_pics -= 1; + } else { + log::warn!("could not find a ShortTerm picture to unmark in the DPB"); + break; + } + } + + self.remove_unused(); + } + + pub fn mmco_op_1( + &mut self, + pic: &PictureData, + marking: &RefPicMarkingInner, + ) -> Result<(), MmcoError> { + let pic_num_x = pic.pic_num - (marking.difference_of_pic_nums_minus1 as i32 + 1); + + log::debug!("MMCO op 1 for pic_num_x {}", pic_num_x); + log::trace!("Dpb state before MMCO=1: {:#?}", self); + + let to_mark = + self.find_short_term_with_pic_num(pic_num_x).ok_or(MmcoError::NoShortTermPic)?; + + to_mark.pic.borrow_mut().set_reference(Reference::None, matches!(pic.field, Field::Frame)); + + Ok(()) + } + + pub fn mmco_op_2( + &mut self, + pic: &PictureData, + marking: &RefPicMarkingInner, + ) -> Result<(), MmcoError> { + log::debug!("MMCO op 2 for long_term_pic_num {}", marking.long_term_pic_num); + + log::trace!("Dpb state before MMCO=2: {:#?}", self); + + let to_mark = self + .find_long_term_with_long_term_pic_num(marking.long_term_pic_num) + .ok_or(MmcoError::NoShortTermPic)?; + + to_mark.pic.borrow_mut().set_reference(Reference::None, matches!(pic.field, Field::Frame)); + + Ok(()) + } + + pub fn mmco_op_3( + &mut self, + pic: &PictureData, + marking: &RefPicMarkingInner, + ) -> Result<(), MmcoError> { + let pic_num_x = pic.pic_num - (marking.difference_of_pic_nums_minus1 as i32 + 1); + + log::debug!("MMCO op 3 for pic_num_x {}", pic_num_x); + log::trace!("Dpb state before MMCO=3: {:#?}", self); + + let to_mark_as_long_pos = + self.find_short_term_with_pic_num_pos(pic_num_x).ok_or(MmcoError::NoShortTermPic)?; + let to_mark_as_long = &self.entries[to_mark_as_long_pos].pic; + + if !matches!(to_mark_as_long.borrow().reference(), Reference::ShortTerm) { + return Err(MmcoError::ExpectedMarked); + } + + if to_mark_as_long.borrow().nonexisting { + return Err(MmcoError::ExpectedExisting); + } + + let to_mark_as_long_ptr = to_mark_as_long.as_ptr(); + let to_mark_as_long_other_field_ptr = + to_mark_as_long.borrow().other_field().map(|f| f.as_ptr()); + + let long_term_frame_idx = marking.long_term_frame_idx; + + for mut picture in self.pictures_mut() { + let long_already_assigned = matches!(picture.reference(), Reference::LongTerm) + && picture.long_term_frame_idx == long_term_frame_idx; + + if long_already_assigned { + let is_frame = matches!(picture.field, Field::Frame); + + let is_complementary_field_pair = picture + .other_field() + .map(|f| { + let pic = f.borrow(); + matches!(pic.reference(), Reference::LongTerm) + && pic.long_term_frame_idx == long_term_frame_idx + }) + .unwrap_or(false); + + // When LongTermFrameIdx equal to + // long_term_frame_idx is already assigned to a + // long-term reference frame or a long-term + // complementary reference field pair, that frame or + // complementary field pair and both of its fields + // are marked as "unused for reference" + if is_frame || is_complementary_field_pair { + picture.set_reference(Reference::None, true); + break; + } + + // When LongTermFrameIdx is already assigned to a + // reference field, and that reference field is not + // part of a complementary field pair that includes + // the picture specified by picNumX, that field is + // marked as "unused for reference". + let reference_field_is_not_part_of_pic_x = match picture.other_field() { + None => true, + Some(other_field) => { + // Check that the fields do not reference one another. + !std::ptr::eq(other_field.as_ptr(), to_mark_as_long_ptr) + && to_mark_as_long_other_field_ptr + .map(|p| !std::ptr::eq(p, &(*picture))) + .unwrap_or(true) + } + }; + + if reference_field_is_not_part_of_pic_x { + picture.set_reference(Reference::None, false); + break; + } + } + } + + let is_frame = matches!(pic.field, Field::Frame); + let to_mark_as_long = &self.entries[to_mark_as_long_pos].pic; + to_mark_as_long.borrow_mut().set_reference(Reference::LongTerm, is_frame); + to_mark_as_long.borrow_mut().long_term_frame_idx = long_term_frame_idx; + + if let Some(other_field) = to_mark_as_long.borrow().other_field() { + let mut other_field = other_field.borrow_mut(); + if matches!(other_field.reference(), Reference::LongTerm) { + other_field.long_term_frame_idx = long_term_frame_idx; + + log::debug!( + "Assigned long_term_frame_idx {} to other_field {:#?}", + long_term_frame_idx, + &other_field + ); + } + } + + Ok(()) + } + + /// Returns the new `max_long_term_frame_idx`. + pub fn mmco_op_4(&mut self, marking: &RefPicMarkingInner) -> MaxLongTermFrameIdx { + log::debug!("MMCO op 4, max_long_term_frame_idx: {:?}", marking.max_long_term_frame_idx); + + log::trace!("Dpb state before MMCO=4: {:#?}", self); + + for mut dpb_pic in self + .pictures_mut() + .filter(|pic| matches!(pic.reference(), Reference::LongTerm)) + .filter(|pic| marking.max_long_term_frame_idx < pic.long_term_frame_idx) + { + dpb_pic.set_reference(Reference::None, false); + } + + marking.max_long_term_frame_idx + } + + /// Returns the new `max_long_term_frame_idx`. + pub fn mmco_op_5(&mut self, pic: &mut PictureData) -> MaxLongTermFrameIdx { + log::debug!("MMCO op 5, marking all pictures in the DPB as unused for reference"); + log::trace!("Dpb state before MMCO=5: {:#?}", self); + + self.mark_all_as_unused_for_ref(); + + pic.has_mmco_5 = true; + + // A picture including a memory_management_control_operation equal to 5 + // shall have frame_num constraints as described above and, after the + // decoding of the current picture and the processing of the memory + // management control operations, the picture shall be inferred to have + // had frame_num equal to 0 for all subsequent use in the decoding + // process, except as specified in clause 7.4.1.2.4. + pic.frame_num = 0; + + // When the current picture includes a + // memory_management_control_operation equal to 5, after the decoding of + // the current picture, tempPicOrderCnt is set equal to PicOrderCnt( + // CurrPic ), TopFieldOrderCnt of the current picture (if any) is set + // equal to TopFieldOrderCnt − tempPicOrderCnt, and BottomFieldOrderCnt + // of the current picture (if any) is set equal to BottomFieldOrderCnt − + // tempPicOrderCnt + match pic.field { + Field::Top => { + pic.top_field_order_cnt = 0; + pic.pic_order_cnt = 0; + } + Field::Bottom => { + pic.bottom_field_order_cnt = 0; + pic.pic_order_cnt = 0; + } + Field::Frame => { + pic.top_field_order_cnt -= pic.pic_order_cnt; + pic.bottom_field_order_cnt -= pic.pic_order_cnt; + pic.pic_order_cnt = + std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt); + } + } + + MaxLongTermFrameIdx::NoLongTermFrameIndices + } + + pub fn mmco_op_6(&mut self, pic: &mut PictureData, marking: &RefPicMarkingInner) { + let long_term_frame_idx = marking.long_term_frame_idx; + + log::debug!("MMCO op 6, long_term_frame_idx: {}", long_term_frame_idx); + log::trace!("Dpb state before MMCO=6: {:#?}", self); + + for mut dpb_pic in self.pictures_mut() { + // When a variable LongTermFrameIdx equal to long_term_frame_idx is + // already assigned to a long-term reference frame or a long-term + // complementary reference field pair, that frame or complementary + // field pair and both of its fields are marked as "unused for + // reference". When LongTermFrameIdx is already assigned to a + // reference field, and that reference field is not part of a + // complementary field pair that includes the current picture, that + // field is marked as "unused for reference". + if matches!(dpb_pic.reference(), Reference::LongTerm) + && dpb_pic.long_term_frame_idx == long_term_frame_idx + { + let is_frame = matches!(dpb_pic.field, Field::Frame); + + let is_complementary_ref_field_pair = dpb_pic + .other_field() + .map(|f| { + let pic = f.borrow(); + matches!(pic.reference(), Reference::LongTerm) + && pic.long_term_frame_idx == long_term_frame_idx + }) + .unwrap_or(false); + + dpb_pic.set_reference(Reference::None, is_frame || is_complementary_ref_field_pair); + + break; + } + } + + let is_frame = matches!(pic.field, Field::Frame); + + let is_second_ref_field = match pic.field_rank() { + FieldRank::Second(first_field) + if *first_field.borrow().reference() == Reference::LongTerm => + { + first_field.borrow_mut().long_term_frame_idx = long_term_frame_idx; + true + } + _ => false, + }; + + pic.set_reference(Reference::LongTerm, is_frame || is_second_ref_field); + pic.long_term_frame_idx = long_term_frame_idx; + } + + #[cfg(debug_assertions)] + fn debug_ref_list_p(ref_pic_list: &[&DpbEntry], field_pic: bool) { + debug!( + "ref_list_p0: (ShortTerm|LongTerm, pic_num) {:?}", + ref_pic_list + .iter() + .map(|h| { + let p = h.pic.borrow(); + let reference = match p.reference() { + Reference::None => panic!("Not a reference."), + Reference::ShortTerm => "ShortTerm", + Reference::LongTerm => "LongTerm", + }; + + let field = if !p.is_second_field() { "First field" } else { "Second field" }; + + let field = format!("{}, {:?}", field, p.field); + + let inner = match (field_pic, p.reference()) { + (false, _) => ("pic_num", p.pic_num, field), + (true, Reference::ShortTerm) => ("frame_num_wrap", p.frame_num_wrap, field), + (true, Reference::LongTerm) => { + ("long_term_frame_idx", p.long_term_frame_idx as i32, field) + } + + _ => panic!("Not a reference."), + }; + (reference, inner) + }) + .collect::>() + ); + } + + #[cfg(debug_assertions)] + fn debug_ref_list_b(ref_pic_list: &[&DpbEntry], ref_pic_list_name: &str) { + debug!( + "{:?}: (ShortTerm|LongTerm, (POC|LongTermPicNum)) {:?}", + ref_pic_list_name, + ref_pic_list + .iter() + .map(|h| { + let p = h.pic.borrow(); + let reference = match p.reference() { + Reference::None => panic!("Not a reference."), + Reference::ShortTerm => "ShortTerm", + Reference::LongTerm => "LongTerm", + }; + + let field = if !p.is_second_field() { "First field" } else { "Second field" }; + + let field = format!("{}, {:?}", field, p.field); + + let inner = match p.reference() { + Reference::ShortTerm => ("POC", p.pic_order_cnt, field), + Reference::LongTerm => { + ("LongTermPicNum", p.long_term_pic_num as i32, field) + } + _ => panic!("Not a reference!"), + }; + (reference, inner) + }) + .collect::>() + ); + } + + fn sort_pic_num_descending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().pic_num)); + } + + fn sort_frame_num_wrap_descending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().frame_num_wrap)); + } + + fn sort_long_term_pic_num_ascending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| h.pic.borrow().long_term_pic_num); + } + + fn sort_long_term_frame_idx_ascending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| h.pic.borrow().long_term_frame_idx); + } + + fn sort_poc_descending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().pic_order_cnt)); + } + + fn sort_poc_ascending(pics: &mut [&DpbEntry]) { + pics.sort_by_key(|h| h.pic.borrow().pic_order_cnt); + } + + // When the reference picture list RefPicList1 has more than one entry + // and RefPicList1 is identical to the reference picture list + // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1] + // are switched. + fn swap_b1_if_needed(b0: &DpbPicRefList, b1: &mut DpbPicRefList) { + if b1.len() > 1 && b0.len() == b1.len() { + let mut equals = true; + for (x1, x2) in b0.iter().zip(b1.iter()) { + if !Rc::ptr_eq(&x1.pic, &x2.pic) { + equals = false; + break; + } + } + + if equals { + b1.swap(0, 1); + } + } + } + + /// Copies from refFrameList(XShort|Long)Term into RefPicListX as per 8.2.4.2.5. Used when + /// building the reference list for fields in interlaced decoding. + fn init_ref_field_pic_list<'a>( + mut field: Field, + reference_type: Reference, + ref_frame_list: &mut DpbPicRefList<'a, T>, + ref_pic_list: &mut DpbPicRefList<'a, T>, + ) { + // When one field of a reference frame was not decoded or is not marked as "used for + // (short|long)-term reference", the missing field is ignored and instead the next + // available stored reference field of the chosen parity from the ordered list of frames + // refFrameListX(Short|Long)Term is inserted into RefPicListX. + ref_frame_list.retain(|h| { + let p = h.pic.borrow(); + let skip = p.nonexisting || *p.reference() != reference_type; + !skip + }); + + while let Some(position) = ref_frame_list.iter().position(|h| { + let p = h.pic.borrow(); + let found = p.field == field; + + if found { + field = field.opposite(); + } + + found + }) { + let pic = ref_frame_list.remove(position); + ref_pic_list.push(pic); + } + + ref_pic_list.append(ref_frame_list); + } + + /// 8.2.4.2.1 Initialization process for the reference picture list for P + /// and SP slices in frames + fn build_ref_pic_list_p(&self) -> DpbPicRefList { + let mut ref_pic_list_p0: Vec<_> = + self.short_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field()).collect(); + + Self::sort_pic_num_descending(&mut ref_pic_list_p0); + + let num_short_term_refs = ref_pic_list_p0.len(); + + ref_pic_list_p0 + .extend(self.long_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field())); + Self::sort_long_term_pic_num_ascending(&mut ref_pic_list_p0[num_short_term_refs..]); + + #[cfg(debug_assertions)] + Self::debug_ref_list_p(&ref_pic_list_p0, false); + + ref_pic_list_p0 + } + + /// 8.2.4.2.2 Initialization process for the reference picture list for P + /// and SP slices in fields + fn build_ref_field_pic_list_p(&self, cur_pic: &PictureData) -> DpbPicRefList { + let mut ref_pic_list_p0 = vec![]; + + let mut ref_frame_list_0_short_term: Vec<_> = self.short_term_refs_iter().collect(); + Self::sort_frame_num_wrap_descending(&mut ref_frame_list_0_short_term); + + let mut ref_frame_list_long_term: Vec<_> = self.long_term_refs_iter().collect(); + Self::sort_long_term_pic_num_ascending(&mut ref_frame_list_long_term); + + // 8.2.4.2.5 + Self::init_ref_field_pic_list( + cur_pic.field, + Reference::ShortTerm, + &mut ref_frame_list_0_short_term, + &mut ref_pic_list_p0, + ); + Self::init_ref_field_pic_list( + cur_pic.field, + Reference::LongTerm, + &mut ref_frame_list_long_term, + &mut ref_pic_list_p0, + ); + + #[cfg(debug_assertions)] + Self::debug_ref_list_p(&ref_pic_list_p0, true); + + ref_pic_list_p0 + } + + // 8.2.4.2.3 Initialization process for reference picture lists for B slices + // in frames + fn build_ref_pic_list_b(&self, cur_pic: &PictureData) -> (DpbPicRefList, DpbPicRefList) { + let mut short_term_refs: Vec<_> = + self.short_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field()).collect(); + + // When pic_order_cnt_type is equal to 0, reference pictures that are + // marked as "non-existing" as specified in clause 8.2.5.2 are not + // included in either RefPicList0 or RefPicList1. + if cur_pic.pic_order_cnt_type == 0 { + short_term_refs.retain(|h| !h.pic.borrow().nonexisting); + } + + let mut ref_pic_list_b0 = vec![]; + let mut ref_pic_list_b1 = vec![]; + let mut remaining = vec![]; + // b0 contains three inner lists of pictures, i.e. [[0] [1] [2]] + // [0]: short term pictures with POC < current, sorted by descending POC. + // [1]: short term pictures with POC > current, sorted by ascending POC. + // [2]: long term pictures sorted by ascending long_term_pic_num + for &handle in &short_term_refs { + let pic = handle.pic.borrow(); + + if pic.pic_order_cnt < cur_pic.pic_order_cnt { + ref_pic_list_b0.push(handle); + } else { + remaining.push(handle); + } + } + + Self::sort_poc_descending(&mut ref_pic_list_b0); + Self::sort_poc_ascending(&mut remaining); + ref_pic_list_b0.append(&mut remaining); + + let mut long_term_refs: Vec<_> = self + .long_term_refs_iter() + .filter(|h| !h.pic.borrow().nonexisting) + .filter(|h| !h.pic.borrow().is_second_field()) + .collect(); + Self::sort_long_term_pic_num_ascending(&mut long_term_refs); + + ref_pic_list_b0.extend(long_term_refs.clone()); + + // b1 contains three inner lists of pictures, i.e. [[0] [1] [2]] + // [0]: short term pictures with POC > current, sorted by ascending POC. + // [1]: short term pictures with POC < current, sorted by descending POC. + // [2]: long term pictures sorted by ascending long_term_pic_num + for &handle in &short_term_refs { + let pic = handle.pic.borrow(); + + if pic.pic_order_cnt > cur_pic.pic_order_cnt { + ref_pic_list_b1.push(handle); + } else { + remaining.push(handle); + } + } + + Self::sort_poc_ascending(&mut ref_pic_list_b1); + Self::sort_poc_descending(&mut remaining); + + ref_pic_list_b1.extend(remaining); + ref_pic_list_b1.extend(long_term_refs); + + // When the reference picture list RefPicList1 has more than one entry + // and RefPicList1 is identical to the reference picture list + // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1] + // are switched. + Self::swap_b1_if_needed(&ref_pic_list_b0, &mut ref_pic_list_b1); + + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_pic_list_b0, "ref_pic_list_b0"); + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_pic_list_b1, "ref_pic_list_b1"); + + (ref_pic_list_b0, ref_pic_list_b1) + } + + /// 8.2.4.2.4 Initialization process for reference picture lists for B + /// slices in fields + fn build_ref_field_pic_list_b( + &self, + cur_pic: &PictureData, + ) -> (DpbPicRefList, DpbPicRefList) { + let mut ref_pic_list_b0 = vec![]; + let mut ref_pic_list_b1 = vec![]; + let mut ref_frame_list_0_short_term = vec![]; + let mut ref_frame_list_1_short_term = vec![]; + + let mut remaining = vec![]; + + let mut short_term_refs: Vec<_> = self.short_term_refs_iter().collect(); + + // When pic_order_cnt_type is equal to 0, reference pictures that are + // marked as "non-existing" as specified in clause 8.2.5.2 are not + // included in either RefPicList0 or RefPicList1. + if cur_pic.pic_order_cnt_type == 0 { + short_term_refs.retain(|h| !h.pic.borrow().nonexisting); + } + + // refFrameList0ShortTerm is comprised of two inner lists, [[0] [1]] + // [0]: short term pictures with POC <= current, sorted by descending POC + // [1]: short term pictures with POC > current, sorted by ascending POC + // NOTE 3 – When the current field follows in decoding order a coded + // field fldPrev with which together it forms a complementary reference + // field pair, fldPrev is included into the list refFrameList0ShortTerm + // using PicOrderCnt( fldPrev ) and the ordering method described in the + // previous sentence is applied. + for &handle in &short_term_refs { + let pic = handle.pic.borrow(); + + if pic.pic_order_cnt <= cur_pic.pic_order_cnt { + ref_frame_list_0_short_term.push(handle); + } else { + remaining.push(handle); + } + } + + Self::sort_poc_descending(&mut ref_frame_list_0_short_term); + Self::sort_poc_ascending(&mut remaining); + ref_frame_list_0_short_term.append(&mut remaining); + + // refFrameList1ShortTerm is comprised of two inner lists, [[0] [1]] + // [0]: short term pictures with POC > current, sorted by ascending POC + // [1]: short term pictures with POC <= current, sorted by descending POC + // NOTE 4 – When the current field follows in decoding order a coded + // field fldPrev with which together it forms a complementary reference + // field pair, fldPrev is included into the list refFrameList1ShortTerm + // using PicOrderCnt( fldPrev ) and the ordering method described in the + // previous sentence is applied. + + for &handle in &short_term_refs { + let pic = handle.pic.borrow(); + + if pic.pic_order_cnt > cur_pic.pic_order_cnt { + ref_frame_list_1_short_term.push(handle); + } else { + remaining.push(handle); + } + } + + Self::sort_poc_ascending(&mut ref_frame_list_1_short_term); + Self::sort_poc_descending(&mut remaining); + ref_frame_list_1_short_term.append(&mut remaining); + + // refFrameListLongTerm: long term pictures sorted by ascending + // LongTermFrameIdx. + // NOTE 5 – When the current picture is the second field of a + // complementary field pair and the first field of the complementary + // field pair is marked as "used for long-term reference", the first + // field is included into the list refFrameListLongTerm. A reference + // entry in which only one field is marked as "used for long-term + // reference" is included into the list refFrameListLongTerm + let mut ref_frame_list_long_term: Vec<_> = + self.long_term_refs_iter().filter(|h| !h.pic.borrow().nonexisting).collect(); + + Self::sort_long_term_frame_idx_ascending(&mut ref_frame_list_long_term); + + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_frame_list_0_short_term, "ref_frame_list_0_short_term"); + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_frame_list_1_short_term, "ref_frame_list_1_short_term"); + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_frame_list_long_term, "ref_frame_list_long_term"); + + // 8.2.4.2.5 + let field = cur_pic.field; + Self::init_ref_field_pic_list( + field, + Reference::ShortTerm, + &mut ref_frame_list_0_short_term, + &mut ref_pic_list_b0, + ); + Self::init_ref_field_pic_list( + field, + Reference::LongTerm, + &mut ref_frame_list_long_term, + &mut ref_pic_list_b0, + ); + + Self::init_ref_field_pic_list( + field, + Reference::ShortTerm, + &mut ref_frame_list_1_short_term, + &mut ref_pic_list_b1, + ); + Self::init_ref_field_pic_list( + field, + Reference::LongTerm, + &mut ref_frame_list_long_term, + &mut ref_pic_list_b1, + ); + + // When the reference picture list RefPicList1 has more than one entry + // and RefPicList1 is identical to the reference picture list + // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1] + // are switched. + Self::swap_b1_if_needed(&ref_pic_list_b0, &mut ref_pic_list_b1); + + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_pic_list_b0, "ref_pic_list_b0"); + #[cfg(debug_assertions)] + Self::debug_ref_list_b(&ref_pic_list_b1, "ref_pic_list_b1"); + + (ref_pic_list_b0, ref_pic_list_b1) + } + + /// Returns the lists of reference pictures for `pic`. + pub fn build_ref_pic_lists(&self, pic: &PictureData) -> ReferencePicLists { + let num_refs = self.pictures().filter(|p| p.is_ref() && !p.nonexisting).count(); + + // 8.2.4.2.1 ~ 8.2.4.2.4: When this process is invoked, there shall be + // at least one reference frame or complementary reference field pair + // that is currently marked as "used for reference" (i.e., as "used for + // short-term reference" or "used for long-term reference") and is not + // marked as "non-existing". + if num_refs == 0 { + return Default::default(); + } + + let (ref_pic_list_p0, (ref_pic_list_b0, ref_pic_list_b1)) = + if matches!(pic.field, Field::Frame) { + (self.build_ref_pic_list_p(), self.build_ref_pic_list_b(pic)) + } else { + (self.build_ref_field_pic_list_p(pic), self.build_ref_field_pic_list_b(pic)) + }; + + let dpb_start = self.entries.as_ptr(); + let refs_to_index = |refs: Vec<_>| { + refs.into_iter() + .map(|r| r as *const DpbEntry) + .map(|r| unsafe { r.offset_from(dpb_start) }) + .map(|i| i as usize) + .collect() + }; + + ReferencePicLists { + ref_pic_list_p0: refs_to_index(ref_pic_list_p0), + ref_pic_list_b0: refs_to_index(ref_pic_list_b0), + ref_pic_list_b1: refs_to_index(ref_pic_list_b1), + } + } +} + +impl Default for Dpb { + fn default() -> Self { + // See https://github.com/rust-lang/rust/issues/26925 on why this can't + // be derived. + Self { + entries: Default::default(), + max_num_pics: Default::default(), + max_num_reorder_frames: Default::default(), + interlaced: Default::default(), + } + } +} + +impl std::fmt::Debug for Dpb { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let pics = self.entries.iter().map(|h| &h.pic).enumerate().collect::>(); + f.debug_struct("Dpb") + .field("pictures", &pics) + .field("max_num_pics", &self.max_num_pics) + .field("interlaced", &self.interlaced) + .finish() + } +} diff --git a/vendor/cros-codecs/src/codec/h264/nalu.rs b/vendor/cros-codecs/src/codec/h264/nalu.rs new file mode 100644 index 0000000..82e5b48 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/nalu.rs @@ -0,0 +1,118 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Cow; +use std::fmt::Debug; +use std::io::Cursor; +use std::io::Seek; +use std::io::SeekFrom; + +#[allow(clippy::len_without_is_empty)] +pub trait Header: Sized { + /// Parse the NALU header, returning it. + fn parse>(cursor: &mut Cursor) -> Result; + /// Whether this header type indicates EOS. + fn is_end(&self) -> bool; + /// The length of the header. + fn len(&self) -> usize; +} + +#[derive(Debug)] +pub struct Nalu<'a, U> { + pub header: U, + /// The mapping that backs this NALU. Possibly shared with the other NALUs + /// in the Access Unit. + pub data: Cow<'a, [u8]>, + + pub size: usize, + pub offset: usize, +} + +impl<'a, U> Nalu<'a, U> +where + U: Debug + Header, +{ + /// Find the next Annex B encoded NAL unit. + pub fn next(cursor: &mut Cursor<&'a [u8]>) -> Result, String> { + let bitstream = cursor.clone().into_inner(); + let pos = usize::try_from(cursor.position()).map_err(|err| err.to_string())?; + + // Find the start code for this NALU + let current_nalu_offset = match Nalu::<'a, U>::find_start_code(cursor, pos) { + Some(offset) => offset, + None => return Err("No NAL found".into()), + }; + + let mut start_code_offset = pos + current_nalu_offset; + + // If the preceding byte is 00, then we actually have a four byte SC, + // i.e. 00 00 00 01 Where the first 00 is the "zero_byte()" + if start_code_offset > 0 && cursor.get_ref()[start_code_offset - 1] == 00 { + start_code_offset -= 1; + } + + // The NALU offset is its offset + 3 bytes to skip the start code. + let nalu_offset = pos + current_nalu_offset + 3; + + // Set the bitstream position to the start of the current NALU + cursor.set_position(u64::try_from(nalu_offset).map_err(|err| err.to_string())?); + + let hdr = U::parse(cursor)?; + + // Find the start of the subsequent NALU. + let mut next_nalu_offset = match Nalu::<'a, U>::find_start_code(cursor, nalu_offset) { + Some(offset) => offset, + None => { + let cur_pos = cursor.position(); + let end_pos = cursor.seek(SeekFrom::End(0)).map_err(|err| err.to_string())?; + let _ = cursor.seek(SeekFrom::Start(cur_pos)).map_err(|err| err.to_string())?; + (end_pos - cur_pos) as usize + } // Whatever data is left must be part of the current NALU + }; + + while next_nalu_offset > 0 && cursor.get_ref()[nalu_offset + next_nalu_offset - 1] == 00 { + // Discard trailing_zero_8bits + next_nalu_offset -= 1; + } + + let nal_size = if hdr.is_end() { + // the NALU is comprised of only the header + hdr.len() + } else { + next_nalu_offset + }; + + Ok(Nalu { + header: hdr, + data: Cow::from(&bitstream[start_code_offset..nalu_offset + nal_size]), + size: nal_size, + offset: nalu_offset - start_code_offset, + }) + } +} + +impl<'a, U> Nalu<'a, U> +where + U: Debug, +{ + fn find_start_code(data: &mut Cursor<&'a [u8]>, offset: usize) -> Option { + // discard all zeroes until the start code pattern is found + data.get_ref()[offset..].windows(3).position(|window| window == [0x00, 0x00, 0x01]) + } + + pub fn into_owned(self) -> Nalu<'static, U> { + Nalu { + header: self.header, + size: self.size, + offset: self.offset, + data: Cow::Owned(self.data.into_owned()), + } + } +} + +impl<'a, U> AsRef<[u8]> for Nalu<'a, U> { + fn as_ref(&self) -> &[u8] { + &self.data[self.offset..self.offset + self.size] + } +} diff --git a/vendor/cros-codecs/src/codec/h264/nalu_writer.rs b/vendor/cros-codecs/src/codec/h264/nalu_writer.rs new file mode 100644 index 0000000..90eaec6 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/nalu_writer.rs @@ -0,0 +1,299 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +use std::fmt; +use std::io::Write; + +use crate::bitstream_utils::BitWriter; +use crate::bitstream_utils::BitWriterError; + +/// Internal wrapper over [`std::io::Write`] for possible emulation prevention +struct EmulationPrevention { + out: W, + prev_bytes: [Option; 2], + + /// Emulation prevention enabled. + ep_enabled: bool, +} + +impl EmulationPrevention { + fn new(writer: W, ep_enabled: bool) -> Self { + Self { out: writer, prev_bytes: [None; 2], ep_enabled } + } + + fn write_byte(&mut self, curr_byte: u8) -> std::io::Result<()> { + if self.prev_bytes[1] == Some(0x00) && self.prev_bytes[0] == Some(0x00) && curr_byte <= 0x03 + { + self.out.write_all(&[0x00, 0x00, 0x03, curr_byte])?; + self.prev_bytes = [None; 2]; + } else { + if let Some(byte) = self.prev_bytes[1] { + self.out.write_all(&[byte])?; + } + + self.prev_bytes[1] = self.prev_bytes[0]; + self.prev_bytes[0] = Some(curr_byte); + } + + Ok(()) + } + + /// Writes a H.264 NALU header. + fn write_header(&mut self, idc: u8, type_: u8) -> NaluWriterResult<()> { + self.out.write_all(&[0x00, 0x00, 0x00, 0x01, (idc & 0b11) << 5 | (type_ & 0b11111)])?; + + Ok(()) + } + + fn has_data_pending(&self) -> bool { + self.prev_bytes[0].is_some() || self.prev_bytes[1].is_some() + } +} + +impl Write for EmulationPrevention { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if !self.ep_enabled { + self.out.write_all(buf)?; + return Ok(buf.len()); + } + + for byte in buf { + self.write_byte(*byte)?; + } + + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + if let Some(byte) = self.prev_bytes[1].take() { + self.out.write_all(&[byte])?; + } + + if let Some(byte) = self.prev_bytes[0].take() { + self.out.write_all(&[byte])?; + } + + self.out.flush() + } +} + +impl Drop for EmulationPrevention { + fn drop(&mut self) { + if let Err(e) = self.flush() { + log::error!("Unable to flush pending bytes {e:?}"); + } + } +} + +#[derive(Debug)] +pub enum NaluWriterError { + Overflow, + Io(std::io::Error), + BitWriterError(BitWriterError), +} + +impl fmt::Display for NaluWriterError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + NaluWriterError::Overflow => write!(f, "value increment caused value overflow"), + NaluWriterError::Io(x) => write!(f, "{}", x.to_string()), + NaluWriterError::BitWriterError(x) => write!(f, "{}", x.to_string()), + } + } +} + +impl From for NaluWriterError { + fn from(err: std::io::Error) -> Self { + NaluWriterError::Io(err) + } +} + +impl From for NaluWriterError { + fn from(err: BitWriterError) -> Self { + NaluWriterError::BitWriterError(err) + } +} + +pub type NaluWriterResult = std::result::Result; + +/// A writer for H.264 bitstream. It is capable of outputing bitstream with +/// emulation-prevention. +pub struct NaluWriter(BitWriter>); + +impl NaluWriter { + pub fn new(writer: W, ep_enabled: bool) -> Self { + Self(BitWriter::new(EmulationPrevention::new(writer, ep_enabled))) + } + + /// Writes fixed bit size integer (up to 32 bit) output with emulation + /// prevention if enabled. Corresponds to `f(n)` in H.264 spec. + pub fn write_f>(&mut self, bits: usize, value: T) -> NaluWriterResult { + self.0.write_f(bits, value).map_err(NaluWriterError::BitWriterError) + } + + /// An alias to [`Self::write_f`] Corresponds to `n(n)` in H.264 spec. + pub fn write_u>(&mut self, bits: usize, value: T) -> NaluWriterResult { + self.write_f(bits, value) + } + + /// Writes a number in exponential golumb format. + pub fn write_exp_golumb(&mut self, value: u32) -> NaluWriterResult<()> { + let value = value.checked_add(1).ok_or(NaluWriterError::Overflow)?; + let bits = 32 - value.leading_zeros() as usize; + let zeros = bits - 1; + + self.write_f(zeros, 0u32)?; + self.write_f(bits, value)?; + + Ok(()) + } + + /// Writes a unsigned integer in exponential golumb format. + /// Coresponds to `ue(v)` in H.264 spec. + pub fn write_ue>(&mut self, value: T) -> NaluWriterResult<()> { + let value = value.into(); + + self.write_exp_golumb(value) + } + + /// Writes a signed integer in exponential golumb format. + /// Coresponds to `se(v)` in H.264 spec. + pub fn write_se>(&mut self, value: T) -> NaluWriterResult<()> { + let value: i32 = value.into(); + let abs_value: u32 = value.unsigned_abs(); + + if value <= 0 { + self.write_ue(2 * abs_value) + } else { + self.write_ue(2 * abs_value - 1) + } + } + + /// Returns `true` if ['Self`] hold data that wasn't written to [`std::io::Write`] + pub fn has_data_pending(&self) -> bool { + self.0.has_data_pending() || self.0.inner().has_data_pending() + } + + /// Writes a H.264 NALU header. + pub fn write_header(&mut self, idc: u8, _type: u8) -> NaluWriterResult<()> { + self.0.flush()?; + self.0.inner_mut().write_header(idc, _type)?; + Ok(()) + } + + /// Returns `true` if next bits will be aligned to 8 + pub fn aligned(&self) -> bool { + !self.0.has_data_pending() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitstream_utils::BitReader; + + #[test] + fn simple_bits() { + let mut buf = Vec::::new(); + { + let mut writer = NaluWriter::new(&mut buf, false); + writer.write_f(1, true).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, false).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + writer.write_f(1, true).unwrap(); + } + assert_eq!(buf, vec![0b10001111u8]); + } + + #[test] + fn simple_first_few_ue() { + fn single_ue(value: u32) -> Vec { + let mut buf = Vec::::new(); + { + let mut writer = NaluWriter::new(&mut buf, false); + writer.write_ue(value).unwrap(); + } + buf + } + + assert_eq!(single_ue(0), vec![0b10000000u8]); + assert_eq!(single_ue(1), vec![0b01000000u8]); + assert_eq!(single_ue(2), vec![0b01100000u8]); + assert_eq!(single_ue(3), vec![0b00100000u8]); + assert_eq!(single_ue(4), vec![0b00101000u8]); + assert_eq!(single_ue(5), vec![0b00110000u8]); + assert_eq!(single_ue(6), vec![0b00111000u8]); + assert_eq!(single_ue(7), vec![0b00010000u8]); + assert_eq!(single_ue(8), vec![0b00010010u8]); + assert_eq!(single_ue(9), vec![0b00010100u8]); + } + + #[test] + fn writer_reader() { + let mut buf = Vec::::new(); + { + let mut writer = NaluWriter::new(&mut buf, false); + writer.write_ue(10u32).unwrap(); + writer.write_se(-42).unwrap(); + writer.write_se(3).unwrap(); + writer.write_ue(5u32).unwrap(); + } + + let mut reader = BitReader::new(&buf, true); + + assert_eq!(reader.read_ue::().unwrap(), 10); + assert_eq!(reader.read_se::().unwrap(), -42); + assert_eq!(reader.read_se::().unwrap(), 3); + assert_eq!(reader.read_ue::().unwrap(), 5); + + let mut buf = Vec::::new(); + { + let mut writer = NaluWriter::new(&mut buf, false); + writer.write_se(30).unwrap(); + writer.write_ue(100u32).unwrap(); + writer.write_se(-402).unwrap(); + writer.write_ue(50u32).unwrap(); + } + + let mut reader = BitReader::new(&buf, true); + + assert_eq!(reader.read_se::().unwrap(), 30); + assert_eq!(reader.read_ue::().unwrap(), 100); + assert_eq!(reader.read_se::().unwrap(), -402); + assert_eq!(reader.read_ue::().unwrap(), 50); + } + + #[test] + fn writer_emulation_prevention() { + fn test(input: &[u8], bitstream: &[u8]) { + let mut buf = Vec::::new(); + { + let mut writer = NaluWriter::new(&mut buf, true); + for byte in input { + writer.write_f(8, *byte).unwrap(); + } + } + assert_eq!(buf, bitstream); + { + let mut reader = BitReader::new(&buf, true); + for byte in input { + assert_eq!(*byte, reader.read_bits::(8).unwrap()); + } + } + } + + test(&[0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00]); + test(&[0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x01]); + test(&[0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x02]); + test(&[0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x03]); + + test(&[0x00, 0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00, 0x00]); + test(&[0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x01]); + test(&[0x00, 0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x00, 0x02]); + test(&[0x00, 0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x00, 0x03]); + } +} diff --git a/vendor/cros-codecs/src/codec/h264/parser.rs b/vendor/cros-codecs/src/codec/h264/parser.rs new file mode 100644 index 0000000..285242a --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/parser.rs @@ -0,0 +1,3023 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Can't reasonably expect client code to consume everything that has been parsed. +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::io::Cursor; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::rc::Rc; + +use crate::bitstream_utils::BitReader; +use crate::codec::h264::nalu; +use crate::codec::h264::nalu::Header; +use crate::codec::h264::picture::Field; + +pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>; + +pub(super) const DEFAULT_4X4_INTRA: [u8; 16] = + [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42]; + +pub(super) const DEFAULT_4X4_INTER: [u8; 16] = + [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34]; + +pub(super) const DEFAULT_8X8_INTRA: [u8; 64] = [ + 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, + 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, + 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42, +]; + +pub(super) const DEFAULT_8X8_INTER: [u8; 64] = [ + 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, + 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, + 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35, +]; + +const MAX_PPS_COUNT: u16 = 256; +const MAX_SPS_COUNT: u8 = 32; + +/// The maximum number of pictures in the DPB, as per A.3.1, clause h) +const DPB_MAX_SIZE: usize = 16; + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct Point { + pub x: T, + pub y: T, +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct Rect { + pub min: Point, + pub max: Point, +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum NaluType { + Unknown = 0, + Slice = 1, + SliceDpa = 2, + SliceDpb = 3, + SliceDpc = 4, + SliceIdr = 5, + Sei = 6, + Sps = 7, + Pps = 8, + AuDelimiter = 9, + SeqEnd = 10, + StreamEnd = 11, + FillerData = 12, + SpsExt = 13, + PrefixUnit = 14, + SubsetSps = 15, + DepthSps = 16, + SliceAux = 19, + SliceExt = 20, + SliceDepth = 21, +} + +impl TryFrom for NaluType { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(NaluType::Unknown), + 1 => Ok(NaluType::Slice), + 2 => Ok(NaluType::SliceDpa), + 3 => Ok(NaluType::SliceDpb), + 4 => Ok(NaluType::SliceDpc), + 5 => Ok(NaluType::SliceIdr), + 6 => Ok(NaluType::Sei), + 7 => Ok(NaluType::Sps), + 8 => Ok(NaluType::Pps), + 9 => Ok(NaluType::AuDelimiter), + 10 => Ok(NaluType::SeqEnd), + 11 => Ok(NaluType::StreamEnd), + 12 => Ok(NaluType::FillerData), + 13 => Ok(NaluType::SpsExt), + 14 => Ok(NaluType::PrefixUnit), + 15 => Ok(NaluType::SubsetSps), + 16 => Ok(NaluType::DepthSps), + 19 => Ok(NaluType::SliceAux), + 20 => Ok(NaluType::SliceExt), + 21 => Ok(NaluType::SliceDepth), + _ => Err(format!("Invalid NaluType {}", value)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RefPicListModification { + pub modification_of_pic_nums_idc: u8, + /* if modification_of_pic_nums_idc == 0 || 1 */ + pub abs_diff_pic_num_minus1: u32, + /* if modification_of_pic_nums_idc == 2 */ + pub long_term_pic_num: u32, + /* if modification_of_pic_nums_idc == 4 || 5 */ + pub abs_diff_view_idx_minus1: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PredWeightTable { + pub luma_log2_weight_denom: u8, + pub chroma_log2_weight_denom: u8, + + pub luma_weight_l0: [i16; 32], + pub luma_offset_l0: [i8; 32], + + /* if seq->ChromaArrayType != 0 */ + pub chroma_weight_l0: [[i16; 2]; 32], + pub chroma_offset_l0: [[i8; 2]; 32], + + /* if slice->slice_type % 5 == 1 */ + pub luma_weight_l1: [i16; 32], + pub luma_offset_l1: [i16; 32], + + /* and if seq->ChromaArrayType != 0 */ + pub chroma_weight_l1: [[i16; 2]; 32], + pub chroma_offset_l1: [[i8; 2]; 32], +} + +/// Representation of `MaxLongTermFrameIdx`. +/// +/// `MaxLongTermFrameIdx` is derived from `max_long_term_frame_idx_plus1`, an unsigned integer with +/// a special value indicating "no long-term frame indices". This type allows easy conversion +/// between the actual and "plus1" representation, while ensuring that the special value is always +/// handled by the code. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +pub enum MaxLongTermFrameIdx { + #[default] + NoLongTermFrameIndices, + Idx(u32), +} + +impl MaxLongTermFrameIdx { + /// Create a value from `max_long_term_frame_idx_plus1`. + pub fn from_value_plus1(max_long_term_frame_idx_plus1: u32) -> Self { + match max_long_term_frame_idx_plus1 { + 0 => Self::NoLongTermFrameIndices, + i @ 1.. => Self::Idx(i - 1), + } + } + + /// Convert this value to the representation used by `max_long_term_frame_idx_plus1`. + pub fn to_value_plus1(self) -> u32 { + match self { + Self::NoLongTermFrameIndices => 0, + Self::Idx(i) => i + 1, + } + } +} + +impl PartialEq for MaxLongTermFrameIdx { + fn eq(&self, other: &u32) -> bool { + match self { + MaxLongTermFrameIdx::NoLongTermFrameIndices => false, + MaxLongTermFrameIdx::Idx(idx) => idx.eq(other), + } + } +} + +impl PartialOrd for MaxLongTermFrameIdx { + fn partial_cmp(&self, other: &u32) -> Option { + match self { + MaxLongTermFrameIdx::NoLongTermFrameIndices => Some(std::cmp::Ordering::Less), + MaxLongTermFrameIdx::Idx(idx) => Some(idx.cmp(other)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RefPicMarkingInner { + /// Specifies a control operation to be applied to affect the reference + /// picture marking. The `memory_management_control_operation` syntax element + /// is followed by data necessary for the operation specified by the value + /// of `memory_management_control_operation`. The values and control + /// operations associated with `memory_management_control_operation` are + /// specified in Table 7-9 + pub memory_management_control_operation: u8, + + /// Used (with memory_management_control_operation equal to 3 or 1) to + /// assign a long-term frame index to a short-term reference picture or to + /// mark a short-term reference picture as "unused for reference". + pub difference_of_pic_nums_minus1: u32, + + /// Used (with memory_management_control_operation equal to 2) to mark a + /// long-term reference picture as "unused for reference". + pub long_term_pic_num: u32, + + /// Used (with memory_management_control_operation equal to 3 or 6) to + /// assign a long-term frame index to a picture. + pub long_term_frame_idx: u32, + + /// Specifies the maximum value of long-term frame index allowed for + /// long-term reference pictures (until receipt of another value of + /// `max_long_term_frame_idx_plus1`). + pub max_long_term_frame_idx: MaxLongTermFrameIdx, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RefPicMarking { + /// Specifies how the previously-decoded pictures in the decoded picture + /// buffer are treated after decoding of an IDR picture. See Annex C. + pub no_output_of_prior_pics_flag: bool, + + /// If unset, specifies that the MaxLongTermFrameIdx variable is set equal + /// to "no long-term frame indices" and that the IDR picture is marked as + /// "used for short-term reference". If set, specifies that the + /// MaxLongTermFrameIdx variable is set equal to 0 and that the current IDR + /// picture is marked "used for long-term reference" and is assigned + /// LongTermFrameIdx equal to 0. + pub long_term_reference_flag: bool, + + /// Selects the reference picture marking mode of the currently decoded + /// picture as specified in Table 7-8. + pub adaptive_ref_pic_marking_mode_flag: bool, + + /// An Vec with additional data used in the marking process. + pub inner: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SliceHeader { + /// Specifies the address of the first macroblock in the slice. + pub first_mb_in_slice: u32, + + /// Specifies the coding type of the slice according to Table 7-6. + pub slice_type: SliceType, + + // Specifies the picture parameter set in use + pub pic_parameter_set_id: u8, + + /// Specifies the colour plane associated with the current slice RBSP when + /// `separate_colour_plane_flag` is set. + pub colour_plane_id: u8, + + /// Used as an identifier for pictures and shall be represented by + /// `log2_max_frame_num_minus4 + 4` bits in the bitstream. + pub frame_num: u16, + + /// If set, specifies that the slice is a slice of a coded field. If not + /// set, specifies that the slice is a slice of a coded frame. + pub field_pic_flag: bool, + + /// If set, specifies that the slice is part of a coded bottom field. If not + /// set, specifies that the picture is a coded top field. + pub bottom_field_flag: bool, + + /// Identifies an IDR picture. The values of `idr_pic_id` in all the slices + /// of an IDR picture shall remain unchanged. When two consecutive access + /// units in decoding order are both IDR access units, the value of + /// `idr_pic_id` in the slices of the first such IDR access unit shall + /// differ from the `idr_pic_id` in the second such IDR access unit + pub idr_pic_id: u16, + + /// Specifies the picture order count modulo `MaxPicOrderCntLsb` for the top + /// field of a coded frame or for a coded field. The length of the + /// `pic_order_cnt_lsb` syntax element is + /// `log2_max_pic_order_cnt_lsb_minus4` + 4 bits. + pub pic_order_cnt_lsb: u16, + + /// Specifies the picture order count difference between the bottom field + /// and the top field of a coded frame as follows + pub delta_pic_order_cnt_bottom: i32, + + /// The first entry specifies the picture order count difference from the + /// expected picture order count for the top field of a coded frame or for a + /// coded field as specified in clause 8.2.1 The second entry specifies the + /// picture order count difference from the expected picture order count for + /// the bottom field of a coded frame specified in clause 8.2.1. + pub delta_pic_order_cnt: [i32; 2], + + /// This value is required by V4L2 stateless decode params so it is calculated + /// by parser while processing slice header. + pub pic_order_cnt_bit_size: usize, + + /// Shall be equal to 0 for slices and slice data partitions belonging to + /// the primary coded picture. The value of `redundant_pic_cnt shall` be + /// greater than 0 for coded slices or coded slice data partitions of a + /// redundant coded picture + pub redundant_pic_cnt: u8, + + /// Specifies the method used in the decoding process to derive motion + /// vectors and reference indices for inter prediction > + pub direct_spatial_mv_pred_flag: bool, + + /// If set, specifies that the syntax element `num_ref_idx_l0_active_minus1` + /// is present for P, SP, and B slices and that the syntax element + /// `num_ref_idx_l1_active_minus1` is present for B slices. If not set, + /// specifies that the syntax elements `num_ref_idx_l0_active_minus1` and + /// `num_ref_idx_l1_active_minus1` are not present. + pub num_ref_idx_active_override_flag: bool, + + /// Specifies the maximum reference index for reference picture list 0 that + /// shall be used to decode the slice. + pub num_ref_idx_l0_active_minus1: u8, + + /// Specifies the maximum reference index for reference picture list 1 that + /// shall be used to decode the slice. + pub num_ref_idx_l1_active_minus1: u8, + + /// If set, specifies that the syntax element `modification_of_pic_nums_idc` + /// is present for specifying reference picture list 0. If not set, + /// specifies that this syntax element is not present. + pub ref_pic_list_modification_flag_l0: bool, + + /// Reference picture list 0 modification as parsed with the + /// `ref_pic_list_modification()` process. + pub ref_pic_list_modification_l0: Vec, + + /// If set, specifies that the syntax element `modification_of_pic_nums_idc` + /// is present for specifying reference picture list 1. If not set, + /// specifies that this syntax element is not present. + pub ref_pic_list_modification_flag_l1: bool, + + /// Reference picture list 1 modification as parsed with the + /// `ref_pic_list_modification()` process. + pub ref_pic_list_modification_l1: Vec, + + /// Prediction weight table as parsed using 7.3.3.2 + pub pred_weight_table: PredWeightTable, + + /// Decoded reference picture marking parsed using 7.3.3.3 + pub dec_ref_pic_marking: RefPicMarking, + + /// This value is required by V4L2 stateless decode params so it is calculated + /// by parser while processing slice header. + pub dec_ref_pic_marking_bit_size: usize, + + /// Specifies the index for determining the initialization table used in the + /// initialization process for context variables. + pub cabac_init_idc: u8, + + /// Specifies the initial value of QP Y to be used for all the macroblocks + /// in the slice until modified by the value of `mb_qp_delta` in the + /// macroblock layer. The initial QPY quantization parameter for the slice + /// is computed using 7-30. + pub slice_qp_delta: i8, + + /// Specifies the decoding process to be used to decode P macroblocks in an + /// SP slice. + pub sp_for_switch_flag: bool, + + /// Specifies the value of QSY for all the macroblocks in SP and SI slices. + /// The QSY quantization parameter for the slice is computed using 7-31. + pub slice_qs_delta: i8, + + /// Specifies whether the operation of the deblocking filter shall be + /// disabled across some block edges of the slice and specifies for which + /// edges the filtering is disabled. + pub disable_deblocking_filter_idc: u8, + + /// Specifies the offset used in accessing the α and tC0 deblocking filter + /// tables for filtering operations controlled by the macroblocks within the + /// slice. From this value, the offset that shall be applied when addressing + /// these tables shall be computed using 7-32. + pub slice_alpha_c0_offset_div2: i8, + + /// Specifies the offset used in accessing the β deblocking filter table for + /// filtering operations controlled by the macroblocks within the slice. + /// From this value, the offset that is applied when addressing the β table + /// of the deblocking filter shall be computed using 7-33. + pub slice_beta_offset_div2: i8, + + /// Same as `MaxPicNum` in the specification. + pub max_pic_num: u32, + + /// Size of the slice_header() in bits + pub header_bit_size: usize, + + /// Number of emulation prevention bytes (EPB) in this slice_header() + pub n_emulation_prevention_bytes: usize, +} + +impl SliceHeader { + /// Returns the field that is coded by this header. + pub fn field(&self) -> Field { + if self.field_pic_flag { + if self.bottom_field_flag { + Field::Bottom + } else { + Field::Top + } + } else { + Field::Frame + } + } +} + +pub struct SliceHeaderBuilder(SliceHeader); + +impl SliceHeaderBuilder { + pub fn new(pps: &Pps) -> Self { + SliceHeaderBuilder(SliceHeader { + pic_parameter_set_id: pps.pic_parameter_set_id, + ..Default::default() + }) + } + + pub fn slice_type(mut self, type_: SliceType) -> Self { + self.0.slice_type = type_; + self + } + + pub fn first_mb_in_slice(mut self, value: u32) -> Self { + self.0.first_mb_in_slice = value; + self + } + + pub fn pic_order_cnt_lsb(mut self, value: u16) -> Self { + self.0.pic_order_cnt_lsb = value; + self + } + + pub fn idr_pic_id(mut self, value: u16) -> Self { + self.0.idr_pic_id = value; + self + } + + pub fn num_ref_idx_active_override_flag(mut self, value: bool) -> Self { + self.0.num_ref_idx_active_override_flag = value; + self + } + + pub fn num_ref_idx_l0_active_minus1(mut self, value: u8) -> Self { + self = self.num_ref_idx_active_override_flag(true); + self.0.num_ref_idx_l0_active_minus1 = value; + self + } + + pub fn num_ref_idx_l0_active(self, value: u8) -> Self { + self.num_ref_idx_l0_active_minus1(value - 1) + } + + pub fn num_ref_idx_l1_active_minus1(mut self, value: u8) -> Self { + self = self.num_ref_idx_active_override_flag(true); + self.0.num_ref_idx_l1_active_minus1 = value; + self + } + + pub fn num_ref_idx_l1_active(self, value: u8) -> Self { + self.num_ref_idx_l1_active_minus1(value - 1) + } + + pub fn build(self) -> SliceHeader { + self.0 + } +} + +/// A H264 slice. An integer number of macroblocks or macroblock pairs ordered +/// consecutively in the raster scan within a particular slice group +pub struct Slice<'a> { + /// The slice header. + pub header: SliceHeader, + /// The NAL unit backing this slice. + pub nalu: Nalu<'a>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// See table 7-6 in the specification. +pub enum SliceType { + P = 0, + B = 1, + I = 2, + Sp = 3, + Si = 4, +} + +impl TryFrom for SliceType { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(SliceType::P), + 1 => Ok(SliceType::B), + 2 => Ok(SliceType::I), + 3 => Ok(SliceType::Sp), + 4 => Ok(SliceType::Si), + _ => Err(format!("Invalid SliceType {}", value)), + } + } +} + +impl SliceType { + /// Whether this is a P slice. See table 7-6 in the specification. + pub fn is_p(&self) -> bool { + matches!(self, SliceType::P) + } + + /// Whether this is a B slice. See table 7-6 in the specification. + pub fn is_b(&self) -> bool { + matches!(self, SliceType::B) + } + + /// Whether this is an I slice. See table 7-6 in the specification. + pub fn is_i(&self) -> bool { + matches!(self, SliceType::I) + } + + /// Whether this is a SP slice. See table 7-6 in the specification. + pub fn is_sp(&self) -> bool { + matches!(self, SliceType::Sp) + } + + /// Whether this is a SI slice. See table 7-6 in the specification. + pub fn is_si(&self) -> bool { + matches!(self, SliceType::Si) + } +} + +impl Default for SliceType { + fn default() -> Self { + Self::P + } +} + +#[derive(Clone, Copy)] +#[repr(u8)] +pub enum Profile { + Baseline = 66, + Main = 77, + Extended = 88, + High = 100, + High10 = 110, + High422P = 122, +} + +impl TryFrom for Profile { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 66 => Ok(Profile::Baseline), + 77 => Ok(Profile::Main), + 88 => Ok(Profile::Extended), + 100 => Ok(Profile::High), + 110 => Ok(Profile::High10), + 122 => Ok(Profile::High422P), + _ => Err(format!("Invalid Profile {}", value)), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + #[default] + L1 = 10, + L1B = 9, + L1_1 = 11, + L1_2 = 12, + L1_3 = 13, + L2_0 = 20, + L2_1 = 21, + L2_2 = 22, + L3 = 30, + L3_1 = 31, + L3_2 = 32, + L4 = 40, + L4_1 = 41, + L4_2 = 42, + L5 = 50, + L5_1 = 51, + L5_2 = 52, + L6 = 60, + L6_1 = 61, + L6_2 = 62, +} + +impl TryFrom for Level { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 10 => Ok(Level::L1), + 9 => Ok(Level::L1B), + 11 => Ok(Level::L1_1), + 12 => Ok(Level::L1_2), + 13 => Ok(Level::L1_3), + 20 => Ok(Level::L2_0), + 21 => Ok(Level::L2_1), + 22 => Ok(Level::L2_2), + 30 => Ok(Level::L3), + 31 => Ok(Level::L3_1), + 32 => Ok(Level::L3_2), + 40 => Ok(Level::L4), + 41 => Ok(Level::L4_1), + 42 => Ok(Level::L4_2), + 50 => Ok(Level::L5), + 51 => Ok(Level::L5_1), + 52 => Ok(Level::L5_2), + 60 => Ok(Level::L6), + 61 => Ok(Level::L6_1), + 62 => Ok(Level::L6_2), + _ => Err(format!("Invalid Level {}", value)), + } + } +} + +/// A H264 Sequence Parameter Set. A syntax structure containing syntax elements +/// that apply to zero or more entire coded video sequences as determined by the +/// content of a seq_parameter_set_id syntax element found in the picture +/// parameter set referred to by the pic_parameter_set_id syntax element found +/// in each slice header. +#[derive(Debug, PartialEq, Eq)] +pub struct Sps { + /// Identifies the sequence parameter set that is referred to by the picture + /// parameter set + pub seq_parameter_set_id: u8, + + /// Profile to which the coded video sequence conforms + pub profile_idc: u8, + + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set0_flag: bool, + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set1_flag: bool, + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set2_flag: bool, + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set3_flag: bool, + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set4_flag: bool, + /// Retains the same meaning as in the specification. See 7.4.2.1.1 + pub constraint_set5_flag: bool, + + /// Level to which the coded video sequence conforms + pub level_idc: Level, + + /// Specifies the chroma sampling relative to the luma sampling as specified + /// in clause 6.2. + pub chroma_format_idc: u8, + + /// Specifies whether the three colour components of the 4:4:4 chroma format + /// are coded separately. + pub separate_colour_plane_flag: bool, + + /// Specifies the bit depth of the samples of the luma array and the value + /// of the luma quantization parameter range offset QpBdOffsetY. See 7-3 and + /// 7-4. + pub bit_depth_luma_minus8: u8, + + /// Specifies the bit depth of the samples of the chroma arrays and the + /// value of the chroma quantization parameter range offset QpBdOffsetC. See + /// 7-5 and 7-6. + pub bit_depth_chroma_minus8: u8, + + /// qpprime_y_zero_transform_bypass_flag equal to 1 specifies that, when + /// QP′Y is equal to 0, a transform bypass operation for the transform + /// coefficient decoding process and picture construction process prior to + /// deblocking filter process as specified in clause 8.5 shall be applied. + /// qpprime_y_zero_transform_bypass_flag equal to 0 specifies that the + /// transform coefficient decoding process and picture construction process + /// prior to deblocking filter process shall not use the transform bypass + /// operation + /// QP′Y is defined in 7-38 as QP′Y = QPY + QpBdOffsetY + pub qpprime_y_zero_transform_bypass_flag: bool, + + /// Whether `seq_scaling_list_present_flag[i]` for i = 0..7 or i = 0..11 is + /// present or whether the sequence level scaling list shall be specified by + /// Flat_4x4_16 for i = 0..5 and flat_8x8_16 for i = 6..11 + pub seq_scaling_matrix_present_flag: bool, + + /// 4x4 Scaling list as read with 7.3.2.1.1.1 + pub scaling_lists_4x4: [[u8; 16]; 6], + /// 8x8 Scaling list as read with 7.3.2.1.1.1 + pub scaling_lists_8x8: [[u8; 64]; 6], + + /// Specifies the value of the variable MaxFrameNum that is used in + /// frame_num related derivations as follows: MaxFrameNum = 2 ^ + /// (log2_max_frame_num_minus4 + 4 ) + pub log2_max_frame_num_minus4: u8, + + /// Specifies the method to decode picture order count (as specified in + /// clause 8.2.1) + pub pic_order_cnt_type: u8, + + /// Specifies the value of the variable MaxPicOrderCntLsb that is used in + /// the decoding process for picture order count as specified in clause + /// 8.2.1 as follows: MaxPicOrderCntLsb = 2 ^ ( + /// log2_max_pic_order_cnt_lsb_minus4 + 4 ). + pub log2_max_pic_order_cnt_lsb_minus4: u8, + + /// If true, specifies that `delta_pic_order_cnt[0]` and + /// `delta_pic_order_cnt[1]` are not present in the slice headers of the + /// sequence and shall be inferred to be equal to 0. + /// If false, specifies that `delta_pic_order_cnt[0]` is present in the + /// slice headers of the sequence and `delta_pic_order_cnt[1]` may be + /// present in the slice headers of the sequence. + pub delta_pic_order_always_zero_flag: bool, + + /// Used to calculate the picture order count of a non-reference picture as + /// specified in clause 8.2.1. + pub offset_for_non_ref_pic: i32, + + /// Used to calculate the picture order count of a bottom field as specified + /// in clause 8.2.1. + pub offset_for_top_to_bottom_field: i32, + + /// Used in the decoding process for picture order count as specified in + /// clause 8.2.1 + pub num_ref_frames_in_pic_order_cnt_cycle: u8, + + /// An element of a list of num_ref_frames_in_pic_order_cnt_cycle values + /// used in the decoding process for picture order count as specified in + /// clause 8.2. + pub offset_for_ref_frame: [i32; 255], + + /// Specifies the maximum number of short-term and long-term reference + /// frames, complementary reference field pairs, and non-paired reference + /// fields that may be used by the decoding process for inter prediction of + /// any picture in the coded video sequence. Also + /// determines the size of the sliding window operation as specified in + /// clause 8.2.5.3. + pub max_num_ref_frames: u8, + + /// Specifies the allowed values of frame_num as specified in clause 7.4.3 + /// and the decoding process in case of an inferred gap between values of + /// frame_num as specified in clause 8.2.5.2 + pub gaps_in_frame_num_value_allowed_flag: bool, + + /// Plus 1 specifies the width of each decoded picture in units of + /// macroblocks. + pub pic_width_in_mbs_minus1: u16, + /// Plus 1 specifies the height in slice group map units of a decoded frame + /// or field. + pub pic_height_in_map_units_minus1: u16, + + /// If true, specifies that every coded picture of the coded video sequence + /// is a coded frame containing only frame macroblocks, else specifies that + /// coded pictures of the coded video sequence may either be coded fields or + /// coded frames. + pub frame_mbs_only_flag: bool, + + /// If true, specifies the possible use of switching between frame and field + /// macroblocks within frames, else, specifies no switching between frame + /// and field macroblocks within a picture. + pub mb_adaptive_frame_field_flag: bool, + + /// Specifies the method used in the derivation process for luma motion + /// vectors for B_Skip, B_Direct_16x16 and B_Direct_8x8 as specified in + /// clause 8.4.1.2. + pub direct_8x8_inference_flag: bool, + + /// If true, specifies that the frame cropping offset parameters follow next + /// in the sequence parameter, else specifies that the frame cropping offset + /// parameters are not present + pub frame_cropping_flag: bool, + + /// Specify the samples of the pictures in the coded video sequence that are + /// output from the decoding process, in terms of a rectangular region + /// specified in frame coordinates for output. + pub frame_crop_left_offset: u32, + /// Specify the samples of the pictures in the coded video sequence that are + /// output from the decoding process, in terms of a rectangular region + /// specified in frame coordinates for output. + pub frame_crop_right_offset: u32, + /// Specify the samples of the pictures in the coded video sequence that are + /// output from the decoding process, in terms of a rectangular region + /// specified in frame coordinates for output. + pub frame_crop_top_offset: u32, + /// Specify the samples of the pictures in the coded video sequence that are + /// output from the decoding process, in terms of a rectangular region + /// specified in frame coordinates for output. + pub frame_crop_bottom_offset: u32, + + // Calculated + /// Same as ExpectedDeltaPerPicOrderCntCycle, see 7-12 in the specification. + pub expected_delta_per_pic_order_cnt_cycle: i32, + + pub vui_parameters_present_flag: bool, + pub vui_parameters: VuiParams, +} + +impl Sps { + /// Returns the coded width of the stream. + /// + /// See 7-13 through 7-17 in the specification. + pub const fn width(&self) -> u32 { + (self.pic_width_in_mbs_minus1 as u32 + 1) * 16 + } + + /// Returns the coded height of the stream. + /// + /// See 7-13 through 7-17 in the specification. + pub const fn height(&self) -> u32 { + (self.pic_height_in_map_units_minus1 as u32 + 1) + * 16 + * (2 - self.frame_mbs_only_flag as u32) + } + + /// Returns `ChromaArrayType`, as computed in the specification. + pub const fn chroma_array_type(&self) -> u8 { + match self.separate_colour_plane_flag { + false => self.chroma_format_idc, + true => 0, + } + } + + /// Returns `SubWidthC` and `SubHeightC`. + /// + /// See table 6-1 in the specification. + fn sub_width_height_c(&self) -> (u32, u32) { + match (self.chroma_format_idc, self.separate_colour_plane_flag) { + (1, false) => (2, 2), + (2, false) => (2, 1), + (3, false) => (1, 1), + // undefined. + _ => (1, 1), + } + } + + /// Returns `CropUnitX` and `CropUnitY`. + /// + /// See 7-19 through 7-22 in the specification. + fn crop_unit_x_y(&self) -> (u32, u32) { + match self.chroma_array_type() { + 0 => (1, 2 - u32::from(self.frame_mbs_only_flag)), + _ => { + let (sub_width_c, sub_height_c) = self.sub_width_height_c(); + (sub_width_c, sub_height_c * (2 - u32::from(self.frame_mbs_only_flag))) + } + } + } + + /// Same as MaxFrameNum. See 7-10 in the specification. + pub fn max_frame_num(&self) -> u32 { + 1 << (self.log2_max_frame_num_minus4 + 4) + } + + pub fn visible_rectangle(&self) -> Rect { + if !self.frame_cropping_flag { + return Rect { + min: Point { x: 0, y: 0 }, + max: Point { x: self.width(), y: self.height() }, + }; + } + + let (crop_unit_x, crop_unit_y) = self.crop_unit_x_y(); + + let crop_left = crop_unit_x * self.frame_crop_left_offset; + let crop_right = crop_unit_x * self.frame_crop_right_offset; + let crop_top = crop_unit_y * self.frame_crop_top_offset; + let crop_bottom = crop_unit_y * self.frame_crop_bottom_offset; + + Rect { + min: Point { x: crop_left, y: crop_top }, + max: Point { + x: self.width() - crop_left - crop_right, + y: self.height() - crop_top - crop_bottom, + }, + } + } + + pub fn max_dpb_frames(&self) -> usize { + let profile = self.profile_idc; + let mut level = self.level_idc; + + // A.3.1 and A.3.2: Level 1b for Baseline, Constrained Baseline and Main + // profile if level_idc == 11 and constraint_set3_flag == 1 + if matches!(level, Level::L1_1) + && (profile == Profile::Baseline as u8 || profile == Profile::Main as u8) + && self.constraint_set3_flag + { + level = Level::L1B; + }; + + // Table A.1 + let max_dpb_mbs = match level { + Level::L1 => 396, + Level::L1B => 396, + Level::L1_1 => 900, + Level::L1_2 => 2376, + Level::L1_3 => 2376, + Level::L2_0 => 2376, + Level::L2_1 => 4752, + Level::L2_2 => 8100, + Level::L3 => 8100, + Level::L3_1 => 18000, + Level::L3_2 => 20480, + Level::L4 => 32768, + Level::L4_1 => 32768, + Level::L4_2 => 34816, + Level::L5 => 110400, + Level::L5_1 => 184320, + Level::L5_2 => 184320, + Level::L6 => 696320, + Level::L6_1 => 696320, + Level::L6_2 => 696320, + }; + + let width_mb = self.width() / 16; + let height_mb = self.height() / 16; + + let max_dpb_frames = + std::cmp::min(max_dpb_mbs / (width_mb * height_mb), DPB_MAX_SIZE as u32) as usize; + + let mut max_dpb_frames = std::cmp::max(max_dpb_frames, self.max_num_ref_frames as usize); + + if self.vui_parameters_present_flag && self.vui_parameters.bitstream_restriction_flag { + max_dpb_frames = std::cmp::max(1, self.vui_parameters.max_dec_frame_buffering as usize); + } + + max_dpb_frames + } + + pub fn max_num_order_frames(&self) -> u32 { + let vui = &self.vui_parameters; + let present = self.vui_parameters_present_flag && vui.bitstream_restriction_flag; + + if present { + vui.max_num_reorder_frames + } else { + let profile = self.profile_idc; + if (profile == 44 + || profile == 86 + || profile == 100 + || profile == 110 + || profile == 122 + || profile == 244) + && self.constraint_set3_flag + { + 0 + } else { + self.max_dpb_frames() as u32 + } + } + } +} + +// TODO: Replace with builder +impl Default for Sps { + fn default() -> Self { + Self { + scaling_lists_4x4: [[0; 16]; 6], + scaling_lists_8x8: [[0; 64]; 6], + offset_for_ref_frame: [0; 255], + seq_parameter_set_id: Default::default(), + profile_idc: Default::default(), + constraint_set0_flag: Default::default(), + constraint_set1_flag: Default::default(), + constraint_set2_flag: Default::default(), + constraint_set3_flag: Default::default(), + constraint_set4_flag: Default::default(), + constraint_set5_flag: Default::default(), + level_idc: Default::default(), + chroma_format_idc: Default::default(), + separate_colour_plane_flag: Default::default(), + bit_depth_luma_minus8: Default::default(), + bit_depth_chroma_minus8: Default::default(), + qpprime_y_zero_transform_bypass_flag: Default::default(), + seq_scaling_matrix_present_flag: Default::default(), + log2_max_frame_num_minus4: Default::default(), + pic_order_cnt_type: Default::default(), + log2_max_pic_order_cnt_lsb_minus4: Default::default(), + delta_pic_order_always_zero_flag: Default::default(), + offset_for_non_ref_pic: Default::default(), + offset_for_top_to_bottom_field: Default::default(), + num_ref_frames_in_pic_order_cnt_cycle: Default::default(), + max_num_ref_frames: Default::default(), + gaps_in_frame_num_value_allowed_flag: Default::default(), + pic_width_in_mbs_minus1: Default::default(), + pic_height_in_map_units_minus1: Default::default(), + frame_mbs_only_flag: Default::default(), + mb_adaptive_frame_field_flag: Default::default(), + direct_8x8_inference_flag: Default::default(), + frame_cropping_flag: Default::default(), + frame_crop_left_offset: Default::default(), + frame_crop_right_offset: Default::default(), + frame_crop_top_offset: Default::default(), + frame_crop_bottom_offset: Default::default(), + expected_delta_per_pic_order_cnt_cycle: Default::default(), + vui_parameters_present_flag: Default::default(), + vui_parameters: Default::default(), + } + } +} + +#[derive(Default)] +pub struct SpsBuilder(Sps); + +impl SpsBuilder { + pub fn new() -> Self { + Default::default() + } + + pub fn seq_parameter_set_id(mut self, value: u8) -> Self { + self.0.seq_parameter_set_id = value; + self + } + + pub fn profile_idc(mut self, value: Profile) -> Self { + self.0.profile_idc = value as u8; + self + } + + pub fn level_idc(mut self, value: Level) -> Self { + self.0.level_idc = value; + self + } + + pub fn frame_crop_offsets(mut self, top: u32, bottom: u32, left: u32, right: u32) -> Self { + self.0.frame_cropping_flag = true; + self.0.frame_crop_top_offset = top; + self.0.frame_crop_bottom_offset = bottom; + self.0.frame_crop_left_offset = left; + self.0.frame_crop_right_offset = right; + self + } + + pub fn frame_crop(self, top: u32, bottom: u32, left: u32, right: u32) -> Self { + let sub_width_c = if self.0.chroma_format_idc > 2 { 1 } else { 2 }; + let sub_height_c = if self.0.chroma_format_idc > 1 { 1 } else { 2 }; + + let crop_unit_x = sub_width_c; + let crop_unit_y = sub_height_c * (if self.0.frame_mbs_only_flag { 1 } else { 2 }); + + self.frame_crop_offsets( + top / crop_unit_y, + bottom / crop_unit_y, + left / crop_unit_x, + right / crop_unit_x, + ) + } + + pub fn resolution(mut self, width: u32, height: u32) -> Self { + const MB_SIZE: u32 = 16; + + let mb_width = (width + MB_SIZE - 1) / MB_SIZE; + let mb_height = (height + MB_SIZE - 1) / MB_SIZE; + + self.0.pic_width_in_mbs_minus1 = (mb_width - 1) as u16; + self.0.pic_height_in_map_units_minus1 = (mb_height - 1) as u16; + + let compressed_width = mb_width * MB_SIZE; + let compressed_height = mb_height * MB_SIZE; + + if compressed_width != width || compressed_height != height { + self = self.frame_crop(0, compressed_height - height, 0, compressed_width - width); + } + + self + } + + pub fn chroma_format_idc(mut self, value: u8) -> Self { + self.0.chroma_format_idc = value; + self + } + + pub fn max_num_ref_frames(mut self, value: u8) -> Self { + self.0.max_num_ref_frames = value; + self + } + + pub fn frame_mbs_only_flag(mut self, value: bool) -> Self { + self.0.frame_mbs_only_flag = value; + self + } + + pub fn mb_adaptive_frame_field_flag(mut self, value: bool) -> Self { + self.0.mb_adaptive_frame_field_flag = value; + self + } + + pub fn seq_scaling_matrix_present_flag(mut self, value: bool) -> Self { + self.0.seq_scaling_matrix_present_flag = value; + self + } + + pub fn direct_8x8_inference_flag(mut self, value: bool) -> Self { + self.0.direct_8x8_inference_flag = value; + self + } + + pub fn vui_parameters_present(mut self) -> Self { + if self.0.vui_parameters_present_flag { + return self; + } + + self.0.vui_parameters_present_flag = true; + // Disable all options at default + self.0.vui_parameters.aspect_ratio_info_present_flag = false; + self.0.vui_parameters.overscan_info_present_flag = false; + self.0.vui_parameters.video_signal_type_present_flag = false; + self.0.vui_parameters.colour_description_present_flag = false; + self.0.vui_parameters.chroma_loc_info_present_flag = false; + self.0.vui_parameters.timing_info_present_flag = false; + self.0.vui_parameters.nal_hrd_parameters_present_flag = false; + self.0.vui_parameters.vcl_hrd_parameters_present_flag = false; + self.0.vui_parameters.pic_struct_present_flag = false; + self.0.vui_parameters.bitstream_restriction_flag = false; + self + } + + pub fn aspect_ratio_idc(mut self, value: u8) -> Self { + self = self.vui_parameters_present(); + self.0.vui_parameters.aspect_ratio_info_present_flag = true; + self.0.vui_parameters.aspect_ratio_idc = value; + self + } + + pub fn sar_resolution(mut self, width: u16, height: u16) -> Self { + self = self.aspect_ratio_idc(255); + self.0.vui_parameters.sar_width = width; + self.0.vui_parameters.sar_height = height; + self + } + + pub fn aspect_ratio(self, width_ratio: u16, height_ratio: u16) -> Self { + // H.264 Table E-1 + match (width_ratio, height_ratio) { + (1, 1) => self.aspect_ratio_idc(1), + (12, 11) => self.aspect_ratio_idc(2), + (10, 11) => self.aspect_ratio_idc(3), + (16, 11) => self.aspect_ratio_idc(4), + (40, 33) => self.aspect_ratio_idc(5), + (24, 11) => self.aspect_ratio_idc(6), + (20, 11) => self.aspect_ratio_idc(7), + (32, 11) => self.aspect_ratio_idc(8), + (80, 33) => self.aspect_ratio_idc(9), + (18, 11) => self.aspect_ratio_idc(10), + (15, 11) => self.aspect_ratio_idc(11), + (64, 33) => self.aspect_ratio_idc(12), + (160, 99) => self.aspect_ratio_idc(13), + (4, 3) => self.aspect_ratio_idc(14), + (3, 2) => self.aspect_ratio_idc(15), + (2, 1) => self.aspect_ratio_idc(16), + + _ => self.sar_resolution(width_ratio, height_ratio), + } + } + + pub fn timing_info( + mut self, + num_units_in_tick: u32, + time_scale: u32, + fixed_frame_rate_flag: bool, + ) -> Self { + self = self.vui_parameters_present(); + self.0.vui_parameters.timing_info_present_flag = true; + self.0.vui_parameters.num_units_in_tick = num_units_in_tick; + self.0.vui_parameters.time_scale = time_scale; + self.0.vui_parameters.fixed_frame_rate_flag = fixed_frame_rate_flag; + self + } + + pub fn log2_max_frame_num_minus4(mut self, value: u8) -> Self { + self.0.log2_max_frame_num_minus4 = value; + self + } + + pub fn max_frame_num(self, value: u32) -> Self { + self.log2_max_frame_num_minus4(value.ilog2() as u8 - 4u8) + } + + pub fn pic_order_cnt_type(mut self, value: u8) -> Self { + self.0.pic_order_cnt_type = value; + self + } + + pub fn log2_max_pic_order_cnt_lsb_minus4(mut self, value: u8) -> Self { + self.0.log2_max_pic_order_cnt_lsb_minus4 = value; + self + } + + pub fn max_pic_order_cnt_lsb(self, value: u32) -> Self { + self.log2_max_pic_order_cnt_lsb_minus4(value.ilog2() as u8 - 4u8) + } + + pub fn delta_pic_order_always_zero_flag(mut self, value: bool) -> Self { + self.0.delta_pic_order_always_zero_flag = value; + self + } + + pub fn bit_depth_chroma_minus8(mut self, value: u8) -> Self { + self.0.bit_depth_chroma_minus8 = value; + self + } + + pub fn bit_depth_chroma(self, value: u8) -> Self { + self.bit_depth_luma_minus8(value - 8u8) + } + + pub fn bit_depth_luma_minus8(mut self, value: u8) -> Self { + self.0.bit_depth_luma_minus8 = value; + self + } + + pub fn bit_depth_luma(self, value: u8) -> Self { + self.bit_depth_luma_minus8(value - 8u8) + } + + pub fn build(self) -> Rc { + Rc::new(self.0) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HrdParams { + /// Plus 1 specifies the number of alternative CPB specifications in the + /// bitstream. The value of `cpb_cnt_minus1` shall be in the range of 0 to 31, + /// inclusive + pub cpb_cnt_minus1: u8, + /// Together with `bit_rate_value_minus1[ SchedSelIdx ]` specifies the + /// maximum input bit rate of the `SchedSelIdx`-th CPB. + pub bit_rate_scale: u8, + /// Together with `cpb_size_value_minus1[ SchedSelIdx ]` specifies the CPB + /// size of the SchedSelIdx-th CPB. + pub cpb_size_scale: u8, + + /// `[ SchedSelIdx ]` (together with bit_rate_scale) specifies the maximum + /// input bit rate for the SchedSelIdx-th CPB. + pub bit_rate_value_minus1: [u32; 32], + /// `[ SchedSelIdx ]` is used together with cpb_size_scale to specify the + /// SchedSelIdx-th CPB size. + pub cpb_size_value_minus1: [u32; 32], + /// `[ SchedSelIdx ]` equal to 0 specifies that to decode this bitstream by + /// the HRD using the `SchedSelIdx`-th CPB specification, the hypothetical + /// stream delivery scheduler (HSS) operates in an intermittent bit rate + /// mode. `cbr_flag[ SchedSelIdx ]` equal to 1 specifies that the HSS operates + /// in a constant bit rate (CBR) mode + pub cbr_flag: [bool; 32], + + /// Specifies the length in bits of the `initial_cpb_removal_delay[ + /// SchedSelIdx ]` and `initial_cpb_removal_delay_offset[ SchedSelIdx ]` syntax + /// elements of the buffering period SEI message. + pub initial_cpb_removal_delay_length_minus1: u8, + /// Specifies the length in bits of the `cpb_removal_delay` syntax element. + pub cpb_removal_delay_length_minus1: u8, + /// Specifies the length in bits of the `dpb_output_delay` syntax element. + pub dpb_output_delay_length_minus1: u8, + /// If greater than 0, specifies the length in bits of the `time_offset` + /// syntax element. `time_offset_length` equal to 0 specifies that the + /// `time_offset` syntax element is not present + pub time_offset_length: u8, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VuiParams { + /// Specifies whether `aspect_ratio_idc` is present. + pub aspect_ratio_info_present_flag: bool, + /// Specifies the value of the sample aspect ratio of the luma samples. + /// Table E-1 shows the meaning of the code. When aspect_ratio_idc indicates + /// Extended_SAR, the sample aspect ratio is represented by sar_width : + /// sar_height. When the aspect_ratio_idc syntax element is not present, + /// aspect_ratio_idc value shall be inferred to be equal to 0 + pub aspect_ratio_idc: u8, + + /* if aspect_ratio_idc == 255 */ + /// Indicates the horizontal size of the sample aspect ratio (in arbitrary + /// units) + pub sar_width: u16, + /// Indicates the vertical size of the sample aspect ratio (in the same + /// arbitrary units as sar_width). + pub sar_height: u16, + + /// If true specifies that the overscan_appropriate_flag is present. Else, + /// the preferred display method for the video signal is unspecified + pub overscan_info_present_flag: bool, + /* if overscan_info_present_flag */ + /// If true, indicates that the cropped decoded pictures output are suitable + /// for display using overscan. Else, indicates that the cropped decoded + /// pictures output contain visually important information in the entire + /// region out to the edges of the cropping rectangle of the picture, such + /// that the cropped decoded pictures output should not be displayed using + /// overscan. + pub overscan_appropriate_flag: bool, + + /// Specifies that video_format, video_full_range_flag and + /// colour_description_present_flag are present + pub video_signal_type_present_flag: bool, + /// Indicates the representation of the pictures as specified in Table E-2, + /// before being coded in accordance with this Recommendation | + /// International Standard. When the video_format syntax element is not + /// present, video_format value shall be inferred to be equal to 5. + pub video_format: u8, + /// Indicates the black level and range of the luma and chroma signals as + /// derived from E′Y, E′PB, and E′PR or E′ R, E′G, and E′B real-valued + /// component signals. + pub video_full_range_flag: bool, + /// Specifies that colour_primaries, transfer_characteristics and + /// matrix_coefficients are present. + pub colour_description_present_flag: bool, + /// Indicates the chromaticity coordinates of the source primaries as + /// specified in Table E-3 in terms of the CIE 1931 definition of x and y as + /// specified by ISO 11664-1. + pub colour_primaries: u8, + /// Retains same meaning as in the specification. + pub transfer_characteristics: u8, + /// Describes the matrix coefficients used in deriving luma and chroma + /// signals from the green, blue, and red, or Y, Z, and X primaries, as + /// specified in Table E-5. + pub matrix_coefficients: u8, + + /// Specifies that chroma_sample_loc_type_top_field and + /// chroma_sample_loc_type_bottom_field are present + pub chroma_loc_info_present_flag: bool, + /// Specify the location of chroma samples. See the spec for more details. + pub chroma_sample_loc_type_top_field: u8, + /// Specify the location of chroma samples. See the spec for more details. + pub chroma_sample_loc_type_bottom_field: u8, + + /// Specifies that num_units_in_tick, time_scale and fixed_frame_rate_flag + /// are present in the bitstream + pub timing_info_present_flag: bool, + /* if timing_info_present_flag */ + /// The number of time units of a clock operating at the frequency + /// time_scale Hz that corresponds to one increment (called a clock tick) of + /// a clock tick counter + pub num_units_in_tick: u32, + /// The number of time units that pass in one second. For example, a time + /// coordinate system that measures time using a 27 MHz clock has a + /// time_scale of 27 000 000. time_scale shall be greater than 0. + pub time_scale: u32, + /// Retains the same meaning as the specification. + pub fixed_frame_rate_flag: bool, + + /// Specifies that NAL HRD parameters (pertaining to Type II bitstream + /// conformance) are present. + pub nal_hrd_parameters_present_flag: bool, + /* if nal_hrd_parameters_present_flag */ + /// The NAL HDR parameters + pub nal_hrd_parameters: HrdParams, + /// Specifies that VCL HRD parameters (pertaining to all bitstream + /// conformance) are present. + pub vcl_hrd_parameters_present_flag: bool, + /* if vcl_hrd_parameters_present_flag */ + /// The VCL HRD parameters + pub vcl_hrd_parameters: HrdParams, + + /// Specifies the HRD operational mode as specified in Annex C. + pub low_delay_hrd_flag: bool, + + /// Specifies that picture timing SEI messages (clause D.2.3) are present + /// that include the pic_struct syntax element. + pub pic_struct_present_flag: bool, + + /// Specifies that the following coded video sequence bitstream restriction + /// parameters are present + pub bitstream_restriction_flag: bool, + /* if bitstream_restriction_flag */ + /// If false, indicates that no sample outside the picture boundaries and no + /// sample at a fractional sample position for which the sample value is + /// derived using one or more samples outside the picture boundaries is used + /// for inter prediction of any sample. If true, indicates that one or more + /// samples outside picture boundaries may be used in inter prediction. When + /// the motion_vectors_over_pic_boundaries_flag syntax element is not + /// present, motion_vectors_over_pic_boundaries_flag value shall be inferred + /// to be true. + pub motion_vectors_over_pic_boundaries_flag: bool, + /// Indicates a number of bytes not exceeded by the sum of the sizes of the + /// VCL NAL units associated with any coded picture in the coded video + /// sequence. + pub max_bytes_per_pic_denom: u32, + /// Indicates an upper bound for the number of coded bits of + /// macroblock_layer( ) data for any macroblock in any picture of the coded + /// video sequence + pub max_bits_per_mb_denom: u32, + /// Retains the same meaning as the specification. + pub log2_max_mv_length_horizontal: u32, + /// Retains the same meaning as the specification. + pub log2_max_mv_length_vertical: u32, + /// Indicates an upper bound for the number of frames buffers, in the + /// decoded picture buffer (DPB), that are required for storing frames, + /// complementary field pairs, and non-paired fields before output. It is a + /// requirement of bitstream conformance that the maximum number of frames, + /// complementary field pairs, or non-paired fields that precede any frame, + /// complementary field pair, or non-paired field in the coded video + /// sequence in decoding order and follow it in output order shall be less + /// than or equal to max_num_reorder_frames. The value of + /// max_num_reorder_frames shall be in the range of 0 to + /// max_dec_frame_buffering, inclusive. + /// + /// When the max_num_reorder_frames syntax element is not present, the value + /// of max_num_reorder_frames value shall be inferred as follows: + /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and + /// constraint_set3_flag is equal to 1, the value of max_num_reorder_frames + /// shall be inferred to be equal to 0. + /// + /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or + /// constraint_set3_flag is equal to 0), the value of max_num_reorder_frames + /// shall be inferred to be equal to MaxDpbFrames. + pub max_num_reorder_frames: u32, + /// Specifies the required size of the HRD decoded picture buffer (DPB) in + /// units of frame buffers. It is a requirement of bitstream conformance + /// that the coded video sequence shall not require a decoded picture buffer + /// with size of more than Max( 1, max_dec_frame_buffering ) frame buffers + /// to enable the output of decoded pictures at the output times specified + /// by dpb_output_delay of the picture timing SEI messages. The value of + /// max_dec_frame_buffering shall be greater than or equal to + /// max_num_ref_frames. An upper bound for the value of + /// max_dec_frame_buffering is specified by the level limits in clauses + /// A.3.1, A.3.2, G.10.2.1, and H.10.2. + /// + /// When the max_dec_frame_buffering syntax element is not present, the + /// value of max_dec_frame_buffering shall be inferred as follows: + /// + /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and + /// constraint_set3_flag is equal to 1, the value of max_dec_frame_buffering + /// shall be inferred to be equal to 0. + /// + /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or + /// constraint_set3_flag is equal to 0), the value of + /// max_dec_frame_buffering shall be inferred to be equal to MaxDpbFrames. + pub max_dec_frame_buffering: u32, +} + +impl Default for VuiParams { + fn default() -> Self { + Self { + aspect_ratio_info_present_flag: Default::default(), + aspect_ratio_idc: Default::default(), + sar_width: Default::default(), + sar_height: Default::default(), + overscan_info_present_flag: Default::default(), + overscan_appropriate_flag: Default::default(), + video_signal_type_present_flag: Default::default(), + video_format: 5, + video_full_range_flag: Default::default(), + colour_description_present_flag: Default::default(), + colour_primaries: 2, + transfer_characteristics: 2, + matrix_coefficients: 2, + chroma_loc_info_present_flag: Default::default(), + chroma_sample_loc_type_top_field: Default::default(), + chroma_sample_loc_type_bottom_field: Default::default(), + timing_info_present_flag: Default::default(), + num_units_in_tick: Default::default(), + time_scale: Default::default(), + fixed_frame_rate_flag: Default::default(), + nal_hrd_parameters_present_flag: Default::default(), + nal_hrd_parameters: Default::default(), + vcl_hrd_parameters_present_flag: Default::default(), + vcl_hrd_parameters: Default::default(), + low_delay_hrd_flag: Default::default(), + pic_struct_present_flag: Default::default(), + bitstream_restriction_flag: Default::default(), + motion_vectors_over_pic_boundaries_flag: Default::default(), + max_bytes_per_pic_denom: Default::default(), + max_bits_per_mb_denom: Default::default(), + log2_max_mv_length_horizontal: Default::default(), + log2_max_mv_length_vertical: Default::default(), + max_num_reorder_frames: Default::default(), + max_dec_frame_buffering: Default::default(), + } + } +} + +/// A H264 Picture Parameter Set. A syntax structure containing syntax elements +/// that apply to zero or more entire coded pictures as determined by the +/// `pic_parameter_set_id` syntax element found in each slice header. +#[derive(Debug, PartialEq, Eq)] +pub struct Pps { + /// Identifies the picture parameter set that is referred to in the slice header. + pub pic_parameter_set_id: u8, + + /// Refers to the active sequence parameter set. + pub seq_parameter_set_id: u8, + + /// Selects the entropy decoding method to be applied for the syntax + /// elements for which two descriptors appear in the syntax tables as + /// follows: If `entropy_coding_mode_flag` is false, the method specified by + /// the left descriptor in the syntax table is applied (Exp-Golomb coded, + /// see clause 9.1 or CAVLC, see clause 9.2). Otherwise + /// (`entropy_coding_mode_flag` is true), the method specified by the right + /// descriptor in the syntax table is applied (CABAC, see clause 9.3). + pub entropy_coding_mode_flag: bool, + + /// If true, specifies that the syntax elements delta_pic_order_cnt_bottom + /// (when `pic_order_cnt_type` is equal to 0) or `delta_pic_order_cnt[1]` + /// (when `pic_order_cnt_type` is equal to 1), which are related to picture + /// order counts for the bottom field of a coded frame, are present in the + /// slice headers for coded frames as specified in clause 7.3.3. Otherwise, + /// specifies that the syntax elements `delta_pic_order_cnt_bottom` and + /// `delta_pic_order_cnt[1]` are not present in the slice headers. + pub bottom_field_pic_order_in_frame_present_flag: bool, + + /// Plus 1 specifies the number of slice groups for a picture. When + /// `num_slice_groups_minus1` is equal to 0, all slices of the picture + /// belong to the same slice group. The allowed range of + /// `num_slice_groups_minus1` is specified in Annex A. + pub num_slice_groups_minus1: u32, + + /// Specifies how `num_ref_idx_l0_active_minus1` is inferred for P, SP, and + /// B slices with `num_ref_idx_active_override_flag` not set. + pub num_ref_idx_l0_default_active_minus1: u8, + + /// Specifies how `num_ref_idx_l1_active_minus1` is inferred for B slices + /// with `num_ref_idx_active_override_flag` not set. + pub num_ref_idx_l1_default_active_minus1: u8, + + /// If not set, specifies that the default weighted prediction shall be + /// applied to P and SP slices. If set, specifies that explicit weighted + /// prediction shall be applied to P and SP slices. + pub weighted_pred_flag: bool, + + /// `weighted_bipred_idc` equal to 0 specifies that the default weighted + /// prediction shall be applied to B slices. `weighted_bipred_idc` equal to + /// 1 specifies that explicit weighted prediction shall be applied to B + /// slices. `weighted_bipred_idc` equal to 2 specifies that implicit + /// weighted prediction shall be applied to B slices + pub weighted_bipred_idc: u8, + + /// Specifies the initial value minus 26 of SliceQPY for each slice. The + /// initial value is modified at the slice layer when a non-zero value of + /// `slice_qp_delta` is decoded, and is modified further when a non-zero + /// value of `mb_qp_delta` is decoded at the macroblock layer. + pub pic_init_qp_minus26: i8, + + /// Specifies the initial value minus 26 of SliceQSY for all macroblocks in + /// SP or SI slices. The initial value is modified at the slice layer when a + /// non-zero value of `slice_qs_delta` is decoded. + pub pic_init_qs_minus26: i8, + + /// Specifies the offset that shall be added to QP Y and QSY for addressing + /// the table of QPC values for the Cb chroma component. + pub chroma_qp_index_offset: i8, + + /// If set, specifies that a set of syntax elements controlling the + /// characteristics of the deblocking filter is present in the slice header. + /// If not set, specifies that the set of syntax elements controlling the + /// characteristics of the deblocking filter is not present in the slice + /// headers and their inferred values are in effect. + pub deblocking_filter_control_present_flag: bool, + + /// If not set, specifies that intra prediction allows usage of residual + /// data and decoded samples of neighbouring macroblocks coded using Inter + /// macroblock prediction modes for the prediction of macroblocks coded + /// using Intra macroblock prediction modes. If set, specifies constrained + /// intra prediction, in which case prediction of macroblocks coded using + /// Intra macroblock prediction modes only uses residual data and decoded + /// samples from I or SI macroblock types. + pub constrained_intra_pred_flag: bool, + + /// If not set, specifies that the `redundant_pic_cnt` syntax element is not + /// present in slice headers, coded slice data partition B NAL units, and + /// coded slice data partition C NAL units that refer (either directly or by + /// association with a corresponding coded slice data partition A NAL unit) + /// to the picture parameter set. If set, specifies that the + /// `redundant_pic_cnt` syntax element is present in all slice headers, + /// coded slice data partition B NAL units, and coded slice data partition C + /// NAL units that refer (either directly or by association with a + /// corresponding coded slice data partition A NAL unit) to the picture + /// parameter set. + pub redundant_pic_cnt_present_flag: bool, + + /// If set, specifies that the 8x8 transform decoding process may be in use + /// (see clause 8.5). If not set, specifies that the 8x8 transform decoding + /// process is not in use. + pub transform_8x8_mode_flag: bool, + + /// If set, specifies that parameters are present to modify the scaling + /// lists specified in the sequence parameter set. If not set, specifies + /// that the scaling lists used for the picture shall be inferred to be + /// equal to those specified by the sequence parameter set. + pub pic_scaling_matrix_present_flag: bool, + + /// 4x4 Scaling list as read with 7.3.2.1.1.1 + pub scaling_lists_4x4: [[u8; 16]; 6], + /// 8x8 Scaling list as read with 7.3.2.1.1.1 + pub scaling_lists_8x8: [[u8; 64]; 6], + + /// Specifies the offset that shall be added to QPY and QSY for addressing + /// the table of QPC values for the Cr chroma component. When + /// `second_chroma_qp_index_offset` is not present, it shall be inferred to be + /// equal to `chroma_qp_index_offset`. + pub second_chroma_qp_index_offset: i8, + + /// The SPS referenced by this PPS. + pub sps: Rc, +} + +pub struct PpsBuilder(Pps); + +impl PpsBuilder { + pub fn new(sps: Rc) -> Self { + PpsBuilder(Pps { + pic_parameter_set_id: 0, + seq_parameter_set_id: sps.seq_parameter_set_id, + entropy_coding_mode_flag: false, + bottom_field_pic_order_in_frame_present_flag: false, + num_slice_groups_minus1: 0, + num_ref_idx_l0_default_active_minus1: 0, + num_ref_idx_l1_default_active_minus1: 0, + weighted_pred_flag: false, + weighted_bipred_idc: 0, + pic_init_qp_minus26: 0, + pic_init_qs_minus26: 0, + chroma_qp_index_offset: 0, + deblocking_filter_control_present_flag: false, + constrained_intra_pred_flag: false, + redundant_pic_cnt_present_flag: false, + transform_8x8_mode_flag: false, + pic_scaling_matrix_present_flag: false, + scaling_lists_4x4: [[0; 16]; 6], + scaling_lists_8x8: [[0; 64]; 6], + second_chroma_qp_index_offset: 0, + sps, + }) + } + + pub fn pic_parameter_set_id(mut self, value: u8) -> Self { + self.0.pic_parameter_set_id = value; + self + } + + pub fn pic_init_qp_minus26(mut self, value: i8) -> Self { + self.0.pic_init_qp_minus26 = value; + self + } + + pub fn pic_init_qp(self, value: u8) -> Self { + self.pic_init_qp_minus26(value as i8 - 26) + } + + pub fn deblocking_filter_control_present_flag(mut self, value: bool) -> Self { + self.0.deblocking_filter_control_present_flag = value; + self + } + + pub fn num_ref_idx_l0_default_active_minus1(mut self, value: u8) -> Self { + self.0.num_ref_idx_l0_default_active_minus1 = value; + self + } + + pub fn num_ref_idx_l0_default_active(self, value: u8) -> Self { + self.num_ref_idx_l0_default_active_minus1(value - 1) + } + + pub fn num_ref_idx_l1_default_active_minus1(mut self, value: u8) -> Self { + self.0.num_ref_idx_l1_default_active_minus1 = value; + self + } + + pub fn num_ref_idx_l1_default_active(self, value: u8) -> Self { + self.num_ref_idx_l1_default_active_minus1(value - 1) + } + + pub fn build(self) -> Rc { + Rc::new(self.0) + } +} + +#[derive(Debug, Default)] +pub struct Parser { + active_spses: BTreeMap>, + active_ppses: BTreeMap>, +} + +impl Parser { + fn fill_default_scaling_list_4x4(scaling_list4x4: &mut [u8; 16], i: usize) { + // See table 7.2 in the spec. + assert!(i < 6); + if i < 3 { + *scaling_list4x4 = DEFAULT_4X4_INTRA; + } else if i < 6 { + *scaling_list4x4 = DEFAULT_4X4_INTER; + } + } + + fn fill_default_scaling_list_8x8(scaling_list8x8: &mut [u8; 64], i: usize) { + assert!(i < 6); + if i % 2 == 0 { + *scaling_list8x8 = DEFAULT_8X8_INTRA; + } else { + *scaling_list8x8 = DEFAULT_8X8_INTER; + } + } + + fn fill_fallback_scaling_list_4x4( + scaling_list4x4: &mut [[u8; 16]; 6], + i: usize, + default_scaling_list_intra: &[u8; 16], + default_scaling_list_inter: &[u8; 16], + ) { + // See table 7.2 in the spec. + scaling_list4x4[i] = match i { + 0 => *default_scaling_list_intra, + 1 => scaling_list4x4[0], + 2 => scaling_list4x4[1], + 3 => *default_scaling_list_inter, + 4 => scaling_list4x4[3], + 5 => scaling_list4x4[4], + _ => panic!("Unexpected value {}", i), + } + } + + fn fill_fallback_scaling_list_8x8( + scaling_list8x8: &mut [[u8; 64]; 6], + i: usize, + default_scaling_list_intra: &[u8; 64], + default_scaling_list_inter: &[u8; 64], + ) { + // See table 7.2 in the spec. + scaling_list8x8[i] = match i { + 0 => *default_scaling_list_intra, + 1 => *default_scaling_list_inter, + 2 => scaling_list8x8[0], + 3 => scaling_list8x8[1], + 4 => scaling_list8x8[2], + 5 => scaling_list8x8[3], + _ => panic!("Unexpected value {}", i), + } + } + + fn fill_scaling_list_flat( + scaling_list4x4: &mut [[u8; 16]; 6], + scaling_list8x8: &mut [[u8; 64]; 6], + ) { + // (7-8) in the spec. + for outer in scaling_list4x4 { + for inner in outer { + *inner = 16; + } + } + + // (7-9) in the spec. + for outer in scaling_list8x8 { + for inner in outer { + *inner = 16; + } + } + } + + fn parse_scaling_list>( + r: &mut BitReader, + scaling_list: &mut U, + use_default: &mut bool, + ) -> Result<(), String> { + // 7.3.2.1.1.1 + let mut last_scale = 8u8; + let mut next_scale = 8u8; + + for j in 0..scaling_list.as_mut().len() { + if next_scale != 0 { + let delta_scale = r.read_se::()?; + next_scale = ((last_scale as i32 + delta_scale + 256) % 256) as u8; + *use_default = j == 0 && next_scale == 0; + if *use_default { + return Ok(()); + } + } + + scaling_list.as_mut()[j] = if next_scale == 0 { last_scale } else { next_scale }; + + last_scale = scaling_list.as_mut()[j]; + } + + Ok(()) + } + + fn parse_sps_scaling_lists(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> { + let scaling_lists4x4 = &mut sps.scaling_lists_4x4; + let scaling_lisst8x8 = &mut sps.scaling_lists_8x8; + + // Parse scaling_list4x4 + for i in 0..6 { + let seq_scaling_list_present_flag = r.read_bit()?; + if seq_scaling_list_present_flag { + let mut use_default = false; + + Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?; + + if use_default { + Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i); + } + } else { + Parser::fill_fallback_scaling_list_4x4( + scaling_lists4x4, + i, + &DEFAULT_4X4_INTRA, + &DEFAULT_4X4_INTER, + ); + } + } + + // Parse scaling_list8x8 + let num_8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 }; + for i in 0..num_8x8 { + let seq_scaling_list_present_flag = r.read_bit()?; + if seq_scaling_list_present_flag { + let mut use_default = false; + Parser::parse_scaling_list(r, &mut scaling_lisst8x8[i], &mut use_default)?; + + if use_default { + Parser::fill_default_scaling_list_8x8(&mut scaling_lisst8x8[i], i); + } + } else { + Parser::fill_fallback_scaling_list_8x8( + scaling_lisst8x8, + i, + &DEFAULT_8X8_INTRA, + &DEFAULT_8X8_INTER, + ); + } + } + Ok(()) + } + + fn parse_pps_scaling_lists(r: &mut BitReader, pps: &mut Pps, sps: &Sps) -> Result<(), String> { + let scaling_lists4x4 = &mut pps.scaling_lists_4x4; + let scaling_lists8x8 = &mut pps.scaling_lists_8x8; + + for i in 0..6 { + let pic_scaling_list_present_flag = r.read_bit()?; + if pic_scaling_list_present_flag { + let mut use_default = false; + + Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?; + + if use_default { + Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i); + } + } else if !sps.seq_scaling_matrix_present_flag { + // Table 7-2: Fallback rule A + Parser::fill_fallback_scaling_list_4x4( + scaling_lists4x4, + i, + &DEFAULT_4X4_INTRA, + &DEFAULT_4X4_INTER, + ); + } else { + // Table 7-2: Fallback rule B + Parser::fill_fallback_scaling_list_4x4( + scaling_lists4x4, + i, + &sps.scaling_lists_4x4[0], + &sps.scaling_lists_4x4[3], + ); + } + } + + if pps.transform_8x8_mode_flag { + let num8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 }; + + for i in 0..num8x8 { + let pic_scaling_list_present_flag = r.read_bit()?; + if pic_scaling_list_present_flag { + let mut use_default = false; + + Parser::parse_scaling_list(r, &mut scaling_lists8x8[i], &mut use_default)?; + + if use_default { + Parser::fill_default_scaling_list_8x8(&mut scaling_lists8x8[i], i); + } + } else if !sps.seq_scaling_matrix_present_flag { + // Table 7-2: Fallback rule A + Parser::fill_fallback_scaling_list_8x8( + scaling_lists8x8, + i, + &DEFAULT_8X8_INTRA, + &DEFAULT_8X8_INTER, + ); + } else { + // Table 7-2: Fallback rule B + Parser::fill_fallback_scaling_list_8x8( + scaling_lists8x8, + i, + &sps.scaling_lists_8x8[0], + &sps.scaling_lists_8x8[1], + ); + } + } + } + + Ok(()) + } + + fn parse_hrd(r: &mut BitReader, hrd: &mut HrdParams) -> Result<(), String> { + hrd.cpb_cnt_minus1 = r.read_ue_max(31)?; + hrd.bit_rate_scale = r.read_bits(4)?; + hrd.cpb_size_scale = r.read_bits(4)?; + + for sched_sel_idx in 0..=usize::from(hrd.cpb_cnt_minus1) { + hrd.bit_rate_value_minus1[sched_sel_idx] = r.read_ue()?; + hrd.cpb_size_value_minus1[sched_sel_idx] = r.read_ue()?; + hrd.cbr_flag[sched_sel_idx] = r.read_bit()?; + } + + hrd.initial_cpb_removal_delay_length_minus1 = r.read_bits(5)?; + hrd.cpb_removal_delay_length_minus1 = r.read_bits(5)?; + hrd.dpb_output_delay_length_minus1 = r.read_bits(5)?; + hrd.time_offset_length = r.read_bits(5)?; + Ok(()) + } + + fn parse_vui(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> { + let vui = &mut sps.vui_parameters; + + vui.aspect_ratio_info_present_flag = r.read_bit()?; + if vui.aspect_ratio_info_present_flag { + vui.aspect_ratio_idc = r.read_bits(8)?; + if vui.aspect_ratio_idc == 255 { + vui.sar_width = r.read_bits(16)?; + vui.sar_height = r.read_bits(16)?; + } + } + + vui.overscan_info_present_flag = r.read_bit()?; + if vui.overscan_info_present_flag { + vui.overscan_appropriate_flag = r.read_bit()?; + } + + vui.video_signal_type_present_flag = r.read_bit()?; + if vui.video_signal_type_present_flag { + vui.video_format = r.read_bits(3)?; + vui.video_full_range_flag = r.read_bit()?; + vui.colour_description_present_flag = r.read_bit()?; + if vui.colour_description_present_flag { + vui.colour_primaries = r.read_bits(8)?; + vui.transfer_characteristics = r.read_bits(8)?; + vui.matrix_coefficients = r.read_bits(8)?; + } + } + + vui.chroma_loc_info_present_flag = r.read_bit()?; + if vui.chroma_loc_info_present_flag { + vui.chroma_sample_loc_type_top_field = r.read_ue_max(5)?; + vui.chroma_sample_loc_type_bottom_field = r.read_ue_max(5)?; + } + + vui.timing_info_present_flag = r.read_bit()?; + if vui.timing_info_present_flag { + vui.num_units_in_tick = r.read_bits::(31)? << 1; + vui.num_units_in_tick |= r.read_bit()? as u32; + if vui.num_units_in_tick == 0 { + return Err("num_units_in_tick == 0, which is not allowed by E.2.1".into()); + } + + vui.time_scale = r.read_bits::(31)? << 1; + vui.time_scale |= r.read_bit()? as u32; + if vui.time_scale == 0 { + return Err("time_scale == 0, which is not allowed by E.2.1".into()); + } + + vui.fixed_frame_rate_flag = r.read_bit()?; + } + + vui.nal_hrd_parameters_present_flag = r.read_bit()?; + if vui.nal_hrd_parameters_present_flag { + Parser::parse_hrd(r, &mut vui.nal_hrd_parameters)?; + } + + vui.vcl_hrd_parameters_present_flag = r.read_bit()?; + if vui.vcl_hrd_parameters_present_flag { + Parser::parse_hrd(r, &mut vui.vcl_hrd_parameters)?; + } + + if vui.nal_hrd_parameters_present_flag || vui.vcl_hrd_parameters_present_flag { + vui.low_delay_hrd_flag = r.read_bit()?; + } + + vui.pic_struct_present_flag = r.read_bit()?; + vui.bitstream_restriction_flag = r.read_bit()?; + + if vui.bitstream_restriction_flag { + vui.motion_vectors_over_pic_boundaries_flag = r.read_bit()?; + vui.max_bytes_per_pic_denom = r.read_ue()?; + vui.max_bits_per_mb_denom = r.read_ue_max(16)?; + vui.log2_max_mv_length_horizontal = r.read_ue_max(16)?; + vui.log2_max_mv_length_vertical = r.read_ue_max(16)?; + vui.max_num_reorder_frames = r.read_ue()?; + vui.max_dec_frame_buffering = r.read_ue()?; + } + + Ok(()) + } + + /// Parse a SPS and add it to the list of active SPSes. + /// + /// Returns a reference to the new SPS. + pub fn parse_sps(&mut self, nalu: &Nalu) -> Result<&Rc, String> { + if !matches!(nalu.header.type_, NaluType::Sps) { + return Err(format!( + "Invalid NALU type, expected {:?}, got {:?}", + NaluType::Sps, + nalu.header.type_ + )); + } + + let data = nalu.as_ref(); + // Skip the header + let mut r = BitReader::new(&data[nalu.header.len()..], true); + let mut sps = Sps { + profile_idc: r.read_bits(8)?, + constraint_set0_flag: r.read_bit()?, + constraint_set1_flag: r.read_bit()?, + constraint_set2_flag: r.read_bit()?, + constraint_set3_flag: r.read_bit()?, + constraint_set4_flag: r.read_bit()?, + constraint_set5_flag: r.read_bit()?, + ..Default::default() + }; + + // skip reserved_zero_2bits + r.skip_bits(2)?; + + let level: u8 = r.read_bits(8)?; + sps.level_idc = Level::try_from(level)?; + sps.seq_parameter_set_id = r.read_ue_max(31)?; + + if sps.profile_idc == 100 + || sps.profile_idc == 110 + || sps.profile_idc == 122 + || sps.profile_idc == 244 + || sps.profile_idc == 44 + || sps.profile_idc == 83 + || sps.profile_idc == 86 + || sps.profile_idc == 118 + || sps.profile_idc == 128 + || sps.profile_idc == 138 + || sps.profile_idc == 139 + || sps.profile_idc == 134 + || sps.profile_idc == 135 + { + sps.chroma_format_idc = r.read_ue_max(3)?; + if sps.chroma_format_idc == 3 { + sps.separate_colour_plane_flag = r.read_bit()?; + } + + sps.bit_depth_luma_minus8 = r.read_ue_max(6)?; + sps.bit_depth_chroma_minus8 = r.read_ue_max(6)?; + sps.qpprime_y_zero_transform_bypass_flag = r.read_bit()?; + sps.seq_scaling_matrix_present_flag = r.read_bit()?; + + if sps.seq_scaling_matrix_present_flag { + Parser::parse_sps_scaling_lists(&mut r, &mut sps)?; + } else { + Parser::fill_scaling_list_flat( + &mut sps.scaling_lists_4x4, + &mut sps.scaling_lists_8x8, + ); + } + } else { + sps.chroma_format_idc = 1; + Parser::fill_scaling_list_flat(&mut sps.scaling_lists_4x4, &mut sps.scaling_lists_8x8); + } + + sps.log2_max_frame_num_minus4 = r.read_ue_max(12)?; + + sps.pic_order_cnt_type = r.read_ue_max(2)?; + + if sps.pic_order_cnt_type == 0 { + sps.log2_max_pic_order_cnt_lsb_minus4 = r.read_ue_max(12)?; + sps.expected_delta_per_pic_order_cnt_cycle = 0; + } else if sps.pic_order_cnt_type == 1 { + sps.delta_pic_order_always_zero_flag = r.read_bit()?; + sps.offset_for_non_ref_pic = r.read_se()?; + sps.offset_for_top_to_bottom_field = r.read_se()?; + sps.num_ref_frames_in_pic_order_cnt_cycle = r.read_ue_max(254)?; + + let mut offset_acc = 0; + for i in 0..usize::from(sps.num_ref_frames_in_pic_order_cnt_cycle) { + sps.offset_for_ref_frame[i] = r.read_se()?; + + // (7-12) in the spec. + offset_acc += sps.offset_for_ref_frame[i]; + } + + sps.expected_delta_per_pic_order_cnt_cycle = offset_acc; + } + + sps.max_num_ref_frames = r.read_ue_max(DPB_MAX_SIZE as u32)?; + sps.gaps_in_frame_num_value_allowed_flag = r.read_bit()?; + sps.pic_width_in_mbs_minus1 = r.read_ue()?; + sps.pic_height_in_map_units_minus1 = r.read_ue()?; + sps.frame_mbs_only_flag = r.read_bit()?; + + if !sps.frame_mbs_only_flag { + sps.mb_adaptive_frame_field_flag = r.read_bit()?; + } + + sps.direct_8x8_inference_flag = r.read_bit()?; + sps.frame_cropping_flag = r.read_bit()?; + + if sps.frame_cropping_flag { + sps.frame_crop_left_offset = r.read_ue()?; + sps.frame_crop_right_offset = r.read_ue()?; + sps.frame_crop_top_offset = r.read_ue()?; + sps.frame_crop_bottom_offset = r.read_ue()?; + + // Validate that cropping info is valid. + let (crop_unit_x, crop_unit_y) = sps.crop_unit_x_y(); + + let _ = sps + .frame_crop_left_offset + .checked_add(sps.frame_crop_right_offset) + .and_then(|r| r.checked_mul(crop_unit_x)) + .and_then(|r| sps.width().checked_sub(r)) + .ok_or::("Invalid frame crop width".into())?; + + let _ = sps + .frame_crop_top_offset + .checked_add(sps.frame_crop_bottom_offset) + .and_then(|r| r.checked_mul(crop_unit_y)) + .and_then(|r| sps.height().checked_sub(r)) + .ok_or::("invalid frame crop height".into())?; + } + + sps.vui_parameters_present_flag = r.read_bit()?; + if sps.vui_parameters_present_flag { + Parser::parse_vui(&mut r, &mut sps)?; + } + + let key = sps.seq_parameter_set_id; + + if self.active_spses.keys().len() >= MAX_SPS_COUNT as usize { + return Err("Broken data: Number of active SPSs > MAX_SPS_COUNT".into()); + } + + let sps = Rc::new(sps); + self.active_spses.remove(&key); + Ok(self.active_spses.entry(key).or_insert(sps)) + } + + pub fn parse_pps(&mut self, nalu: &Nalu) -> Result<&Pps, String> { + if !matches!(nalu.header.type_, NaluType::Pps) { + return Err(format!( + "Invalid NALU type, expected {:?}, got {:?}", + NaluType::Pps, + nalu.header.type_ + )); + } + + let data = nalu.as_ref(); + // Skip the header + let mut r = BitReader::new(&data[nalu.header.len()..], true); + let pic_parameter_set_id = r.read_ue_max(MAX_PPS_COUNT as u32 - 1)?; + let seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?; + let sps = self.get_sps(seq_parameter_set_id).ok_or::(format!( + "Could not get SPS for seq_parameter_set_id {}", + seq_parameter_set_id + ))?; + let mut pps = Pps { + pic_parameter_set_id, + seq_parameter_set_id, + sps: Rc::clone(sps), + scaling_lists_4x4: [[0; 16]; 6], + scaling_lists_8x8: [[0; 64]; 6], + entropy_coding_mode_flag: Default::default(), + bottom_field_pic_order_in_frame_present_flag: Default::default(), + num_slice_groups_minus1: Default::default(), + num_ref_idx_l0_default_active_minus1: Default::default(), + num_ref_idx_l1_default_active_minus1: Default::default(), + weighted_pred_flag: Default::default(), + weighted_bipred_idc: Default::default(), + pic_init_qp_minus26: Default::default(), + pic_init_qs_minus26: Default::default(), + chroma_qp_index_offset: Default::default(), + deblocking_filter_control_present_flag: Default::default(), + constrained_intra_pred_flag: Default::default(), + redundant_pic_cnt_present_flag: Default::default(), + transform_8x8_mode_flag: Default::default(), + second_chroma_qp_index_offset: Default::default(), + pic_scaling_matrix_present_flag: Default::default(), + }; + + pps.entropy_coding_mode_flag = r.read_bit()?; + pps.bottom_field_pic_order_in_frame_present_flag = r.read_bit()?; + pps.num_slice_groups_minus1 = r.read_ue_max(7)?; + + if pps.num_slice_groups_minus1 > 0 { + return Err("Stream contain unsupported/unimplemented NALs".into()); + } + + pps.num_ref_idx_l0_default_active_minus1 = r.read_ue_max(31)?; + pps.num_ref_idx_l1_default_active_minus1 = r.read_ue_max(31)?; + + pps.weighted_pred_flag = r.read_bit()?; + pps.weighted_bipred_idc = r.read_bits(2)?; + + let qp_bd_offset_y = i32::from(6 * (sps.bit_depth_luma_minus8)); + pps.pic_init_qp_minus26 = r.read_se_bounded(-(26 + qp_bd_offset_y), 25)?; + pps.pic_init_qs_minus26 = r.read_se_bounded(-26, 25)?; + + pps.chroma_qp_index_offset = r.read_se_bounded(-12, 12)?; + + // When second_chroma_qp_index_offset is not present, it shall be + // inferred to be equal to chroma_qp_index_offset. + pps.second_chroma_qp_index_offset = pps.chroma_qp_index_offset; + + pps.deblocking_filter_control_present_flag = r.read_bit()?; + pps.constrained_intra_pred_flag = r.read_bit()?; + pps.redundant_pic_cnt_present_flag = r.read_bit()?; + + if r.has_more_rsbp_data() { + pps.transform_8x8_mode_flag = r.read_bit()?; + pps.pic_scaling_matrix_present_flag = r.read_bit()?; + + if pps.pic_scaling_matrix_present_flag { + Parser::parse_pps_scaling_lists(&mut r, &mut pps, sps)?; + } + + pps.second_chroma_qp_index_offset = r.read_se()?; + } + + if !pps.pic_scaling_matrix_present_flag { + // If not set, specifies that the scaling lists used for the picture + // shall be inferred to be equal to those specified by the sequence + // parameter set. When pic_scaling_matrix_present_flag is not + // present, it shall be inferred to be not set. + pps.scaling_lists_4x4 = sps.scaling_lists_4x4; + pps.scaling_lists_8x8 = sps.scaling_lists_8x8; + } + + let key = pps.pic_parameter_set_id; + + if self.active_ppses.keys().len() >= MAX_PPS_COUNT as usize { + return Err("Broken Data: number of active PPSs > MAX_PPS_COUNT".into()); + } + + let pps = Rc::new(pps); + self.active_ppses.remove(&key); + Ok(self.active_ppses.entry(key).or_insert(pps)) + } + + fn parse_ref_pic_list_modification( + r: &mut BitReader, + num_ref_idx_active_minus1: u8, + ref_list_mods: &mut Vec, + ) -> Result<(), String> { + if num_ref_idx_active_minus1 >= 32 { + return Err("Broken Data: num_ref_idx_active_minus1 >= 32".into()); + } + + loop { + let mut pic_num_mod = RefPicListModification { + modification_of_pic_nums_idc: r.read_ue_max(3)?, + ..Default::default() + }; + + match pic_num_mod.modification_of_pic_nums_idc { + 0 | 1 => { + pic_num_mod.abs_diff_pic_num_minus1 = r.read_ue()?; + } + + 2 => { + pic_num_mod.long_term_pic_num = r.read_ue()?; + } + + 3 => { + ref_list_mods.push(pic_num_mod); + break; + } + + _ => return Err("Broken Data: modification_of_pic_nums_idc > 3".into()), + } + + ref_list_mods.push(pic_num_mod); + } + + Ok(()) + } + + fn parse_ref_pic_list_modifications( + r: &mut BitReader, + header: &mut SliceHeader, + ) -> Result<(), String> { + if !header.slice_type.is_i() && !header.slice_type.is_si() { + header.ref_pic_list_modification_flag_l0 = r.read_bit()?; + if header.ref_pic_list_modification_flag_l0 { + Parser::parse_ref_pic_list_modification( + r, + header.num_ref_idx_l0_active_minus1, + &mut header.ref_pic_list_modification_l0, + )?; + } + } + + if header.slice_type.is_b() { + header.ref_pic_list_modification_flag_l1 = r.read_bit()?; + if header.ref_pic_list_modification_flag_l1 { + Parser::parse_ref_pic_list_modification( + r, + header.num_ref_idx_l1_active_minus1, + &mut header.ref_pic_list_modification_l1, + )?; + } + } + + Ok(()) + } + + fn parse_pred_weight_table( + r: &mut BitReader, + sps: &Sps, + header: &mut SliceHeader, + ) -> Result<(), String> { + let pt = &mut header.pred_weight_table; + pt.luma_log2_weight_denom = r.read_ue_max(7)?; + + // When luma_weight_l0_flag is equal to 0, luma_weight_l0[i] shall be + // inferred to be equal to 2 ^ luma_log2_weight_denom for + // RefPicList0[i]. + let default_luma_weight = 1 << pt.luma_log2_weight_denom; + for i in 0..=header.num_ref_idx_l0_active_minus1 { + pt.luma_weight_l0[usize::from(i)] = default_luma_weight; + } + + // When luma_weight_l1_flag is equal to 1, luma_weight_l1[i] shall be + // inferred to be equal to 2 ^ luma_log2_weight_denom for + // RefPicList1[i]. + if header.slice_type.is_b() { + for i in 0..=header.num_ref_idx_l1_active_minus1 { + pt.luma_weight_l1[usize::from(i)] = default_luma_weight; + } + } + + if sps.chroma_array_type() != 0 { + pt.chroma_log2_weight_denom = r.read_ue_max(7)?; + let default_chroma_weight = 1 << pt.chroma_log2_weight_denom; + + // When chroma_weight_l0_flag is equal to 0, chroma_weight_l0[i] + // shall be inferred to be equal to 2 ^ chroma_log2_weight_denom for + // RefPicList0[i]. + for i in 0..=header.num_ref_idx_l0_active_minus1 { + pt.chroma_weight_l0[usize::from(i)][0] = default_chroma_weight; + pt.chroma_weight_l0[usize::from(i)][1] = default_chroma_weight; + } + + // When chroma_weight_l1_flag is equal to 0, chroma_weight_l1[i] + // shall be inferred to be equal to 2 ^ chroma_log2_weight_denom for + // RefPicList1[i]. + for i in 0..=header.num_ref_idx_l1_active_minus1 { + pt.chroma_weight_l1[usize::from(i)][0] = default_chroma_weight; + pt.chroma_weight_l1[usize::from(i)][1] = default_chroma_weight; + } + } + + for i in 0..=header.num_ref_idx_l0_active_minus1 { + let luma_weight_l0_flag = r.read_bit()?; + + if luma_weight_l0_flag { + pt.luma_weight_l0[usize::from(i)] = r.read_se_bounded(-128, 127)?; + pt.luma_offset_l0[usize::from(i)] = r.read_se_bounded(-128, 127)?; + } + + if sps.chroma_array_type() != 0 { + let chroma_weight_l0_flag = r.read_bit()?; + if chroma_weight_l0_flag { + for j in 0..2 { + pt.chroma_weight_l0[usize::from(i)][j] = r.read_se_bounded(-128, 127)?; + pt.chroma_offset_l0[usize::from(i)][j] = r.read_se_bounded(-128, 127)?; + } + } + } + } + + if header.slice_type.is_b() { + for i in 0..=header.num_ref_idx_l1_active_minus1 { + let luma_weight_l1_flag = r.read_bit()?; + + if luma_weight_l1_flag { + pt.luma_weight_l1[usize::from(i)] = r.read_se_bounded(-128, 127)?; + pt.luma_offset_l1[usize::from(i)] = r.read_se_bounded(-128, 127)?; + } + + if sps.chroma_array_type() != 0 { + let chroma_weight_l1_flag = r.read_bit()?; + if chroma_weight_l1_flag { + for j in 0..2 { + pt.chroma_weight_l1[usize::from(i)][j] = + r.read_se_bounded(-128, 127)?; + pt.chroma_offset_l1[usize::from(i)][j] = + r.read_se_bounded(-128, 127)?; + } + } + } + } + } + + Ok(()) + } + + fn parse_dec_ref_pic_marking( + r: &mut BitReader, + nalu: &Nalu, + header: &mut SliceHeader, + ) -> Result<(), String> { + let rpm = &mut header.dec_ref_pic_marking; + + let num_bits_left = r.num_bits_left(); + if nalu.header.idr_pic_flag { + rpm.no_output_of_prior_pics_flag = r.read_bit()?; + rpm.long_term_reference_flag = r.read_bit()?; + } else { + rpm.adaptive_ref_pic_marking_mode_flag = r.read_bit()?; + + if rpm.adaptive_ref_pic_marking_mode_flag { + loop { + let mut marking = RefPicMarkingInner::default(); + + let mem_mgmt_ctrl_op = r.read_ue_max::(6)?; + marking.memory_management_control_operation = mem_mgmt_ctrl_op; + + if mem_mgmt_ctrl_op == 0 { + break; + } + + if mem_mgmt_ctrl_op == 1 || mem_mgmt_ctrl_op == 3 { + marking.difference_of_pic_nums_minus1 = r.read_ue()?; + } + + if mem_mgmt_ctrl_op == 2 { + marking.long_term_pic_num = r.read_ue()?; + } + + if mem_mgmt_ctrl_op == 3 || mem_mgmt_ctrl_op == 6 { + marking.long_term_frame_idx = r.read_ue()?; + } + + if mem_mgmt_ctrl_op == 4 { + marking.max_long_term_frame_idx = + MaxLongTermFrameIdx::from_value_plus1(r.read_ue()?); + } + + rpm.inner.push(marking); + } + } + } + header.dec_ref_pic_marking_bit_size = num_bits_left - r.num_bits_left(); + + Ok(()) + } + + pub fn parse_slice_header<'a>(&self, nalu: Nalu<'a>) -> Result, String> { + if !matches!( + nalu.header.type_, + NaluType::Slice + | NaluType::SliceDpa + | NaluType::SliceDpb + | NaluType::SliceDpc + | NaluType::SliceIdr + | NaluType::SliceExt + ) { + return Err(format!("Invalid NALU type: {:?} is not a slice NALU", nalu.header.type_)); + } + + let data = nalu.as_ref(); + // Skip the header + let mut r = BitReader::new(&data[nalu.header.len()..], true); + + let mut header = SliceHeader { first_mb_in_slice: r.read_ue()?, ..Default::default() }; + + let slice_type = r.read_ue_max::(9)? % 5; + header.slice_type = SliceType::try_from(slice_type)?; + + header.pic_parameter_set_id = r.read_ue()?; + + let pps = self.get_pps(header.pic_parameter_set_id).ok_or::(format!( + "Could not get PPS for pic_parameter_set_id {}", + header.pic_parameter_set_id + ))?; + + let sps = &pps.sps; + + if sps.separate_colour_plane_flag { + header.colour_plane_id = r.read_bits(2)?; + } + + header.frame_num = r.read_bits(usize::from(sps.log2_max_frame_num_minus4) + 4)?; + + if !sps.frame_mbs_only_flag { + header.field_pic_flag = r.read_bit()?; + if header.field_pic_flag { + header.bottom_field_flag = r.read_bit()?; + } + } + + if header.field_pic_flag { + header.max_pic_num = 2 * sps.max_frame_num(); + } else { + header.max_pic_num = sps.max_frame_num(); + } + + if nalu.header.idr_pic_flag { + header.idr_pic_id = r.read_ue_max(0xffff)?; + } + + let num_bits_left = r.num_bits_left(); + if sps.pic_order_cnt_type == 0 { + header.pic_order_cnt_lsb = + r.read_bits(usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4)?; + + if pps.bottom_field_pic_order_in_frame_present_flag && !header.field_pic_flag { + header.delta_pic_order_cnt_bottom = r.read_se()?; + } + } + + if sps.pic_order_cnt_type == 1 && !sps.delta_pic_order_always_zero_flag { + header.delta_pic_order_cnt[0] = r.read_se()?; + if pps.bottom_field_pic_order_in_frame_present_flag && !header.field_pic_flag { + header.delta_pic_order_cnt[1] = r.read_se()?; + } + } + header.pic_order_cnt_bit_size = num_bits_left - r.num_bits_left(); + + if pps.redundant_pic_cnt_present_flag { + header.redundant_pic_cnt = r.read_ue_max(127)?; + } + + if header.slice_type.is_b() { + header.direct_spatial_mv_pred_flag = r.read_bit()?; + } + + if header.slice_type.is_p() || header.slice_type.is_sp() || header.slice_type.is_b() { + header.num_ref_idx_active_override_flag = r.read_bit()?; + if header.num_ref_idx_active_override_flag { + header.num_ref_idx_l0_active_minus1 = r.read_ue()?; + if header.slice_type.is_b() { + header.num_ref_idx_l1_active_minus1 = r.read_ue()?; + } + } else { + header.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1; + if header.slice_type.is_b() { + header.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1; + } + } + } + + if header.field_pic_flag { + if header.num_ref_idx_l0_active_minus1 > 31 || header.num_ref_idx_l1_active_minus1 > 31 + { + return Err("Broken Data".into()); + } + } else if header.num_ref_idx_l0_active_minus1 > 15 + || header.num_ref_idx_l1_active_minus1 > 15 + { + return Err("Broken Data".into()); + } + + if let NaluType::SliceExt = nalu.header.type_ { + return Err("Stream contain unsupported/unimplemented NALs".into()); + } + + Parser::parse_ref_pic_list_modifications(&mut r, &mut header)?; + + if (pps.weighted_pred_flag && (header.slice_type.is_p() || header.slice_type.is_sp())) + || (pps.weighted_bipred_idc == 1 && header.slice_type.is_b()) + { + Parser::parse_pred_weight_table(&mut r, sps, &mut header)?; + } + + if nalu.header.ref_idc != 0 { + Parser::parse_dec_ref_pic_marking(&mut r, &nalu, &mut header)?; + } + + if pps.entropy_coding_mode_flag && !header.slice_type.is_i() && !header.slice_type.is_si() { + header.cabac_init_idc = r.read_ue_max(2)?; + } + + header.slice_qp_delta = r.read_se_bounded(-87, 77)?; + + if header.slice_type.is_sp() || header.slice_type.is_si() { + if header.slice_type.is_sp() { + header.sp_for_switch_flag = r.read_bit()?; + } + + header.slice_qs_delta = r.read_se_bounded(-51, 51)?; + } + + if pps.deblocking_filter_control_present_flag { + header.disable_deblocking_filter_idc = r.read_ue_max(2)?; + + if header.disable_deblocking_filter_idc != 1 { + header.slice_alpha_c0_offset_div2 = r.read_se_bounded(-6, 6)?; + header.slice_beta_offset_div2 = r.read_se_bounded(-6, 6)?; + } + } + + if pps.num_slice_groups_minus1 > 0 { + return Err("Stream contain unsupported/unimplemented NALs".into()); + } + + let epb = r.num_epb(); + header.header_bit_size = (nalu.size - epb) * 8 - r.num_bits_left(); + + header.n_emulation_prevention_bytes = epb; + + Ok(Slice { header, nalu }) + } + + pub fn get_sps(&self, sps_id: u8) -> Option<&Rc> { + self.active_spses.get(&sps_id) + } + + pub fn get_pps(&self, pps_id: u8) -> Option<&Rc> { + self.active_ppses.get(&pps_id) + } +} + +#[derive(Debug)] +pub struct NaluHeader { + pub ref_idc: u8, + pub type_: NaluType, + pub idr_pic_flag: bool, +} + +impl Header for NaluHeader { + fn parse>(cursor: &mut Cursor) -> Result { + let mut byte_buf = [0u8; 1]; + cursor.read_exact(&mut byte_buf).map_err(|_| String::from("Broken Data"))?; + let byte = byte_buf[0]; + let _ = cursor.seek(SeekFrom::Current(-1 * byte_buf.len() as i64)); + + let type_ = NaluType::try_from(byte & 0x1f)?; + + if let NaluType::SliceExt = type_ { + return Err("Stream contain unsupported/unimplemented NALs".into()); + } + + let ref_idc = (byte & 0x60) >> 5; + let idr_pic_flag = matches!(type_, NaluType::SliceIdr); + + Ok(NaluHeader { ref_idc, type_, idr_pic_flag }) + } + + fn is_end(&self) -> bool { + matches!(self.type_, NaluType::SeqEnd | NaluType::StreamEnd) + } + + fn len(&self) -> usize { + 1 + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use crate::codec::h264::parser::Level; + use crate::codec::h264::parser::MaxLongTermFrameIdx; + use crate::codec::h264::parser::Nalu; + use crate::codec::h264::parser::NaluType; + use crate::codec::h264::parser::Parser; + + const STREAM_TEST_25_FPS: &[u8] = include_bytes!("test_data/test-25fps.h264"); + const STREAM_TEST_25_FPS_NUM_NALUS: usize = 759; + + const STREAM_TEST_25_FPS_SLICE_0: &[u8] = + include_bytes!("test_data/test-25fps-h264-slice-data-0.bin"); + const STREAM_TEST_25_FPS_SLICE_2: &[u8] = + include_bytes!("test_data/test-25fps-h264-slice-data-2.bin"); + const STREAM_TEST_25_FPS_SLICE_4: &[u8] = + include_bytes!("test_data/test-25fps-h264-slice-data-4.bin"); + + /// This test is adapted from chromium, available at media/video/h264_parser_unittest.cc + #[test] + fn parse_nalus_from_stream_file() { + let mut cursor = Cursor::new(STREAM_TEST_25_FPS); + let mut num_nalus = 0; + while Nalu::next(&mut cursor).is_ok() { + num_nalus += 1; + } + + assert_eq!(num_nalus, STREAM_TEST_25_FPS_NUM_NALUS) + } + + /// The results were manually extracted from the GStreamer parser using GDB + /// (gsth264parser.c) in order to compare both implementations using the + /// following pipeline: + /// gst-launch-1.0 filesrc location=test-25fps.h264 ! h264parse ! 'video/x-h264,stream-format=byte-stream' ! vah264dec ! fakevideosink + #[test] + fn parse_test25fps() { + let mut cursor = Cursor::new(STREAM_TEST_25_FPS); + let mut sps_ids = Vec::new(); + let mut pps_ids = Vec::new(); + let mut slices = Vec::new(); + + let mut parser = Parser::default(); + + while let Ok(nalu) = Nalu::next(&mut cursor) { + match nalu.header.type_ { + NaluType::Slice + | NaluType::SliceDpa + | NaluType::SliceDpb + | NaluType::SliceDpc + | NaluType::SliceIdr + | NaluType::SliceExt => { + let slice = parser.parse_slice_header(nalu).unwrap(); + slices.push(slice); + } + NaluType::Sps => { + let sps = parser.parse_sps(&nalu).unwrap(); + sps_ids.push(sps.seq_parameter_set_id); + } + NaluType::Pps => { + let pps = parser.parse_pps(&nalu).unwrap(); + pps_ids.push(pps.pic_parameter_set_id); + } + _ => { + continue; + } + } + } + + for sps_id in &sps_ids { + // four identical SPSes in this stream + let sps = parser.get_sps(*sps_id).unwrap(); + + assert_eq!(sps.seq_parameter_set_id, 0); + assert_eq!(sps.profile_idc, 77); + assert!(!sps.constraint_set0_flag); + assert!(sps.constraint_set1_flag); + assert!(!sps.constraint_set2_flag); + assert!(!sps.constraint_set3_flag); + assert!(!sps.constraint_set4_flag); + assert!(!sps.constraint_set5_flag); + assert_eq!(sps.level_idc, Level::L1_3); + assert_eq!(sps.chroma_format_idc, 1); + assert!(!sps.separate_colour_plane_flag); + assert_eq!(sps.bit_depth_luma_minus8, 0); + assert_eq!(sps.bit_depth_chroma_minus8, 0); + assert!(!sps.qpprime_y_zero_transform_bypass_flag); + assert!(!sps.seq_scaling_matrix_present_flag); + + for outer in &sps.scaling_lists_4x4 { + for inner in outer { + assert_eq!(*inner, 16); + } + } + + for outer in &sps.scaling_lists_8x8 { + for inner in outer { + assert_eq!(*inner, 16); + } + } + + assert_eq!(sps.log2_max_frame_num_minus4, 1); + assert_eq!(sps.pic_order_cnt_type, 0); + assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 3); + assert!(!sps.delta_pic_order_always_zero_flag); + assert_eq!(sps.offset_for_non_ref_pic, 0); + assert_eq!(sps.offset_for_top_to_bottom_field, 0); + assert_eq!(sps.num_ref_frames_in_pic_order_cnt_cycle, 0); + + for offset in sps.offset_for_ref_frame { + assert_eq!(offset, 0); + } + + assert_eq!(sps.max_num_ref_frames, 2); + assert!(!sps.gaps_in_frame_num_value_allowed_flag); + assert_eq!(sps.pic_width_in_mbs_minus1, 19); + assert_eq!(sps.pic_height_in_map_units_minus1, 14); + assert!(sps.frame_mbs_only_flag); + assert!(!sps.mb_adaptive_frame_field_flag); + assert!(!sps.direct_8x8_inference_flag); + assert!(!sps.frame_cropping_flag); + assert_eq!(sps.frame_crop_left_offset, 0); + assert_eq!(sps.frame_crop_right_offset, 0); + assert_eq!(sps.frame_crop_top_offset, 0); + assert_eq!(sps.frame_crop_bottom_offset, 0); + assert_eq!(sps.chroma_array_type(), 1); + assert_eq!(sps.max_frame_num(), 32); + assert_eq!(sps.width(), 320); + assert_eq!(sps.height(), 240); + } + + for pps_id in &pps_ids { + // four identical SPSes in this stream + let pps = parser.get_pps(*pps_id).unwrap(); + assert_eq!(pps.pic_parameter_set_id, 0); + assert_eq!(pps.seq_parameter_set_id, 0); + assert!(pps.bottom_field_pic_order_in_frame_present_flag); + assert_eq!(pps.num_slice_groups_minus1, 0); + assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0); + assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0); + assert!(!pps.weighted_pred_flag); + assert_eq!(pps.weighted_bipred_idc, 0); + assert_eq!(pps.pic_init_qp_minus26, 2); + assert_eq!(pps.pic_init_qs_minus26, 0); + assert_eq!(pps.chroma_qp_index_offset, 0); + assert!(!pps.deblocking_filter_control_present_flag); + assert!(!pps.constrained_intra_pred_flag); + assert!(!pps.redundant_pic_cnt_present_flag); + assert!(!pps.transform_8x8_mode_flag); + + for outer in &pps.scaling_lists_4x4 { + for inner in outer { + assert_eq!(*inner, 16); + } + } + + for outer in &pps.scaling_lists_8x8 { + for inner in outer { + assert_eq!(*inner, 16); + } + } + + assert_eq!(pps.second_chroma_qp_index_offset, 0); + assert!(!pps.pic_scaling_matrix_present_flag); + } + + // test an I slice + let hdr = &slices[0].header; + let nalu = &slices[0].nalu; + assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_0); + + assert_eq!(hdr.first_mb_in_slice, 0); + assert!(hdr.slice_type.is_i()); + assert_eq!(hdr.colour_plane_id, 0); + assert_eq!(hdr.frame_num, 0); + assert!(!hdr.field_pic_flag); + assert!(!hdr.bottom_field_flag); + assert_eq!(hdr.idr_pic_id, 0); + assert_eq!(hdr.pic_order_cnt_lsb, 0); + assert_eq!(hdr.delta_pic_order_cnt_bottom, 0); + assert_eq!(hdr.delta_pic_order_cnt[0], 0); + assert_eq!(hdr.delta_pic_order_cnt[1], 0); + assert_eq!(hdr.redundant_pic_cnt, 0); + assert!(!hdr.direct_spatial_mv_pred_flag); + assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0); + assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0); + assert!(!hdr.ref_pic_list_modification_flag_l0); + + assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l0 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + assert!(!hdr.ref_pic_list_modification_flag_l1); + assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l1 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + // Safe because this type does not have any references + assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() }); + + assert_eq!(hdr.dec_ref_pic_marking, Default::default()); + + assert_eq!(hdr.cabac_init_idc, 0); + assert_eq!(hdr.slice_qp_delta, 12); + assert_eq!(hdr.slice_qs_delta, 0); + assert_eq!(hdr.disable_deblocking_filter_idc, 0); + assert_eq!(hdr.slice_alpha_c0_offset_div2, 0); + assert_eq!(hdr.slice_beta_offset_div2, 0); + assert_eq!(hdr.max_pic_num, 32); + assert_eq!(hdr.header_bit_size, 38); + assert!(!hdr.num_ref_idx_active_override_flag); + + // test a P slice + let hdr = &slices[2].header; + let nalu = &slices[2].nalu; + assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_2); + + assert_eq!(hdr.first_mb_in_slice, 0); + assert!(hdr.slice_type.is_p()); + assert_eq!(hdr.colour_plane_id, 0); + assert_eq!(hdr.frame_num, 1); + assert!(!hdr.field_pic_flag); + assert!(!hdr.bottom_field_flag); + assert_eq!(hdr.idr_pic_id, 0); + assert_eq!(hdr.pic_order_cnt_lsb, 4); + assert_eq!(hdr.delta_pic_order_cnt_bottom, 0); + assert_eq!(hdr.delta_pic_order_cnt[0], 0); + assert_eq!(hdr.delta_pic_order_cnt[1], 0); + assert_eq!(hdr.redundant_pic_cnt, 0); + assert!(!hdr.direct_spatial_mv_pred_flag); + assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0); + assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0); + assert!(!hdr.ref_pic_list_modification_flag_l0); + + assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l0 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + assert!(!hdr.ref_pic_list_modification_flag_l1); + assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l1 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + // Safe because this type does not have any references + assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() }); + + assert_eq!(hdr.dec_ref_pic_marking, Default::default()); + + assert_eq!(hdr.cabac_init_idc, 0); + assert_eq!(hdr.slice_qp_delta, 0); + assert_eq!(hdr.slice_qs_delta, 0); + assert_eq!(hdr.disable_deblocking_filter_idc, 0); + assert_eq!(hdr.slice_alpha_c0_offset_div2, 0); + assert_eq!(hdr.slice_beta_offset_div2, 0); + assert_eq!(hdr.max_pic_num, 32); + assert_eq!(hdr.header_bit_size, 28); + assert!(!hdr.num_ref_idx_active_override_flag); + + // test a B slice + let hdr = &slices[4].header; + let nalu = &slices[4].nalu; + assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_4); + + assert_eq!(hdr.first_mb_in_slice, 0); + assert!(hdr.slice_type.is_b()); + assert_eq!(hdr.colour_plane_id, 0); + assert_eq!(hdr.frame_num, 2); + assert!(!hdr.field_pic_flag); + assert!(!hdr.bottom_field_flag); + assert_eq!(hdr.idr_pic_id, 0); + assert_eq!(hdr.pic_order_cnt_lsb, 2); + assert_eq!(hdr.delta_pic_order_cnt_bottom, 0); + assert_eq!(hdr.delta_pic_order_cnt[0], 0); + assert_eq!(hdr.delta_pic_order_cnt[1], 0); + assert_eq!(hdr.redundant_pic_cnt, 0); + assert!(hdr.direct_spatial_mv_pred_flag); + assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0); + assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0); + assert!(!hdr.ref_pic_list_modification_flag_l0); + + assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l0 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + assert!(!hdr.ref_pic_list_modification_flag_l1); + assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0); + + for rplm in &hdr.ref_pic_list_modification_l1 { + assert_eq!(rplm.modification_of_pic_nums_idc, 0); + assert_eq!(rplm.abs_diff_pic_num_minus1, 0); + assert_eq!(rplm.long_term_pic_num, 0); + assert_eq!(rplm.abs_diff_view_idx_minus1, 0); + } + + // Safe because this type does not have any references + assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() }); + + assert_eq!(hdr.dec_ref_pic_marking, Default::default()); + + assert_eq!(hdr.cabac_init_idc, 0); + assert_eq!(hdr.slice_qp_delta, 16); + assert_eq!(hdr.slice_qs_delta, 0); + assert_eq!(hdr.disable_deblocking_filter_idc, 0); + assert_eq!(hdr.slice_alpha_c0_offset_div2, 0); + assert_eq!(hdr.slice_beta_offset_div2, 0); + assert_eq!(hdr.max_pic_num, 32); + assert_eq!(hdr.header_bit_size, 41); + assert!(!hdr.num_ref_idx_active_override_flag); + } + + #[test] + fn invalid_sps_crop_width() { + // This SPS contains invalid frame_crop_*_offset settings. This led to + // unconditional panic in the parser in the past. This test make sure a + // panic is avoided. + let invalid_sps = + vec![0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x0a, 0xfb, 0xb0, 0x32, 0xc0, 0xca, 0x80]; + + let mut cursor = Cursor::new(invalid_sps.as_ref()); + let mut parser = Parser::default(); + + while let Ok(nalu) = Nalu::next(&mut cursor) { + assert_eq!(nalu.header.type_, NaluType::Sps); + parser.parse_sps(&nalu).unwrap_err(); + } + } + + #[test] + fn max_long_term_frame_idx() { + assert_eq!( + MaxLongTermFrameIdx::from_value_plus1(0), + MaxLongTermFrameIdx::NoLongTermFrameIndices + ); + assert_eq!(MaxLongTermFrameIdx::NoLongTermFrameIndices.to_value_plus1(), 0); + + assert_eq!(MaxLongTermFrameIdx::from_value_plus1(1), MaxLongTermFrameIdx::Idx(0)); + assert_eq!(MaxLongTermFrameIdx::Idx(0).to_value_plus1(), 1); + + assert_eq!(MaxLongTermFrameIdx::from_value_plus1(25), MaxLongTermFrameIdx::Idx(24)); + assert_eq!(MaxLongTermFrameIdx::Idx(24).to_value_plus1(), 25); + + // Check PartialOrd implementation. + assert!(MaxLongTermFrameIdx::NoLongTermFrameIndices < 0); + assert_ne!(MaxLongTermFrameIdx::NoLongTermFrameIndices, 0); + assert_eq!(MaxLongTermFrameIdx::Idx(0), 0); + assert!(MaxLongTermFrameIdx::Idx(0) < 1); + assert_eq!(MaxLongTermFrameIdx::Idx(24), 24); + assert!(MaxLongTermFrameIdx::Idx(24) < 25); + } +} diff --git a/vendor/cros-codecs/src/codec/h264/picture.rs b/vendor/cros-codecs/src/codec/h264/picture.rs new file mode 100644 index 0000000..ed8bc75 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/picture.rs @@ -0,0 +1,415 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::ops::Deref; +use std::rc::Rc; +use std::rc::Weak; + +use log::debug; + +use crate::codec::h264::parser::MaxLongTermFrameIdx; +use crate::codec::h264::parser::RefPicMarking; +use crate::codec::h264::parser::Slice; +use crate::codec::h264::parser::SliceType; +use crate::codec::h264::parser::Sps; +use crate::Resolution; + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum Field { + #[default] + Frame, + Top, + Bottom, +} + +impl Field { + /// Returns the field of opposite parity. + pub fn opposite(&self) -> Self { + match *self { + Field::Frame => Field::Frame, + Field::Top => Field::Bottom, + Field::Bottom => Field::Top, + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum Reference { + #[default] + None, + ShortTerm, + LongTerm, +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum IsIdr { + #[default] + No, + Yes { + idr_pic_id: u16, + }, +} + +/// The rank of a field, i.e. whether it is the first or second one to be parsed from the stream. +/// This is unrelated to the `Field` type, as the first field can be either `Top` or `Bottom`. +#[derive(Default, Debug)] +pub enum FieldRank { + /// Frame has a single field. + #[default] + Single, + /// Frame is interlaced, and this is the first field (with a reference to the second one). + First(Weak>), + /// Frame is interlaced, and this is the second field (with a reference to the first one). + Second(Rc>), +} + +#[derive(Default)] +pub struct PictureData { + pub pic_order_cnt_type: u8, + pub top_field_order_cnt: i32, + pub bottom_field_order_cnt: i32, + pub pic_order_cnt: i32, + pub pic_order_cnt_msb: i32, + pub pic_order_cnt_lsb: i32, + pub delta_pic_order_cnt_bottom: i32, + pub delta_pic_order_cnt0: i32, + pub delta_pic_order_cnt1: i32, + + pub pic_num: i32, + pub long_term_pic_num: u32, + pub frame_num: u32, + pub frame_num_offset: u32, + pub frame_num_wrap: i32, + pub long_term_frame_idx: u32, + + pub coded_resolution: Resolution, + pub display_resolution: Resolution, + + pub type_: SliceType, + pub nal_ref_idc: u8, + pub is_idr: IsIdr, + reference: Reference, + pub ref_pic_list_modification_flag_l0: i32, + pub abs_diff_pic_num_minus1: i32, + + // Does memory management op 5 needs to be executed after this + // picture has finished decoding? + pub has_mmco_5: bool, + + // Created by the decoding process for gaps in frame_num. + // Not for decode or output. + pub nonexisting: bool, + + pub field: Field, + + // Values from slice_hdr to be used during reference marking and + // memory management after finishing this picture. + pub ref_pic_marking: RefPicMarking, + + field_rank: FieldRank, + + pub timestamp: u64, +} + +/// A `PictureData` within a `Rc` which field rank is guaranteed to be correct. +/// +/// The field rank of `PictureData` is only final after both fields have been constructed - namely, +/// the first field can only point to the second one after the latter is available as a Rc. Methods +/// [`PictureData::into_rc`] and [`PictureData::split_frame`] take care of this, and is this only +/// producer of this type, ensuring all instances are correct. +#[derive(Default, Debug, Clone)] +pub struct RcPictureData { + pic: Rc>, +} + +impl Deref for RcPictureData { + type Target = Rc>; + + fn deref(&self) -> &Self::Target { + &self.pic + } +} + +impl PictureData { + pub fn new_non_existing(frame_num: u32, timestamp: u64) -> Self { + PictureData { + frame_num, + nonexisting: true, + nal_ref_idc: 1, + field: Field::Frame, + pic_num: frame_num as i32, + reference: Reference::ShortTerm, + timestamp, + ..Default::default() + } + } + + /// Create a new picture from a `slice`, `sps`, and `timestamp`. + /// + /// `first_field` is set if this picture is the second field of a frame. + pub fn new_from_slice( + slice: &Slice, + sps: &Sps, + timestamp: u64, + first_field: Option<&RcPictureData>, + ) -> Self { + let hdr = &slice.header; + let nalu_hdr = &slice.nalu.header; + + let is_idr = if nalu_hdr.idr_pic_flag { + IsIdr::Yes { idr_pic_id: hdr.idr_pic_id } + } else { + IsIdr::No + }; + + let field = if hdr.field_pic_flag { + if hdr.bottom_field_flag { + Field::Bottom + } else { + Field::Top + } + } else { + Field::Frame + }; + + let reference = if nalu_hdr.ref_idc != 0 { Reference::ShortTerm } else { Reference::None }; + + let pic_num = if !hdr.field_pic_flag { hdr.frame_num } else { 2 * hdr.frame_num + 1 }; + + let ( + pic_order_cnt_lsb, + delta_pic_order_cnt_bottom, + delta_pic_order_cnt0, + delta_pic_order_cnt1, + ) = match sps.pic_order_cnt_type { + 0 => ( + hdr.pic_order_cnt_lsb, + hdr.delta_pic_order_cnt_bottom, + Default::default(), + Default::default(), + ), + 1 => ( + Default::default(), + Default::default(), + hdr.delta_pic_order_cnt[0], + hdr.delta_pic_order_cnt[1], + ), + _ => (Default::default(), Default::default(), Default::default(), Default::default()), + }; + + let coded_resolution = Resolution::from((sps.width(), sps.height())); + + let visible_rect = sps.visible_rectangle(); + + let display_resolution = Resolution { + width: visible_rect.max.x - visible_rect.min.x, + height: visible_rect.max.y - visible_rect.min.y, + }; + + let mut pic = PictureData { + pic_order_cnt_type: sps.pic_order_cnt_type, + pic_order_cnt_lsb: i32::from(pic_order_cnt_lsb), + delta_pic_order_cnt_bottom, + delta_pic_order_cnt0, + delta_pic_order_cnt1, + pic_num: i32::from(pic_num), + frame_num: u32::from(hdr.frame_num), + nal_ref_idc: nalu_hdr.ref_idc, + is_idr, + reference, + field, + ref_pic_marking: hdr.dec_ref_pic_marking.clone(), + coded_resolution, + display_resolution, + timestamp, + ..Default::default() + }; + + if let Some(first_field) = first_field { + pic.set_first_field_to(first_field); + } + + pic + } + + /// Whether the current picture is a reference, either ShortTerm or LongTerm. + pub fn is_ref(&self) -> bool { + !matches!(self.reference, Reference::None) + } + + /// Whether this picture is a second field. + pub fn is_second_field(&self) -> bool { + matches!(self.field_rank, FieldRank::Second(..)) + } + + /// Returns the field rank of this picture, including a reference to its other field. + pub fn field_rank(&self) -> &FieldRank { + &self.field_rank + } + + /// Returns a reference to the picture's Reference + pub fn reference(&self) -> &Reference { + &self.reference + } + + /// Mark the picture as a reference picture. + pub fn set_reference(&mut self, reference: Reference, apply_to_other_field: bool) { + log::debug!("Set reference of {:#?} to {:?}", self, reference); + self.reference = reference; + + if apply_to_other_field { + if let Some(other_field) = self.other_field() { + log::debug!( + "other_field: Set reference of {:#?} to {:?}", + &other_field.borrow(), + reference + ); + other_field.borrow_mut().reference = reference; + } + } + } + + /// Get a reference to the picture's other field, if there is any + /// and its reference is still valid. + pub fn other_field(&self) -> Option>> { + match &self.field_rank { + FieldRank::Single => None, + FieldRank::First(other_field) => other_field.upgrade(), + FieldRank::Second(other_field) => Some(other_field.clone()), + } + } + + /// Set this picture's second field. + fn set_second_field_to(&mut self, other_field: &Rc>) { + self.field_rank = FieldRank::First(Rc::downgrade(other_field)); + } + + /// Whether the current picture is the second field of a complementary ref pair. + pub fn is_second_field_of_complementary_ref_pair(&self) -> bool { + self.is_ref() + && matches!(self.field_rank(), FieldRank::Second(first_field) if first_field.borrow().is_ref()) + } + + /// Set this picture's first field. + fn set_first_field_to(&mut self, other_field: &Rc>) { + self.field_rank = FieldRank::Second(other_field.clone()); + } + + pub fn pic_num_f(&self, max_pic_num: i32) -> i32 { + if !matches!(self.reference(), Reference::LongTerm) { + self.pic_num + } else { + max_pic_num + } + } + + pub fn long_term_pic_num_f(&self, max_long_term_frame_idx: MaxLongTermFrameIdx) -> u32 { + if matches!(self.reference(), Reference::LongTerm) { + self.long_term_pic_num + } else { + 2 * max_long_term_frame_idx.to_value_plus1() + } + } + + /// Consume this picture and return a Rc'd version. + /// + /// If the picture was a second field, adjust the field of the first field to point to this + /// one. + pub fn into_rc(self) -> RcPictureData { + let self_rc = Rc::new(RefCell::new(self)); + + if let FieldRank::Second(first_field) = self_rc.borrow().field_rank() { + first_field.borrow_mut().set_second_field_to(&self_rc); + } + + RcPictureData { pic: self_rc } + } + + /// Split a frame into two complementary fields that reference one another. + pub fn split_frame(mut self) -> (RcPictureData, RcPictureData) { + assert!(matches!(self.field, Field::Frame)); + assert!(matches!(self.field_rank, FieldRank::Single)); + + debug!( + "Splitting picture (frame_num, POC) ({:?}, {:?})", + self.frame_num, self.pic_order_cnt + ); + + let second_pic_order_cnt = if self.top_field_order_cnt < self.bottom_field_order_cnt { + self.field = Field::Top; + self.pic_order_cnt = self.top_field_order_cnt; + + self.bottom_field_order_cnt + } else { + self.field = Field::Bottom; + self.pic_order_cnt = self.bottom_field_order_cnt; + + self.top_field_order_cnt + }; + + let second_field = PictureData { + top_field_order_cnt: self.top_field_order_cnt, + bottom_field_order_cnt: self.bottom_field_order_cnt, + frame_num: self.frame_num, + reference: self.reference, + nonexisting: self.nonexisting, + pic_order_cnt: second_pic_order_cnt, + field: self.field.opposite(), + ..Default::default() + }; + + debug!( + "Split into picture (frame_num, POC) ({:?}, {:?}), field: {:?}", + self.frame_num, self.pic_order_cnt, self.field + ); + debug!( + "Split into picture (frame_num, POC) ({:?}, {:?}), field {:?}", + second_field.frame_num, second_field.pic_order_cnt, second_field.field + ); + + let first_field = Rc::new(RefCell::new(self)); + let second_field = Rc::new(RefCell::new(second_field)); + + first_field.borrow_mut().set_second_field_to(&second_field); + second_field.borrow_mut().set_first_field_to(&first_field); + + (RcPictureData { pic: first_field }, RcPictureData { pic: second_field }) + } +} + +impl std::fmt::Debug for PictureData { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PictureData") + .field("pic_order_cnt_type", &self.pic_order_cnt_type) + .field("top_field_order_cnt", &self.top_field_order_cnt) + .field("bottom_field_order_cnt", &self.bottom_field_order_cnt) + .field("pic_order_cnt", &self.pic_order_cnt) + .field("pic_order_cnt_msb", &self.pic_order_cnt_msb) + .field("pic_order_cnt_lsb", &self.pic_order_cnt_lsb) + .field("delta_pic_order_cnt_bottom", &self.delta_pic_order_cnt_bottom) + .field("delta_pic_order_cnt0", &self.delta_pic_order_cnt0) + .field("delta_pic_order_cnt1", &self.delta_pic_order_cnt1) + .field("pic_num", &self.pic_num) + .field("long_term_pic_num", &self.long_term_pic_num) + .field("frame_num", &self.frame_num) + .field("frame_num_offset", &self.frame_num_offset) + .field("frame_num_wrap", &self.frame_num_wrap) + .field("long_term_frame_idx", &self.long_term_frame_idx) + .field("coded_resolution", &self.coded_resolution) + .field("display_resolution", &self.display_resolution) + .field("type_", &self.type_) + .field("nal_ref_idc", &self.nal_ref_idc) + .field("is_idr", &self.is_idr) + .field("reference", &self.reference) + .field("ref_pic_list_modification_flag_l0", &self.ref_pic_list_modification_flag_l0) + .field("abs_diff_pic_num_minus1", &self.abs_diff_pic_num_minus1) + .field("has_mmco_5", &self.has_mmco_5) + .field("nonexisting", &self.nonexisting) + .field("field", &self.field) + .field("ref_pic_marking", &self.ref_pic_marking) + .field("field_rank", &self.field_rank) + .finish() + } +} diff --git a/vendor/cros-codecs/src/codec/h264/synthesizer.rs b/vendor/cros-codecs/src/codec/h264/synthesizer.rs new file mode 100644 index 0000000..b28596c --- /dev/null +++ b/vendor/cros-codecs/src/codec/h264/synthesizer.rs @@ -0,0 +1,582 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +use std::fmt; +use std::io::Write; + +use crate::codec::h264::nalu_writer::NaluWriter; +use crate::codec::h264::nalu_writer::NaluWriterError; +use crate::codec::h264::parser::HrdParams; +use crate::codec::h264::parser::NaluType; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::parser::DEFAULT_4X4_INTER; +use crate::codec::h264::parser::DEFAULT_4X4_INTRA; +use crate::codec::h264::parser::DEFAULT_8X8_INTER; +use crate::codec::h264::parser::DEFAULT_8X8_INTRA; + +mod private { + pub trait NaluStruct {} +} + +impl private::NaluStruct for Sps {} + +impl private::NaluStruct for Pps {} + +#[derive(Debug)] +pub enum SynthesizerError { + Unsupported, + NaluWriter(NaluWriterError), +} + +impl fmt::Display for SynthesizerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SynthesizerError::Unsupported => write!(f, "tried to synthesize unsupported settings"), + SynthesizerError::NaluWriter(x) => write!(f, "{}", x.to_string()), + } + } +} + +impl From for SynthesizerError { + fn from(err: NaluWriterError) -> Self { + SynthesizerError::NaluWriter(err) + } +} + +pub type SynthesizerResult = Result; + +/// A helper to output typed NALUs to [`std::io::Write`] using [`NaluWriter`]. +pub struct Synthesizer<'n, N: private::NaluStruct, W: Write> { + writer: NaluWriter, + nalu: &'n N, +} + +/// Extended Sample Aspect Ratio - H.264 Table E-1 +const EXTENDED_SAR: u8 = 255; + +impl Synthesizer<'_, N, W> { + fn u>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { + self.writer.write_u(bits, value)?; + Ok(()) + } + + fn f>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { + self.writer.write_f(bits, value)?; + Ok(()) + } + + fn ue>(&mut self, value: T) -> SynthesizerResult<()> { + self.writer.write_ue(value)?; + Ok(()) + } + + fn se>(&mut self, value: T) -> SynthesizerResult<()> { + self.writer.write_se(value)?; + Ok(()) + } + + fn scaling_list(&mut self, list: &[u8], default: &[u8]) -> SynthesizerResult<()> { + // H.264 7.3.2.1.1.1 + if list == default { + self.se(-8)?; + return Ok(()); + } + + // The number of list values we want to encode. + let mut run = list.len(); + + // Check how many values at the end of the matrix are the same, + // so we can save on encoding those. + for j in (1..list.len()).rev() { + if list[j - 1] != list[j] { + break; + } + run -= 1; + } + + // Encode deltas. + let mut last_scale = 8; + for scale in &list[0..run] { + let delta_scale = *scale as i32 - last_scale; + self.se(delta_scale)?; + last_scale = *scale as i32; + } + + // Didn't encode all values, encode -|last_scale| to set decoder's + // |next_scale| (H.264 7.3.2.1.1.1) to zero, i.e. decoder should repeat + // last values in matrix. + if run < list.len() { + self.se(-last_scale)?; + } + + Ok(()) + } + + fn default_scaling_list(i: usize) -> &'static [u8] { + // H.264 Table 7-2 + match i { + 0 => &DEFAULT_4X4_INTRA[..], + 1 => &DEFAULT_4X4_INTRA[..], + 2 => &DEFAULT_4X4_INTRA[..], + 3 => &DEFAULT_4X4_INTER[..], + 4 => &DEFAULT_4X4_INTER[..], + 5 => &DEFAULT_4X4_INTER[..], + 6 => &DEFAULT_8X8_INTRA[..], + 7 => &DEFAULT_8X8_INTER[..], + 8 => &DEFAULT_8X8_INTRA[..], + 9 => &DEFAULT_8X8_INTER[..], + 10 => &DEFAULT_8X8_INTRA[..], + 11 => &DEFAULT_8X8_INTER[..], + _ => unreachable!(), + } + } + + fn rbsp_trailing_bits(&mut self) -> SynthesizerResult<()> { + self.f(1, 1u32)?; + + while !self.writer.aligned() { + self.f(1, 0u32)?; + } + + Ok(()) + } +} + +impl<'n, W: Write> Synthesizer<'n, Sps, W> { + pub fn synthesize( + ref_idc: u8, + sps: &'n Sps, + writer: W, + ep_enabled: bool, + ) -> SynthesizerResult<()> { + let mut s = Self { writer: NaluWriter::::new(writer, ep_enabled), nalu: sps }; + + s.writer.write_header(ref_idc, NaluType::Sps as u8)?; + s.seq_parameter_set_data()?; + s.rbsp_trailing_bits() + } + + fn hrd_parameters(&mut self, hrd_params: &HrdParams) -> SynthesizerResult<()> { + self.ue(hrd_params.cpb_cnt_minus1)?; + self.u(4, hrd_params.bit_rate_scale)?; + self.u(4, hrd_params.cpb_size_scale)?; + + for i in 0..=(hrd_params.cpb_cnt_minus1 as usize) { + self.ue(hrd_params.bit_rate_value_minus1[i])?; + self.ue(hrd_params.cpb_size_value_minus1[i])?; + self.u(1, hrd_params.cbr_flag[i])?; + } + + self.u(5, hrd_params.initial_cpb_removal_delay_length_minus1)?; + self.u(5, hrd_params.cpb_removal_delay_length_minus1)?; + self.u(5, hrd_params.dpb_output_delay_length_minus1)?; + self.u(5, hrd_params.time_offset_length)?; + + Ok(()) + } + + fn vui_parameters(&mut self) -> SynthesizerResult<()> { + // H.264 E.1.1 + let vui_params = &self.nalu.vui_parameters; + + self.u(1, vui_params.aspect_ratio_info_present_flag)?; + if vui_params.aspect_ratio_info_present_flag { + self.u(8, vui_params.aspect_ratio_idc)?; + if vui_params.aspect_ratio_idc == EXTENDED_SAR { + self.u(16, vui_params.sar_width)?; + self.u(16, vui_params.sar_height)?; + } + } + + self.u(1, vui_params.overscan_info_present_flag)?; + if vui_params.overscan_info_present_flag { + self.u(1, vui_params.overscan_appropriate_flag)?; + } + + self.u(1, vui_params.video_signal_type_present_flag)?; + if vui_params.video_signal_type_present_flag { + self.u(3, vui_params.video_format)?; + self.u(1, vui_params.video_full_range_flag)?; + + self.u(1, vui_params.colour_description_present_flag)?; + if vui_params.colour_description_present_flag { + self.u(8, vui_params.colour_primaries)?; + self.u(8, vui_params.transfer_characteristics)?; + self.u(8, vui_params.matrix_coefficients)?; + } + } + + self.u(1, vui_params.chroma_loc_info_present_flag)?; + if vui_params.chroma_loc_info_present_flag { + self.ue(vui_params.chroma_sample_loc_type_top_field)?; + self.ue(self.nalu.vui_parameters.chroma_sample_loc_type_bottom_field)?; + } + + self.u(1, vui_params.timing_info_present_flag)?; + if vui_params.timing_info_present_flag { + self.u(32, vui_params.num_units_in_tick)?; + self.u(32, vui_params.time_scale)?; + self.u(1, vui_params.fixed_frame_rate_flag)?; + } + + self.u(1, vui_params.nal_hrd_parameters_present_flag)?; + if vui_params.nal_hrd_parameters_present_flag { + self.hrd_parameters(&vui_params.nal_hrd_parameters)?; + } + self.u(1, vui_params.vcl_hrd_parameters_present_flag)?; + if vui_params.vcl_hrd_parameters_present_flag { + self.hrd_parameters(&vui_params.vcl_hrd_parameters)?; + } + + if vui_params.nal_hrd_parameters_present_flag || vui_params.vcl_hrd_parameters_present_flag + { + self.u(1, vui_params.low_delay_hrd_flag)?; + } + + self.u(1, vui_params.pic_struct_present_flag)?; + + self.u(1, vui_params.bitstream_restriction_flag)?; + if vui_params.bitstream_restriction_flag { + self.u(1, vui_params.motion_vectors_over_pic_boundaries_flag)?; + self.ue(vui_params.max_bytes_per_pic_denom)?; + self.ue(vui_params.max_bits_per_mb_denom)?; + self.ue(vui_params.log2_max_mv_length_horizontal)?; + self.ue(vui_params.log2_max_mv_length_vertical)?; + self.ue(vui_params.max_num_reorder_frames)?; + self.ue(vui_params.max_dec_frame_buffering)?; + } + + Ok(()) + } + + fn seq_parameter_set_data(&mut self) -> SynthesizerResult<()> { + // H.264 7.3.2.1.1 + self.u(8, self.nalu.profile_idc)?; + self.u(1, self.nalu.constraint_set0_flag)?; + self.u(1, self.nalu.constraint_set1_flag)?; + self.u(1, self.nalu.constraint_set2_flag)?; + self.u(1, self.nalu.constraint_set3_flag)?; + self.u(1, self.nalu.constraint_set4_flag)?; + self.u(1, self.nalu.constraint_set5_flag)?; + self.u(2, /* reserved_zero_2bits */ 0u32)?; + self.u(8, self.nalu.level_idc as u32)?; + self.ue(self.nalu.seq_parameter_set_id)?; + + if self.nalu.profile_idc == 100 + || self.nalu.profile_idc == 110 + || self.nalu.profile_idc == 122 + || self.nalu.profile_idc == 244 + || self.nalu.profile_idc == 44 + || self.nalu.profile_idc == 83 + || self.nalu.profile_idc == 86 + || self.nalu.profile_idc == 118 + || self.nalu.profile_idc == 128 + || self.nalu.profile_idc == 138 + || self.nalu.profile_idc == 139 + || self.nalu.profile_idc == 134 + || self.nalu.profile_idc == 135 + { + self.ue(self.nalu.chroma_format_idc)?; + + if self.nalu.chroma_format_idc == 3 { + self.u(1, self.nalu.separate_colour_plane_flag)?; + } + + self.ue(self.nalu.bit_depth_luma_minus8)?; + self.ue(self.nalu.bit_depth_chroma_minus8)?; + self.u(1, self.nalu.qpprime_y_zero_transform_bypass_flag)?; + self.u(1, self.nalu.seq_scaling_matrix_present_flag)?; + + if self.nalu.seq_scaling_matrix_present_flag { + let scaling_list_count = if self.nalu.chroma_format_idc != 3 { 8 } else { 12 }; + + for i in 0..scaling_list_count { + // Assume if scaling lists are zeroed that they are not present. + if i < 6 { + if self.nalu.scaling_lists_4x4[i] == [0; 16] { + self.u(1, /* seq_scaling_list_present_flag */ false)?; + } else { + self.u(1, /* seq_scaling_list_present_flag */ true)?; + self.scaling_list( + &self.nalu.scaling_lists_4x4[i], + Self::default_scaling_list(i), + )?; + } + } else if self.nalu.scaling_lists_8x8[i - 6] == [0; 64] { + self.u(1, /* seq_scaling_list_present_flag */ false)?; + } else { + self.u(1, /* seq_scaling_list_present_flag */ true)?; + self.scaling_list( + &self.nalu.scaling_lists_8x8[i - 6], + Self::default_scaling_list(i), + )?; + } + } + } + } + + self.ue(self.nalu.log2_max_frame_num_minus4)?; + self.ue(self.nalu.pic_order_cnt_type)?; + + if self.nalu.pic_order_cnt_type == 0 { + self.ue(self.nalu.log2_max_pic_order_cnt_lsb_minus4)?; + } else if self.nalu.pic_order_cnt_type == 1 { + self.u(1, self.nalu.delta_pic_order_always_zero_flag)?; + self.se(self.nalu.offset_for_non_ref_pic)?; + self.se(self.nalu.offset_for_top_to_bottom_field)?; + self.ue(self.nalu.num_ref_frames_in_pic_order_cnt_cycle)?; + + for offset_for_ref_frame in &self.nalu.offset_for_ref_frame { + self.se(*offset_for_ref_frame)?; + } + } + + self.ue(self.nalu.max_num_ref_frames)?; + self.u(1, self.nalu.gaps_in_frame_num_value_allowed_flag)?; + self.ue(self.nalu.pic_width_in_mbs_minus1)?; + self.ue(self.nalu.pic_height_in_map_units_minus1)?; + self.u(1, self.nalu.frame_mbs_only_flag)?; + if !self.nalu.frame_mbs_only_flag { + self.u(1, self.nalu.mb_adaptive_frame_field_flag)?; + } + self.u(1, self.nalu.direct_8x8_inference_flag)?; + + self.u(1, self.nalu.frame_cropping_flag)?; + if self.nalu.frame_cropping_flag { + self.ue(self.nalu.frame_crop_left_offset)?; + self.ue(self.nalu.frame_crop_right_offset)?; + self.ue(self.nalu.frame_crop_top_offset)?; + self.ue(self.nalu.frame_crop_bottom_offset)?; + } + + self.u(1, self.nalu.vui_parameters_present_flag)?; + if self.nalu.vui_parameters_present_flag { + self.vui_parameters()?; + } + + Ok(()) + } +} + +impl<'n, W: Write> Synthesizer<'n, Pps, W> { + pub fn synthesize( + ref_idc: u8, + pps: &'n Pps, + writer: W, + ep_enabled: bool, + ) -> SynthesizerResult<()> { + let mut s = Self { writer: NaluWriter::::new(writer, ep_enabled), nalu: pps }; + + s.writer.write_header(ref_idc, NaluType::Pps as u8)?; + s.pic_parameter_set_rbsp()?; + s.rbsp_trailing_bits() + } + + fn pic_parameter_set_rbsp(&mut self) -> SynthesizerResult<()> { + self.ue(self.nalu.pic_parameter_set_id)?; + self.ue(self.nalu.seq_parameter_set_id)?; + self.u(1, self.nalu.entropy_coding_mode_flag)?; + self.u(1, self.nalu.bottom_field_pic_order_in_frame_present_flag)?; + + self.ue(self.nalu.num_slice_groups_minus1)?; + if self.nalu.num_slice_groups_minus1 > 0 { + return Err(SynthesizerError::Unsupported); + } + + self.ue(self.nalu.num_ref_idx_l0_default_active_minus1)?; + self.ue(self.nalu.num_ref_idx_l1_default_active_minus1)?; + self.u(1, self.nalu.weighted_pred_flag)?; + self.u(2, self.nalu.weighted_bipred_idc)?; + self.se(self.nalu.pic_init_qp_minus26)?; + self.se(self.nalu.pic_init_qs_minus26)?; + self.se(self.nalu.chroma_qp_index_offset)?; + self.u(1, self.nalu.deblocking_filter_control_present_flag)?; + self.u(1, self.nalu.constrained_intra_pred_flag)?; + self.u(1, self.nalu.redundant_pic_cnt_present_flag)?; + + if !(self.nalu.transform_8x8_mode_flag + || self.nalu.pic_scaling_matrix_present_flag + || self.nalu.second_chroma_qp_index_offset != 0) + { + return Ok(()); + } + + self.u(1, self.nalu.transform_8x8_mode_flag)?; + self.u(1, self.nalu.pic_scaling_matrix_present_flag)?; + + if self.nalu.pic_scaling_matrix_present_flag { + let mut scaling_list_count = 6; + if self.nalu.transform_8x8_mode_flag { + if self.nalu.sps.chroma_format_idc != 3 { + scaling_list_count += 2; + } else { + scaling_list_count += 6; + } + } + + for i in 0..scaling_list_count { + // Assume if scaling lists are zeroed that they are not present. + if i < 6 { + if self.nalu.scaling_lists_4x4[i] == [0; 16] { + self.u(1, /* seq_scaling_list_present_flag */ false)?; + } else { + self.u(1, /* seq_scaling_list_present_flag */ true)?; + self.scaling_list( + &self.nalu.scaling_lists_4x4[i], + Self::default_scaling_list(i), + )?; + } + } else if self.nalu.scaling_lists_8x8[i - 6] == [0; 64] { + self.u(1, /* seq_scaling_list_present_flag */ false)?; + } else { + self.u(1, /* seq_scaling_list_present_flag */ true)?; + self.scaling_list( + &self.nalu.scaling_lists_8x8[i - 6], + Self::default_scaling_list(i), + )?; + } + } + } + + self.se(self.nalu.second_chroma_qp_index_offset)?; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use super::*; + use crate::codec::h264::parser::Nalu; + use crate::codec::h264::parser::NaluType; + use crate::codec::h264::parser::Parser; + use crate::codec::h264::parser::Profile; + + #[test] + fn synthesize_sps() { + let raw_sps_buf = [0x00, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x0a, 0xfb, 0x88]; + let mut raw_sps = Cursor::new(&raw_sps_buf[..]); + + let nalu = Nalu::next(&mut raw_sps).unwrap(); + assert_eq!(nalu.header.type_, NaluType::Sps); + + let mut parser = Parser::default(); + let sps = parser.parse_sps(&nalu).unwrap(); + + let mut buf = Vec::::new(); + Synthesizer::<'_, Sps, _>::synthesize(0, sps, &mut buf, false).unwrap(); + + assert_eq!(buf, raw_sps_buf); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + let mut out = std::fs::File::create("sps.h264").unwrap(); + out.write_all(&buf).unwrap(); + out.flush().unwrap(); + } + + let mut cursor = Cursor::new(&buf[..]); + let nalu = Nalu::next(&mut cursor).unwrap(); + + let mut parser = Parser::default(); + + let sps2 = parser.parse_sps(&nalu).unwrap(); + + assert_eq!(sps, sps2); + } + + #[test] + fn synthesize_sps_scaling_lists() { + let sps = Sps { + profile_idc: Profile::High as u8, + seq_scaling_matrix_present_flag: true, + scaling_lists_4x4: [[11, 20, 10, 20, 10, 22, 10, 20, 10, 20, 13, 20, 10, 20, 10, 24]; + 6], + scaling_lists_8x8: [ + [ + 33, 20, 10, 21, 33, 20, 12, 20, 33, 23, 10, 20, 33, 20, 10, 20, 33, 24, 10, 20, + 33, 20, 15, 20, 33, 20, 10, 26, 33, 20, 17, 20, 33, 28, 10, 20, 33, 20, 10, 20, + 33, 29, 10, 20, 33, 20, 11, 20, 33, 20, 10, 20, 33, 20, 10, 20, 33, 20, 10, 20, + 33, 20, 10, 20, + ], + [ + 10, 77, 11, 20, 10, 77, 12, 20, 10, 77, 13, 20, 10, 77, 14, 20, 10, 77, 15, 20, + 10, 77, 16, 20, 10, 77, 17, 20, 10, 77, 18, 20, 10, 77, 19, 20, 10, 77, 10, 20, + 10, 77, 10, 21, 10, 77, 10, 22, 10, 77, 10, 23, 10, 77, 10, 24, 10, 77, 10, 26, + 10, 77, 10, 28, + ], + [0; 64], + [0; 64], + [0; 64], + [0; 64], + ], + frame_mbs_only_flag: true, + ..Default::default() + }; + + let mut buf = Vec::::new(); + Synthesizer::<'_, Sps, _>::synthesize(0, &sps, &mut buf, false).unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + let mut out = std::fs::File::create("sps.h264").unwrap(); + out.write_all(&buf).unwrap(); + out.flush().unwrap(); + } + + let mut cursor = Cursor::new(&buf[..]); + let nalu = Nalu::next(&mut cursor).unwrap(); + + let mut parser = Parser::default(); + + let sps2 = parser.parse_sps(&nalu).unwrap(); + + assert_eq!(sps.scaling_lists_4x4, sps2.scaling_lists_4x4); + assert_eq!(sps.scaling_lists_8x8, sps2.scaling_lists_8x8); + } + + #[test] + fn synthesize_pps() { + let raw_sps_pps = [ + 0x00, 0x00, 0x00, 0x01, 0x07, 0x4d, 0x40, 0x0d, 0xa9, 0x18, 0x28, 0x3e, 0x60, 0x0d, + 0x41, 0x80, 0x41, 0xad, 0xb0, 0xad, 0x7b, 0xdf, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0xde, 0x09, 0x88, + ]; + + let mut buf = Vec::::new(); + let mut out = Cursor::new(&mut buf); + + let mut cursor = Cursor::new(&raw_sps_pps[..]); + let mut parser: Parser = Default::default(); + + while let Ok(nalu) = Nalu::next(&mut cursor) { + match nalu.header.type_ { + NaluType::Sps => { + let sps = parser.parse_sps(&nalu).unwrap(); + Synthesizer::<'_, Sps, _>::synthesize(0, sps, &mut out, false).unwrap(); + } + NaluType::Pps => { + let pps = parser.parse_pps(&nalu).unwrap(); + Synthesizer::<'_, Pps, _>::synthesize(0, pps, &mut out, false).unwrap(); + } + _ => panic!(), + } + } + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + let mut out = std::fs::File::create("sps_pps.h264").unwrap(); + out.write_all(&buf).unwrap(); + out.flush().unwrap(); + + let mut out = std::fs::File::create("sps_pps_ref.h264").unwrap(); + out.write_all(&raw_sps_pps).unwrap(); + out.flush().unwrap(); + } + + assert_eq!(buf, raw_sps_pps); + } +} diff --git a/vendor/cros-codecs/src/codec/h265.rs b/vendor/cros-codecs/src/codec/h265.rs new file mode 100644 index 0000000..44f3f8a --- /dev/null +++ b/vendor/cros-codecs/src/codec/h265.rs @@ -0,0 +1,7 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +pub mod dpb; +pub mod parser; +pub mod picture; diff --git a/vendor/cros-codecs/src/codec/h265/dpb.rs b/vendor/cros-codecs/src/codec/h265/dpb.rs new file mode 100644 index 0000000..a9bfb92 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h265/dpb.rs @@ -0,0 +1,276 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::Ref; +use std::cell::RefCell; +use std::cell::RefMut; +use std::rc::Rc; + +use crate::codec::h265::parser::Sps; +use crate::codec::h265::picture::PictureData; +use crate::codec::h265::picture::Reference; + +// Shortcut to refer to a DPB entry. +// +// The first member of the tuple is the `PictureData` for the frame. +// +// The second member is the backend handle of the frame. +#[derive(Clone, Debug)] +pub struct DpbEntry(pub Rc>, pub T); + +pub struct Dpb { + /// List of `PictureData` and backend handles to decoded pictures. + entries: Vec>, + /// The maximum number of pictures that can be stored. + max_num_pics: usize, +} + +impl Dpb { + /// Returns an iterator over the underlying H265 pictures stored in the + /// DPB. + pub fn pictures(&self) -> impl Iterator> { + self.entries.iter().map(|h| h.0.borrow()) + } + + /// Returns a mutable iterator over the underlying H265 pictures stored in + /// the DPB. + pub fn pictures_mut(&mut self) -> impl Iterator> { + self.entries.iter().map(|h| h.0.borrow_mut()) + } + + /// Returns the length of the DPB. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Get a reference to the whole DPB entries. + pub fn entries(&self) -> &Vec> { + &self.entries + } + + /// Set the dpb's max num pics. + pub fn set_max_num_pics(&mut self, max_num_pics: usize) { + self.max_num_pics = max_num_pics; + } + + /// Get a reference to the dpb's max num pics. + pub fn max_num_pics(&self) -> usize { + self.max_num_pics + } + + /// Mark all pictures in the DPB as unused for reference. + pub fn mark_all_as_unused_for_ref(&mut self) { + for mut picture in self.pictures_mut() { + picture.set_reference(Reference::None); + } + } + + /// Gets the position of `needle` in the DPB, if any. + fn get_position(&self, needle: &Rc>) -> Option { + self.entries.iter().position(|handle| Rc::ptr_eq(&handle.0, needle)) + } + + /// Finds a reference picture in the DPB using `poc`. + pub fn find_ref_by_poc(&self, poc: i32) -> Option> { + let position = self.pictures().position(|p| p.is_ref() && p.pic_order_cnt_val == poc); + + log::debug!("find_ref_by_poc: {}, found position {:?}", poc, position); + Some(self.entries[position?].clone()) + } + + /// Finds a reference picture in the DPB using `poc` and `mask`. + pub fn find_ref_by_poc_masked(&self, poc: i32, mask: i32) -> Option> { + let position = + self.pictures().position(|p| p.is_ref() && p.pic_order_cnt_val & mask == poc); + + log::debug!("find_ref_by_poc: {}, found position {:?}", poc, position); + Some(self.entries[position?].clone()) + } + + /// Finds a short term reference picture in the DPB using `poc`. + pub fn find_short_term_ref_by_poc(&self, poc: i32) -> Option> { + let position = self.pictures().position(|p| { + matches!(p.reference(), Reference::ShortTerm) && p.pic_order_cnt_val == poc + }); + + log::debug!("find_short_term_ref_by_poc: {}, found position {:?}", poc, position); + Some(self.entries[position?].clone()) + } + + /// Drains the DPB by continuously invoking the bumping process. + pub fn drain(&mut self) -> Vec> { + log::debug!("Draining the DPB."); + + let mut pics = vec![]; + while let Some(pic) = self.bump(true) { + pics.push(pic); + } + + pics + } + + /// Whether the DPB needs bumping. See C.5.2.2. + pub fn needs_bumping(&mut self, sps: &Sps) -> bool { + let num_needed_for_output = self.pictures().filter(|pic| pic.needed_for_output).count(); + + let highest_tid = sps.max_sub_layers_minus1; + let max_num_reorder_pics = sps.max_num_reorder_pics[usize::from(highest_tid)]; + let max_latency_increase_plus1 = sps.max_latency_increase_plus1[usize::from(highest_tid)]; + let pic_over_max_latency = self.pictures().find(|pic| { + pic.needed_for_output && pic.pic_latency_cnt >= i32::from(max_latency_increase_plus1) + }); + let max_dec_pic_buffering = + usize::from(sps.max_dec_pic_buffering_minus1[usize::from(highest_tid)]) + 1; + + num_needed_for_output > max_num_reorder_pics.into() + || (max_latency_increase_plus1 != 0 && pic_over_max_latency.is_some()) + || self.entries().len() >= max_dec_pic_buffering + } + + /// Find the lowest POC in the DPB that can be bumped. + fn find_lowest_poc_for_bumping(&self) -> Option> { + let lowest = self + .pictures() + .filter(|pic| pic.needed_for_output) + .min_by_key(|pic| pic.pic_order_cnt_val)?; + + let position = self + .entries + .iter() + .position(|handle| handle.0.borrow().pic_order_cnt_val == lowest.pic_order_cnt_val) + .unwrap(); + + Some(self.entries[position].clone()) + } + + /// See C.5.2.4 "Bumping process". + pub fn bump(&mut self, flush: bool) -> Option> { + let handle = self.find_lowest_poc_for_bumping()?; + let mut pic = handle.0.borrow_mut(); + + pic.needed_for_output = false; + log::debug!("Bumping POC {} from the dpb", pic.pic_order_cnt_val); + log::trace!("{:#?}", pic); + + if !pic.is_ref() || flush { + let index = self.get_position(&handle.0).unwrap(); + + log::debug!( + "Removed POC {} from the dpb: reference: {}, flush: {}", + pic.pic_order_cnt_val, + pic.is_ref(), + flush + ); + log::trace!("{:#?}", pic); + + self.entries.remove(index); + } + + Some(handle.clone()) + } + + /// See C.5.2.3. Happens when we are done decoding the picture. + pub fn needs_additional_bumping(&mut self, sps: &Sps) -> bool { + let num_needed_for_output = self.pictures().filter(|pic| pic.needed_for_output).count(); + let highest_tid = sps.max_sub_layers_minus1; + + let max_num_reorder_pics = sps.max_num_reorder_pics[usize::from(highest_tid)]; + let max_latency_increase_plus1 = sps.max_latency_increase_plus1[usize::from(highest_tid)]; + + let pic_over_max_latency = self.pictures().find(|pic| { + pic.needed_for_output && pic.pic_latency_cnt >= i32::from(max_latency_increase_plus1) + }); + + num_needed_for_output > max_num_reorder_pics.into() + || (max_latency_increase_plus1 != 0 && pic_over_max_latency.is_some()) + } + + /// Clears the DPB, dropping all the pictures. + pub fn clear(&mut self) { + log::debug!("Clearing the DPB"); + + let max_num_pics = self.max_num_pics; + + *self = Default::default(); + self.max_num_pics = max_num_pics; + } + + /// Removes all pictures which are marked as "not needed for output" and + /// "unused for reference". See C.5.2.2 + pub fn remove_unused(&mut self) { + log::debug!("Removing unused pictures from DPB."); + self.entries.retain(|e| { + let pic = e.0.borrow(); + let retain = pic.needed_for_output || pic.is_ref(); + log::debug!("Retaining pic POC: {}: {}", pic.pic_order_cnt_val, retain); + retain + }) + } + + /// Store a picture and its backend handle in the DPB. + pub fn store_picture( + &mut self, + picture: Rc>, + handle: T, + ) -> Result<(), String> { + if self.entries.len() >= self.max_num_pics { + return Err("Can't add a picture to the DPB: DPB is full.".into()); + } + + let mut pic = picture.borrow_mut(); + log::debug!( + "Stored picture POC {:?}, the DPB length is {:?}", + pic.pic_order_cnt_val, + self.entries.len() + ); + + if pic.pic_output_flag { + pic.needed_for_output = true; + pic.pic_latency_cnt = 0; + } else { + pic.needed_for_output = false; + } + + // C.3.4. + // After all the slices of the current picture have been decoded, this + // picture is marked as "used for short-term reference". + pic.set_reference(Reference::ShortTerm); + drop(pic); + + for mut pic in self.pictures_mut() { + pic.pic_latency_cnt += 1; + } + + self.entries.push(DpbEntry(picture, handle)); + + Ok(()) + } + + /// Returns all the references in the DPB. + pub fn get_all_references(&self) -> Vec> { + self.entries.iter().filter(|e| e.0.borrow().is_ref()).cloned().collect() + } +} + +impl Default for Dpb { + fn default() -> Self { + // See https://github.com/rust-lang/rust/issues/26925 on why this can't + // be derived. + Self { entries: Default::default(), max_num_pics: Default::default() } + } +} + +impl std::fmt::Debug for Dpb { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let pics = self.entries.iter().map(|h| &h.0).enumerate().collect::>(); + f.debug_struct("Dpb") + .field("pictures", &pics) + .field("max_num_pics", &self.max_num_pics) + .finish() + } +} diff --git a/vendor/cros-codecs/src/codec/h265/parser.rs b/vendor/cros-codecs/src/codec/h265/parser.rs new file mode 100644 index 0000000..c3bb75c --- /dev/null +++ b/vendor/cros-codecs/src/codec/h265/parser.rs @@ -0,0 +1,4784 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! An Annex B h.265 parser. +//! +//! Parses VPSs, SPSs, PPSs and Slices from NALUs. + +use std::collections::BTreeMap; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::rc::Rc; + +use crate::bitstream_utils::BitReader; +use crate::codec::h264::nalu; +use crate::codec::h264::nalu::Header; +use crate::codec::h264::parser::Point; +use crate::codec::h264::parser::Rect; + +// Given the max VPS id. +const MAX_VPS_COUNT: usize = 16; +// Given the max SPS id. +const MAX_SPS_COUNT: usize = 16; +// Given the max PPS id. +const MAX_PPS_COUNT: usize = 64; +// 7.4.7.1 +const MAX_REF_IDX_ACTIVE: u32 = 15; + +// 7.4.3.2.1: +// num_short_term_ref_pic_sets specifies the number of st_ref_pic_set( ) syntax +// structures included in the SPS. The value of num_short_term_ref_pic_sets +// shall be in the range of 0 to 64, inclusive. +// NOTE 5 – A decoder should allocate memory for a total number of +// num_short_term_ref_pic_sets + 1 st_ref_pic_set( ) syntax structures since +// there may be a st_ref_pic_set( ) syntax structure directly signalled in the +// slice headers of a current picture. A st_ref_pic_set( ) syntax structure +// directly signalled in the slice headers of a current picture has an index +// equal to num_short_term_ref_pic_sets. +const MAX_SHORT_TERM_REF_PIC_SETS: usize = 65; + +// 7.4.3.2.1: +const MAX_LONG_TERM_REF_PIC_SETS: usize = 32; + +// From table 7-5. +const DEFAULT_SCALING_LIST_0: [u8; 16] = [16; 16]; + +// From Table 7-6. +const DEFAULT_SCALING_LIST_1: [u8; 64] = [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20, + 21, 20, 19, 21, 24, 22, 22, 24, 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, + 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115, +]; + +// From Table 7-6. +const DEFAULT_SCALING_LIST_2: [u8; 64] = [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20, + 20, 20, 20, 20, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, + 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91, +]; + +/// Table 7-1 – NAL unit type codes and NAL unit type classes +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum NaluType { + #[default] + TrailN = 0, + TrailR = 1, + TsaN = 2, + TsaR = 3, + StsaN = 4, + StsaR = 5, + RadlN = 6, + RadlR = 7, + RaslN = 8, + RaslR = 9, + RsvVclN10 = 10, + RsvVclR11 = 11, + RsvVclN12 = 12, + RsvVclR13 = 13, + RsvVclN14 = 14, + RsvVclR15 = 15, + BlaWLp = 16, + BlaWRadl = 17, + BlaNLp = 18, + IdrWRadl = 19, + IdrNLp = 20, + CraNut = 21, + RsvIrapVcl22 = 22, + RsvIrapVcl23 = 23, + RsvVcl24 = 24, + RsvVcl25 = 25, + RsvVcl26 = 26, + RsvVcl27 = 27, + RsvVcl28 = 28, + RsvVcl29 = 29, + RsvVcl30 = 30, + RsvVcl31 = 31, + VpsNut = 32, + SpsNut = 33, + PpsNut = 34, + AudNut = 35, + EosNut = 36, + EobNut = 37, + FdNut = 38, + PrefixSeiNut = 39, + SuffixSeiNut = 40, + RsvNvcl41 = 41, + RsvNvcl42 = 42, + RsvNvcl43 = 43, + RsvNvcl44 = 44, + RsvNvcl45 = 45, + RsvNvcl46 = 46, + RsvNvcl47 = 47, +} + +impl TryFrom for NaluType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(NaluType::TrailN), + 1 => Ok(NaluType::TrailR), + 2 => Ok(NaluType::TsaN), + 3 => Ok(NaluType::TsaR), + 4 => Ok(NaluType::StsaN), + 5 => Ok(NaluType::StsaR), + 6 => Ok(NaluType::RadlN), + 7 => Ok(NaluType::RadlR), + 8 => Ok(NaluType::RaslN), + 9 => Ok(NaluType::RaslR), + 10 => Ok(NaluType::RsvVclN10), + 11 => Ok(NaluType::RsvVclR11), + 12 => Ok(NaluType::RsvVclN12), + 13 => Ok(NaluType::RsvVclR13), + 14 => Ok(NaluType::RsvVclN14), + 15 => Ok(NaluType::RsvVclR15), + 16 => Ok(NaluType::BlaWLp), + 17 => Ok(NaluType::BlaWRadl), + 18 => Ok(NaluType::BlaNLp), + 19 => Ok(NaluType::IdrWRadl), + 20 => Ok(NaluType::IdrNLp), + 21 => Ok(NaluType::CraNut), + 22 => Ok(NaluType::RsvIrapVcl22), + 23 => Ok(NaluType::RsvIrapVcl23), + 24 => Ok(NaluType::RsvVcl24), + 25 => Ok(NaluType::RsvVcl25), + 26 => Ok(NaluType::RsvVcl26), + 27 => Ok(NaluType::RsvVcl27), + 28 => Ok(NaluType::RsvVcl28), + 29 => Ok(NaluType::RsvVcl29), + 30 => Ok(NaluType::RsvVcl30), + 31 => Ok(NaluType::RsvVcl31), + 32 => Ok(NaluType::VpsNut), + 33 => Ok(NaluType::SpsNut), + 34 => Ok(NaluType::PpsNut), + 35 => Ok(NaluType::AudNut), + 36 => Ok(NaluType::EosNut), + 37 => Ok(NaluType::EobNut), + 38 => Ok(NaluType::FdNut), + 39 => Ok(NaluType::PrefixSeiNut), + 40 => Ok(NaluType::SuffixSeiNut), + 41 => Ok(NaluType::RsvNvcl41), + 42 => Ok(NaluType::RsvNvcl42), + 43 => Ok(NaluType::RsvNvcl43), + 44 => Ok(NaluType::RsvNvcl44), + 45 => Ok(NaluType::RsvNvcl45), + 46 => Ok(NaluType::RsvNvcl46), + 47 => Ok(NaluType::RsvNvcl47), + _ => Err(format!("Invalid NaluType {}", value)), + } + } +} + +impl NaluType { + /// Whether this is an IDR NALU. + pub fn is_idr(&self) -> bool { + matches!(self, Self::IdrWRadl | Self::IdrNLp) + } + + /// Whether this is an IRAP NALU. + pub fn is_irap(&self) -> bool { + let type_ = *self as u32; + type_ >= Self::BlaWLp as u32 && type_ <= Self::RsvIrapVcl23 as u32 + } + + /// Whether this is a BLA NALU. + pub fn is_bla(&self) -> bool { + let type_ = *self as u32; + type_ >= Self::BlaWLp as u32 && type_ <= Self::BlaNLp as u32 + } + + /// Whether this is a CRA NALU. + pub fn is_cra(&self) -> bool { + matches!(self, Self::CraNut) + } + + /// Whether this is a RADL NALU. + pub fn is_radl(&self) -> bool { + matches!(self, Self::RadlN | Self::RadlR) + } + + /// Whether this is a RASL NALU. + pub fn is_rasl(&self) -> bool { + matches!(self, Self::RaslN | Self::RaslR) + } + + //// Whether this is a SLNR NALU. + pub fn is_slnr(&self) -> bool { + // From the specification: + // If a picture has nal_unit_type equal to TRAIL_N, TSA_N, STSA_N, + // RADL_N, RASL_N, RSV_VCL_N10, RSV_VCL_N12 or RSV_VCL_N14, the picture + // is an SLNR picture. Otherwise, the picture is a sub-layer reference + // picture. + matches!( + self, + Self::TrailN + | Self::TsaN + | Self::StsaN + | Self::RadlN + | Self::RaslN + | Self::RsvVclN10 + | Self::RsvVclN12 + | Self::RsvVclN14 + ) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NaluHeader { + /// The NALU type. + pub type_: NaluType, + /// Specifies the identifier of the layer to which a VCL NAL unit belongs or + /// the identifier of a layer to which a non-VCL NAL unit applies. + pub nuh_layer_id: u8, + /// Minus 1 specifies a temporal identifier for the NAL unit. The value of + /// nuh_temporal_id_plus1 shall not be equal to 0. + pub nuh_temporal_id_plus1: u8, +} + +impl NaluHeader { + pub fn nuh_temporal_id(&self) -> u8 { + self.nuh_temporal_id_plus1.saturating_sub(1) + } +} + +impl Header for NaluHeader { + fn parse>(cursor: &mut std::io::Cursor) -> Result { + let mut data = [0u8; 2]; + cursor.read_exact(&mut data).map_err(|_| String::from("Broken Data"))?; + let mut r = BitReader::new(&data, false); + let _ = cursor.seek(SeekFrom::Current(-1 * data.len() as i64)); + + // Skip forbidden_zero_bit + r.skip_bits(1)?; + + Ok(Self { + type_: NaluType::try_from(r.read_bits::(6)?)?, + nuh_layer_id: r.read_bits::(6)?, + nuh_temporal_id_plus1: r.read_bits::(3)?, + }) + } + + fn is_end(&self) -> bool { + matches!(self.type_, NaluType::EosNut | NaluType::EobNut) + } + + fn len(&self) -> usize { + // 7.3.1.2 + 2 + } +} + +pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>; + +/// H265 levels as defined by table A.8. +/// `general_level_idc` and `sub_layer_level_idc[ OpTid ]` shall be set equal to a +/// value of 30 times the level number specified in Table A.8 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + #[default] + L1 = 30, + L2 = 60, + L2_1 = 63, + L3 = 90, + L3_1 = 93, + L4 = 120, + L4_1 = 123, + L5 = 150, + L5_1 = 153, + L5_2 = 156, + L6 = 180, + L6_1 = 183, + L6_2 = 186, +} + +impl TryFrom for Level { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 30 => Ok(Level::L1), + 60 => Ok(Level::L2), + 63 => Ok(Level::L2_1), + 90 => Ok(Level::L3), + 93 => Ok(Level::L3_1), + 120 => Ok(Level::L4), + 123 => Ok(Level::L4_1), + 150 => Ok(Level::L5), + 153 => Ok(Level::L5_1), + 156 => Ok(Level::L5_2), + 180 => Ok(Level::L6), + 183 => Ok(Level::L6_1), + 186 => Ok(Level::L6_2), + _ => Err(format!("Invalid Level {}", value)), + } + } +} + +/// H265 profiles. See A.3. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum Profile { + #[default] + Main = 1, + Main10 = 2, + MainStill = 3, + RangeExtensions = 4, + HighThroughput = 5, + MultiviewMain = 6, + ScalableMain = 7, + ThreeDMain = 8, + ScreenContentCoding = 9, + ScalableRangeExtensions = 10, + HighThroughputScreenContentCoding = 11, +} + +impl TryFrom for Profile { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 1 => Ok(Profile::Main), + 2 => Ok(Profile::Main10), + 3 => Ok(Profile::MainStill), + 4 => Ok(Profile::RangeExtensions), + 5 => Ok(Profile::HighThroughput), + 6 => Ok(Profile::MultiviewMain), + 7 => Ok(Profile::ScalableMain), + 8 => Ok(Profile::ThreeDMain), + 9 => Ok(Profile::ScreenContentCoding), + 10 => Ok(Profile::ScalableRangeExtensions), + 11 => Ok(Profile::HighThroughputScreenContentCoding), + _ => Err(format!("Invalid Profile {}", value)), + } + } +} + +/// A H.265 Video Parameter Set. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Vps { + /// Identifies the VPS for reference by other syntax elements. + pub video_parameter_set_id: u8, + /// If vps_base_layer_internal_flag is equal to 1 and + /// vps_base_layer_available_flag is equal to 1, the base layer is present + /// in the bitstream. + pub base_layer_internal_flag: bool, + /// See `base_layer_internal_flag`. + pub base_layer_available_flag: bool, + /// Plus 1 specifies the maximum allowed number of layers in each CVS + /// referring to the VPS. + pub max_layers_minus1: u8, + /// Plus 1 specifies the maximum number of temporal sub-layers that may be + /// present in each CVS referring to the VPS. + pub max_sub_layers_minus1: u8, + /// When vps_max_sub_layers_minus1 is greater than 0, specifies whether + /// inter prediction is additionally restricted for CVSs referring to the + /// VPS. + pub temporal_id_nesting_flag: bool, + /// ProfileTierLevel() data. + pub profile_tier_level: ProfileTierLevel, + /// When true, specifies that `vps_max_dec_pic_buffering_minus1[ i ]`, + /// `vps_max_num_reorder_pics[ i ]` and `vps_max_latency_increase_plus1[ i ]` + /// are present for vps_max_sub_layers_ minus1 + 1 sub-layers. + /// vps_sub_layer_ordering_info_present_flag equal to 0 specifies that the + /// values of `vps_max_dec_pic_buffering_minus1[ vps_max_sub_layers_minus1 ]`, + /// vps_max_num_reorder_pics[ vps_max_sub_ layers_minus1 ] and + /// `vps_max_latency_increase_plus1[ vps_max_sub_layers_minus1 ]` apply to all + /// sub-layers + pub sub_layer_ordering_info_present_flag: bool, + /// `max_dec_pic_buffering_minus1[i]` plus 1 specifies the maximum required + /// size of the decoded picture buffer for the CVS in units of picture + /// storage buffers when HighestTid is equal to i. + pub max_dec_pic_buffering_minus1: [u32; 7], + /// Indicates the maximum allowed number of pictures with PicOutputFlag + /// equal to 1 that can precede any picture with PicOutputFlag equal to 1 in + /// the CVS in decoding order and follow that picture with PicOutputFlag + /// equal to 1 in output order when HighestTid is equal to i. + pub max_num_reorder_pics: [u32; 7], + /// When true, `max_latency_increase_plus1[i]` is used to compute the value of + /// `VpsMaxLatencyPictures[ i ]`, which specifies the maximum number of + /// pictures with PicOutputFlag equal to 1 that can precede any picture with + /// PicOutputFlag equal to 1 in the CVS in output order and follow that + /// picture with PicOutputFlag equal to 1 in decoding order when HighestTid + /// is equal to i. + pub max_latency_increase_plus1: [u32; 7], + /// Specifies the maximum allowed value of nuh_layer_id of all NAL units in + /// each CVS referring to the VPS. + pub max_layer_id: u8, + /// num_layer_sets_minus1 plus 1 specifies the number of layer sets that are + /// specified by the VPS. + pub num_layer_sets_minus1: u32, + /// When true, specifies that num_units_in_tick, time_scale, + /// poc_proportional_to_timing_flag and num_hrd_parameters are present in + /// the VPS. + pub timing_info_present_flag: bool, + /// The number of time units of a clock operating at the frequency + /// vps_time_scale Hz that corresponds to one increment (called a clock + /// tick) of a clock tick counter. The value of vps_num_units_in_tick shall + /// be greater than 0. A clock tick, in units of seconds, is equal to the + /// quotient of vps_num_units_in_tick divided by vps_time_scale. For + /// example, when the picture rate of a video signal is 25 Hz, + /// vps_time_scale may be equal to 27 000 000 and vps_num_units_in_tick may + /// be equal to 1 080 000, and consequently a clock tick may be 0.04 + /// seconds. + pub num_units_in_tick: u32, + /// The number of time units that pass in one second. For example, a time + /// coordinate system that measures time using a 27 MHz clock has a + /// vps_time_scale of 27 000 000. + pub time_scale: u32, + /// When true, indicates that the picture order count value for each picture + /// in the CVS that is not the first picture in the CVS, in decoding order, + /// is proportional to the output time of the picture relative to the output + /// time of the first picture in the CVS. When false, indicates that the + /// picture order count value for each picture in the CVS that is not the + /// first picture in the CVS, in decoding order, may or may not be + /// proportional to the output time of the picture relative to the output + /// time of the first picture in the CVS. + pub poc_proportional_to_timing_flag: bool, + /// num_ticks_poc_diff_one_minus1 plus 1 specifies the number of clock ticks + /// corresponding to a difference of picture order count values equal to 1. + pub num_ticks_poc_diff_one_minus1: u32, + /// Specifies the number of hrd_parameters( ) syntax structures present in + /// the VPS RBSP before the vps_extension_flag syntax element. + pub num_hrd_parameters: u32, + /// `hrd_layer_set_idx[ i ]` specifies the index, into the list of layer sets + /// specified by the VPS, of the layer set to which the i-th hrd_parameters( + /// ) syntax structure in the VPS applies. + pub hrd_layer_set_idx: Vec, + /// `cprms_present_flag[ i ]` equal to true specifies that the HRD parameters + /// that are common for all sub-layers are present in the i-th + /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ i ]` + /// equal to false specifies that the HRD parameters that are common for all + /// sub-layers are not present in the i-th hrd_parameters( ) syntax + /// structure in the VPS and are derived to be the same as the ( i − 1 )-th + /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ 0 ]` + /// is inferred to be equal to true. + pub cprms_present_flag: Vec, + /// The hrd_parameters() data. + pub hrd_parameters: Vec, + /// When false, specifies that no vps_extension_data_flag syntax elements + /// are present in the VPS RBSP syntax structure. When true, specifies that + /// there are vps_extension_data_flag syntax elements present in the VPS + /// RBSP syntax structure. Decoders conforming to a profile specified in + /// Annex A but not supporting the INBLD capability specified in Annex F + /// shall ignore all data that follow the value 1 for vps_extension_flag in + /// a VPS NAL unit. + pub extension_flag: bool, +} + +impl Default for Vps { + fn default() -> Self { + Self { + video_parameter_set_id: Default::default(), + base_layer_internal_flag: Default::default(), + base_layer_available_flag: Default::default(), + max_layers_minus1: Default::default(), + max_sub_layers_minus1: Default::default(), + temporal_id_nesting_flag: Default::default(), + profile_tier_level: Default::default(), + sub_layer_ordering_info_present_flag: Default::default(), + max_dec_pic_buffering_minus1: Default::default(), + max_num_reorder_pics: Default::default(), + max_latency_increase_plus1: Default::default(), + max_layer_id: Default::default(), + num_layer_sets_minus1: Default::default(), + timing_info_present_flag: Default::default(), + num_units_in_tick: Default::default(), + time_scale: Default::default(), + poc_proportional_to_timing_flag: Default::default(), + num_ticks_poc_diff_one_minus1: Default::default(), + num_hrd_parameters: Default::default(), + hrd_layer_set_idx: Default::default(), + cprms_present_flag: vec![true], + hrd_parameters: Default::default(), + extension_flag: Default::default(), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProfileTierLevel { + /// Specifies the context for the interpretation of general_profile_idc and + /// `general_profile_compatibility_flag[ j ]` for all values of j in the range + /// of 0 to 31, inclusive. + pub general_profile_space: u8, + /// Specifies the tier context for the interpretation of general_level_idc + /// as specified in Annex A. + pub general_tier_flag: bool, + /// When general_profile_space is equal to 0, indicates a profile to which + /// the CVS conforms as specified in Annex A. Bitstreams shall not contain + /// values of general_profile_idc other than those specified in Annex A. + /// Other values of general_profile_idc are reserved for future use by ITU-T + /// | ISO/IEC. + pub general_profile_idc: u8, + /// `general_profile_compatibility_flag[ j ]` equal to true, when + /// general_profile_space is false, indicates that the CVS conforms to the + /// profile indicated by general_profile_idc equal to j as specified in + /// Annex A. + pub general_profile_compatibility_flag: [bool; 32], + /// general_progressive_source_flag and general_interlaced_source_flag are + /// interpreted as follows: + /// + /// –If general_progressive_source_flag is true and + /// general_interlaced_source_flag is false, the source scan type of the + /// pictures in the CVS should be interpreted as progressive only. + /// + /// –Otherwise, if general_progressive_source_flag is false and + /// general_interlaced_source_flag is true, the source scan type of the + /// pictures in the CVS should be interpreted as interlaced only. + /// + /// –Otherwise, if general_progressive_source_flag is false and + /// general_interlaced_source_flag is false, the source scan type of the + /// pictures in the CVS should be interpreted as unknown or unspecified. + /// + /// –Otherwise (general_progressive_source_flag is true and + /// general_interlaced_source_flag is true), the source scan type of each + /// picture in the CVS is indicated at the picture level using the syntax + /// element source_scan_type in a picture timing SEI message. + pub general_progressive_source_flag: bool, + /// See `general_progressive_source_flag`. + pub general_interlaced_source_flag: bool, + /// If true, specifies that there are no frame packing arrangement SEI + /// messages, segmented rectangular frame packing arrangement SEI messages, + /// equirectangular projection SEI messages, or cubemap projection SEI + /// messages present in the CVS. If false, indicates that there may or may + /// not be one or more frame packing arrangement SEI messages, segmented + /// rectangular frame packing arrangement SEI messages, equirectangular + /// projection SEI messages, or cubemap projection SEI messages present in + /// the CVS. + pub general_non_packed_constraint_flag: bool, + /// When true, specifies that field_seq_flag is false. When false, indicates + /// that field_seq_flag may or may not be false. + pub general_frame_only_constraint_flag: bool, + /// See Annex A. + pub general_max_12bit_constraint_flag: bool, + /// See Annex A. + pub general_max_10bit_constraint_flag: bool, + /// See Annex A. + pub general_max_8bit_constraint_flag: bool, + /// See Annex A. + pub general_max_422chroma_constraint_flag: bool, + /// See Annex A. + pub general_max_420chroma_constraint_flag: bool, + /// See Annex A. + pub general_max_monochrome_constraint_flag: bool, + /// See Annex A. + pub general_intra_constraint_flag: bool, + /// See Annex A. + pub general_lower_bit_rate_constraint_flag: bool, + /// See Annex A. + pub general_max_14bit_constraint_flag: bool, + /// See Annex A. + pub general_one_picture_only_constraint_flag: bool, + /// When true, specifies that the INBLD capability as specified in Annex F + /// is required for decoding of the layer to which the profile_tier_level( ) + /// syntax structure applies. When false, specifies that the INBLD + /// capability as specified in Annex F is not required for decoding of the + /// layer to which the profile_tier_level( ) syntax structure applies. + pub general_inbld_flag: bool, + /// Indicates a level to which the CVS conforms as specified in Annex A. + pub general_level_idc: Level, + /// Sub-layer syntax element. + pub sub_layer_profile_present_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_level_present_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_profile_space: [u8; 6], + /// Sub-layer syntax element. + pub sub_layer_tier_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_profile_idc: [u8; 6], + /// Sub-layer syntax element. + pub sub_layer_profile_compatibility_flag: [[bool; 32]; 6], + /// Sub-layer syntax element. + pub sub_layer_progressive_source_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_interlaced_source_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_non_packed_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_frame_only_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_12bit_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_10bit_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_8bit_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_422chroma_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_420chroma_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_monochrome_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_intra_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_one_picture_only_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_lower_bit_rate_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_max_14bit_constraint_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_inbld_flag: [bool; 6], + /// Sub-layer syntax element. + pub sub_layer_level_idc: [Level; 6], +} + +impl ProfileTierLevel { + pub fn max_luma_ps(&self) -> u32 { + // See Table A.8. + match self.general_level_idc { + Level::L1 => 36864, + Level::L2 => 122880, + Level::L2_1 => 245760, + Level::L3 => 552960, + Level::L3_1 => 983040, + Level::L4 | Level::L4_1 => 2228224, + Level::L5 | Level::L5_1 | Level::L5_2 => 8912896, + _ => 35651584, + } + } + + pub fn max_dpb_pic_buf(&self) -> u32 { + if self.general_profile_idc >= 1 && self.general_profile_idc <= 5 { + 6 + } else { + 7 + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SpsRangeExtension { + pub transform_skip_rotation_enabled_flag: bool, + pub transform_skip_context_enabled_flag: bool, + pub implicit_rdpcm_enabled_flag: bool, + pub explicit_rdpcm_enabled_flag: bool, + pub extended_precision_processing_flag: bool, + pub intra_smoothing_disabled_flag: bool, + pub high_precision_offsets_enabled_flag: bool, + pub persistent_rice_adaptation_enabled_flag: bool, + pub cabac_bypass_alignment_enabled_flag: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SpsSccExtension { + /// When set, specifies that a picture in the CVS may be included in a + /// reference picture list of a slice of the picture itself. When not set, + /// specifies that a picture in the CVS is never included in a reference + /// picture list of a slice of the picture itself. + pub curr_pic_ref_enabled_flag: bool, + /// When set, specifies that the decoding process for palette mode may be + /// used for intra blocks. When not set, specifies that the decoding process + /// for palette mode is not applied. + pub palette_mode_enabled_flag: bool, + /// Specifies the maximum allowed palette size. + pub palette_max_size: u8, + /// Specifies the difference between the maximum allowed palette predictor + /// size and the maximum allowed palette size. + pub delta_palette_max_predictor_size: u8, + /// When set, specifies that the sequence palette predictors are initialized + /// using the sps_palette_predictor_initializers. When not set, specifies + /// that the entries in the sequence palette predictor are initialized to 0. + pub palette_predictor_initializers_present_flag: bool, + /// num_palette_predictor_initializers_minus1 plus 1 specifies the number of + /// entries in the sequence palette predictor initializer. + pub num_palette_predictor_initializer_minus1: u8, + /// `palette_predictor_initializer[ comp ][ i ]` specifies the value of the + /// comp-th component of the i-th palette entry in the SPS that is used to + /// initialize the array PredictorPaletteEntries. + pub palette_predictor_initializer: [[u32; 128]; 3], + /// Controls the presence and inference of the use_integer_mv_flag that + /// specifies the resolution of motion vectors for inter prediction. + pub motion_vector_resolution_control_idc: u8, + /// When set, specifies that the intra boundary filtering process is + /// unconditionally disabled for intra prediction. If not set, specifies + /// that the intra boundary filtering process may be used. + pub intra_boundary_filtering_disabled_flag: bool, +} + +impl Default for SpsSccExtension { + fn default() -> Self { + Self { + curr_pic_ref_enabled_flag: Default::default(), + palette_mode_enabled_flag: Default::default(), + palette_max_size: Default::default(), + delta_palette_max_predictor_size: Default::default(), + palette_predictor_initializers_present_flag: Default::default(), + num_palette_predictor_initializer_minus1: Default::default(), + palette_predictor_initializer: [[0; 128]; 3], + motion_vector_resolution_control_idc: Default::default(), + intra_boundary_filtering_disabled_flag: Default::default(), + } + } +} + +/// A H.265 Sequence Parameter Set. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Sps { + /// Specifies the value of the vps_video_parameter_set_id of the active VPS. + pub video_parameter_set_id: u8, + /// `max_sub_layers_minus1` plus 1 specifies the maximum number of temporal + /// sub-layers that may be present in each CVS referring to the SPS. + pub max_sub_layers_minus1: u8, + /// When sps_max_sub_layers_minus1 is greater than 0, specifies whether + /// inter prediction is additionally restricted for CVSs referring to the + /// SPS. + pub temporal_id_nesting_flag: bool, + /// profile_tier_level() data. + pub profile_tier_level: ProfileTierLevel, + /// Provides an identifier for the SPS for reference by other syntax + /// elements. + pub seq_parameter_set_id: u8, + /// Specifies the chroma sampling relative to the luma sampling as specified + /// in clause 6.2. + pub chroma_format_idc: u8, + /// When true, specifies that the three colour components of the 4:4:4 + /// chroma format are coded separately. When false, specifies that the + /// colour components are not coded separately. + pub separate_colour_plane_flag: bool, + /// Specifies the width of each decoded picture in units of luma samples. + pub pic_width_in_luma_samples: u16, + /// Specifies the height of each decoded picture in units of luma samples. + pub pic_height_in_luma_samples: u16, + /// When true, indicates that the conformance cropping window offset + /// parameters follow next in the SPS. When false, indicates that the + /// conformance cropping window offset parameters are not present. + pub conformance_window_flag: bool, + /* if conformance_window_flag */ + /// Specify the samples of the pictures in the CVS that are output from the + /// decoding process, in terms of a rectangular region specified in picture + /// coordinates for output. + pub conf_win_left_offset: u32, + pub conf_win_right_offset: u32, + pub conf_win_top_offset: u32, + pub conf_win_bottom_offset: u32, + + /// Specifies the bit depth of the samples of the luma array BitDepthY and + /// the value of the luma quantization parameter range offset QpBdOffsetY. + pub bit_depth_luma_minus8: u8, + /// Specifies the bit depth of the samples of the chroma arrays BitDepthC + /// and the value of the chroma quantization parameter range offset + /// QpBdOffsetC. + pub bit_depth_chroma_minus8: u8, + /// Specifies the value of the variable MaxPicOrderCntLsb that is used in + /// the decoding process for picture order count. + pub log2_max_pic_order_cnt_lsb_minus4: u8, + /// When true, specifies that `max_dec_pic_buffering_minus1[ i ]`, + /// `max_num_reorder_pics[ i ]` and `max_latency_increase_plus1[ i ]` are + /// present for max_sub_layers_minus1 + 1 sub- layers. When false, specifies + /// that the values of `max_dec_pic_ buffering_minus1[ max_sub_layers_minus1 + /// ]`, `max_num_reorder_pics[ max_sub_layers_minus1 ]` and max_ + /// `latency_increase_plus1[ max_sub_layers_minus1 ]` apply to all sub-layers. + pub sub_layer_ordering_info_present_flag: bool, + /// `max_dec_pic_buffering_minus1[ i ]` plus 1 specifies the maximum required + /// size of the decoded picture buffer for the CVS in units of picture + /// storage buffers when HighestTid is equal to i. + pub max_dec_pic_buffering_minus1: [u8; 7], + /// `max_num_reorder_pics[ i ]` indicates the maximum allowed number of + /// pictures with PicOutputFlag equal to 1 that can precede any picture with + /// PicOutputFlag equal to 1 in the CVS in decoding order and follow that + /// picture with PicOutputFlag equal to 1 in output order when HighestTid is + /// equal to i. + pub max_num_reorder_pics: [u8; 7], + /// `max_latency_increase_plus1[ i ]` not equal to 0 is used to compute the + /// value of `SpsMaxLatencyPictures[ i ]`, which specifies the maximum number + /// of pictures with PicOutputFlag equal to 1 that can precede any picture + /// with PicOutputFlag equal to 1 in the CVS in output order and follow that + /// picture with PicOutputFlag equal to 1 in decoding order when HighestTid + /// is equal to i. + pub max_latency_increase_plus1: [u8; 7], + /// min_luma_coding_block_size_minus3 plus 3 specifies the minimum luma + /// coding block size. + pub log2_min_luma_coding_block_size_minus3: u8, + /// Specifies the difference between the maximum and minimum luma coding + /// block size. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// min_luma_transform_block_size_minus2 plus 2 specifies the minimum luma + /// transform block size. + pub log2_min_luma_transform_block_size_minus2: u8, + /// Specifies the difference between the maximum and minimum luma transform + /// block size. + pub log2_diff_max_min_luma_transform_block_size: u8, + /// Specifies the maximum hierarchy depth for transform units of coding + /// units coded in inter prediction mode. + pub max_transform_hierarchy_depth_inter: u8, + /// Specifies the maximum hierarchy depth for transform units of coding + /// units coded in intra prediction mode. + pub max_transform_hierarchy_depth_intra: u8, + /// When true, specifies that a scaling list is used for the scaling process + /// for transform coefficients. When false, specifies that scaling list is + /// not used for the scaling process for transform coefficients. + pub scaling_list_enabled_flag: bool, + /* if scaling_list_enabled_flag */ + /// When true, specifies that the scaling_list_data( ) syntax structure is + /// present in the SPS. When false, specifies that the scaling_list_data( ) + /// syntax structure is not present in the SPS. + pub scaling_list_data_present_flag: bool, + /// The scaling_list_data() syntax data. + pub scaling_list: ScalingLists, + /// When true, specifies that asymmetric motion partitions, i.e., PartMode + /// equal to PART_2NxnU, PART_2NxnD, PART_nLx2N or PART_nRx2N, may be used + /// in CTBs. When false, specifies that asymmetric motion partitions cannot + /// be used in CTBs. + pub amp_enabled_flag: bool, + /// When true, specifies that the sample adaptive offset process is applied + /// to the reconstructed picture after the deblocking filter process. When + /// false, specifies that the sample adaptive offset process is not applied + /// to the reconstructed picture after the deblocking filter process. + pub sample_adaptive_offset_enabled_flag: bool, + /// When false, specifies that PCM-related syntax + /// (pcm_sample_bit_depth_luma_minus1, pcm_sample_ bit_depth_chroma_minus1, + /// log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_ + /// coding_block_size, pcm_loop_filter_disabled_flag, pcm_flag, + /// pcm_alignment_zero_bit syntax elements and pcm_sample( ) syntax + /// structure) is not present in the CVS. + pub pcm_enabled_flag: bool, + + /* if pcm_enabled_flag */ + pub pcm_sample_bit_depth_luma_minus1: u8, + /// Specifies the number of bits used to represent each of PCM sample values + /// of the luma component. + pub pcm_sample_bit_depth_chroma_minus1: u8, + /// Specifies the number of bits used to represent each of PCM sample values + /// of the chroma components. + pub log2_min_pcm_luma_coding_block_size_minus3: u8, + /// Specifies the difference between the maximum and minimum size of coding + /// blocks with pcm_flag equal to true. + pub log2_diff_max_min_pcm_luma_coding_block_size: u8, + /// Specifies whether the loop filter process is disabled on reconstructed + /// samples in a coding unit with pcm_flag equal to true as follows: + /// + /// – If pcm_loop_filter_disabled_flag is set, the deblocking filter and + /// sample adaptive offset filter processes on the reconstructed samples in + /// a coding unit with pcm_flag set are disabled. + /// + /// – Otherwise (pcm_loop_filter_disabled_flag value is not set), the + /// deblocking filter and sample adaptive offset filter processes on the + /// reconstructed samples in a coding unit with pcm_flag set are not + /// disabled. + pub pcm_loop_filter_disabled_flag: bool, + /// Specifies the number of st_ref_pic_set( ) syntax structures included in + /// the SPS. + pub num_short_term_ref_pic_sets: u8, + /// the st_ref_pic_set() data. + pub short_term_ref_pic_set: Vec, + /// If unset, specifies that no long-term reference picture is used for + /// inter prediction of any coded picture in the CVS. + /// If set, specifies that long-term reference pictures may be used for + /// inter prediction of one or more coded pictures in the CVS. + pub long_term_ref_pics_present_flag: bool, + + /* if long_term_ref_pics_present_flag */ + /// Specifies the number of candidate long-term reference pictures that are + /// specified in the SPS. + pub num_long_term_ref_pics_sps: u8, + /// `lt_ref_pic_poc_lsb_sps[ i ]` specifies the picture order count modulo + /// MaxPicOrderCntLsb of the i-th candidate long-term reference picture + /// specified in the SPS. + pub lt_ref_pic_poc_lsb_sps: [u32; MAX_LONG_TERM_REF_PIC_SETS], + /// `used_by_curr_pic_lt_sps_flag[ i ]` equal to false specifies that the i-th + /// candidate long-term reference picture specified in the SPS is not used + /// for reference by a picture that includes in its long-term reference + /// picture set (RPS) the i-th candidate long-term reference picture + /// specified in the SPS. + pub used_by_curr_pic_lt_sps_flag: [bool; MAX_LONG_TERM_REF_PIC_SETS], + /// When set, specifies that slice_temporal_mvp_enabled_flag is present in + /// the slice headers of non-IDR pictures in the CVS. When not set, + /// specifies that slice_temporal_mvp_enabled_flag is not present in slice + /// headers and that temporal motion vector predictors are not used in the + /// CVS. + pub temporal_mvp_enabled_flag: bool, + /// When set, specifies that bi-linear interpolation is conditionally used + /// in the intraprediction filtering process in the CVS as specified in + /// clause 8.4.4.2.3. + pub strong_intra_smoothing_enabled_flag: bool, + /// When set, specifies that the vui_parameters( ) syntax structure as + /// specified in Annex E is present. When not set, specifies that the + /// vui_parameters( ) syntax structure as specified in Annex E is not + /// present. + pub vui_parameters_present_flag: bool, + /// The vui_parameters() data. + pub vui_parameters: VuiParams, + /// When set, specifies that the syntax elements sps_range_extension_flag, + /// sps_multilayer_extension_flag, sps_3d_extension_flag, + /// sps_scc_extension_flag, and sps_extension_4bits are present in the SPS + /// RBSP syntax structure. When not set, specifies that these syntax + /// elements are not present. + pub extension_present_flag: bool, + + pub range_extension_flag: bool, + /// The sps_range_extension() data. + pub range_extension: SpsRangeExtension, + /// When set, specifies that the sps_scc_extension( ) syntax structure is + /// present in the SPS RBSP syntax structure. When not set, specifies that + /// this syntax structure is not present + pub scc_extension_flag: bool, + /// The sps_scc_extension() data. + pub scc_extension: SpsSccExtension, + + // Internal H265 variables. Computed from the bitstream. + /// Equivalent to MinCbLog2SizeY in the specification. + pub min_cb_log2_size_y: u32, + /// Equivalent to CtbLog2SizeY in the specification. + pub ctb_log2_size_y: u32, + /// Equivalent to CtbSizeY in the specification. + pub ctb_size_y: u32, + /// Equivalent to PicHeightInCtbsY in the specification. + pub pic_height_in_ctbs_y: u32, + /// Equivalent to PicWidthInCtbsY in the specification. + pub pic_width_in_ctbs_y: u32, + /// Equivalent to PicSizeInCtbsY in the specification. + pub pic_size_in_ctbs_y: u32, + /// Equivalent to ChromaArrayType in the specification. + pub chroma_array_type: u8, + /// Equivalent to WpOffsetHalfRangeY in the specification. + pub wp_offset_half_range_y: u32, + /// Equivalent to WpOffsetHalfRangeC in the specification. + pub wp_offset_half_range_c: u32, + /// Equivalent to MaxTbLog2SizeY in the specification. + pub max_tb_log2_size_y: u32, + /// Equivalent to PicSizeInSamplesY in the specification. + pub pic_size_in_samples_y: u32, + + /// The VPS referenced by this SPS, if any. + pub vps: Option>, +} + +impl Sps { + pub fn max_dpb_size(&self) -> usize { + let max_luma_ps = self.profile_tier_level.max_luma_ps(); + let max_dpb_pic_buf = self.profile_tier_level.max_dpb_pic_buf(); + + // Equation A-2 + let max = if self.pic_size_in_samples_y <= (max_luma_ps >> 2) { + std::cmp::min(4 * max_dpb_pic_buf, 16) + } else if self.pic_size_in_samples_y <= (max_luma_ps >> 1) { + std::cmp::min(2 * max_dpb_pic_buf, 16) + } else if self.pic_size_in_samples_y <= ((3 * max_luma_ps) >> 2) { + std::cmp::min(4 * max_dpb_pic_buf / 3, 16) + } else { + max_dpb_pic_buf + }; + + max as usize + } + + pub fn width(&self) -> u16 { + self.pic_width_in_luma_samples + } + + pub fn height(&self) -> u16 { + self.pic_height_in_luma_samples + } + + pub fn visible_rectangle(&self) -> Rect { + // From the specification: + // NOTE 3 – The conformance cropping window offset parameters are + // only applied at the output. All internal decoding processes are + // applied to the uncropped picture size. + if !self.conformance_window_flag { + return Rect { + min: Point { x: 0, y: 0 }, + max: Point { x: u32::from(self.width()), y: u32::from(self.height()) }, + }; + } + const SUB_HEIGHT_C: [u32; 5] = [1, 2, 1, 1, 1]; + const SUB_WIDTH_C: [u32; 5] = [1, 2, 2, 1, 1]; + + let crop_unit_y = SUB_HEIGHT_C[usize::from(self.chroma_array_type)]; + let crop_unit_x = SUB_WIDTH_C[usize::from(self.chroma_array_type)]; + let crop_left = crop_unit_x * self.conf_win_left_offset; + let crop_right = crop_unit_x * self.conf_win_right_offset; + let crop_top = crop_unit_y * self.conf_win_top_offset; + let crop_bottom = crop_unit_y * self.conf_win_bottom_offset; + + Rect { + min: Point { x: crop_left, y: crop_top }, + max: Point { + x: u32::from(self.width()) - crop_left - crop_right, + y: u32::from(self.height()) - crop_top - crop_bottom, + }, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PpsSccExtension { + /// When set, specifies that a picture referring to the PPS may be included + /// in a reference picture list of a slice of the picture itself. If not + /// set, specifies that a picture referring to the PPS is never included in + /// a reference picture list of a slice of the picture itself. + pub curr_pic_ref_enabled_flag: bool, + /// When set, specifies that an adaptive colour transform may be applied to + /// the residual in the decoding process. When not set, specifies that + /// adaptive colour transform is not applied to the residual. + pub residual_adaptive_colour_transform_enabled_flag: bool, + /// When set, specifies that slice_act_y_qp_offset, slice_act_cb_qp_offset, + /// slice_act_cr_qp_offset are present in the slice header. When not set, + /// specifies that slice_act_y_qp_offset, slice_act_cb_qp_offset, + /// slice_act_cr_qp_offset are not present in the slice header. + pub slice_act_qp_offsets_present_flag: bool, + /// See the specificartion for more details. + pub act_y_qp_offset_plus5: i8, + /// See the specificartion for more details. + pub act_cb_qp_offset_plus5: i8, + /// See the specificartion for more details. + pub act_cr_qp_offset_plus3: i8, + /// When set, specifies that the palette predictor initializers used for the + /// pictures referring to the PPS are derived based on the palette predictor + /// initializers specified by the PPS. If not set, specifies that the + /// palette predictor initializers used for the pictures referring to the + /// PPS are inferred to be equal to those specified by the active SPS. + pub palette_predictor_initializers_present_flag: bool, + /// Specifies the number of entries in the picture palette predictor + /// initializer. + pub num_palette_predictor_initializers: u8, + /// When set, specifies that the pictures that refer to this PPS are + /// monochrome. If not set, specifies that the pictures that refer to this + /// PPS have multiple components. + pub monochrome_palette_flag: bool, + /// luma_bit_depth_entry_minus8 plus 8 specifies the bit depth of the luma + /// component of the entries of the palette predictor initializer. + pub luma_bit_depth_entry_minus8: u8, + /// chroma_bit_depth_entry_minus8 plus 8 specifies the bit depth of the + /// chroma components of the entries of the palette predictor initializer. + pub chroma_bit_depth_entry_minus8: u8, + /// `pps_palette_predictor_initializer[ comp ][ i ]` specifies the value of + /// the comp-th component of the i-th palette entry in the PPS that is used + /// to initialize the array PredictorPaletteEntries. + pub palette_predictor_initializer: [[u8; 128]; 3], +} + +impl Default for PpsSccExtension { + fn default() -> Self { + Self { + curr_pic_ref_enabled_flag: Default::default(), + residual_adaptive_colour_transform_enabled_flag: Default::default(), + slice_act_qp_offsets_present_flag: Default::default(), + act_y_qp_offset_plus5: Default::default(), + act_cb_qp_offset_plus5: Default::default(), + act_cr_qp_offset_plus3: Default::default(), + palette_predictor_initializers_present_flag: Default::default(), + num_palette_predictor_initializers: Default::default(), + monochrome_palette_flag: Default::default(), + luma_bit_depth_entry_minus8: Default::default(), + chroma_bit_depth_entry_minus8: Default::default(), + palette_predictor_initializer: [[0; 128]; 3], + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PpsRangeExtension { + /// log2_max_transform_skip_block_size_minus2 plus 2 specifies the maximum + /// transform block size for which transform_skip_flag may be present in + /// coded pictures referring to the PPS. When not present, the value of + /// log2_max_transform_skip_block_size_minus2 is inferred to be equal to 0. + /// When present, the value of log2_max_transform_skip_block_size_minus2 + /// shall be less than or equal to MaxTbLog2SizeY − 2. + pub log2_max_transform_skip_block_size_minus2: u32, + /// When set, specifies that log2_res_scale_abs_plus1 and + /// res_scale_sign_flag may be present in the transform unit syntax for + /// pictures referring to the PPS. When not set, specifies that + /// log2_res_scale_abs_plus1 and res_scale_sign_flag are not present for + /// pictures referring to the PPS. + pub cross_component_prediction_enabled_flag: bool, + /// When set, specifies that the cu_chroma_qp_offset_flag may be present in + /// the transform unit syntax. When not set, specifies that the + /// cu_chroma_qp_offset_flag is not present in the transform unit syntax. + pub chroma_qp_offset_list_enabled_flag: bool, + /// Specifies the difference between the luma CTB size and the minimum luma + /// coding block size of coding units that convey cu_chroma_qp_offset_flag. + pub diff_cu_chroma_qp_offset_depth: u32, + /// chroma_qp_offset_list_len_minus1 plus 1 specifies the number of + /// `cb_qp_offset_list[ i ]` and `cr_qp_offset_list[ i ]` syntax elements that + /// are present in the PPS. + pub chroma_qp_offset_list_len_minus1: u32, + /// Specify offsets used in the derivation of Qp′Cb and Qp′Cr, respectively. + pub cb_qp_offset_list: [i32; 6], + /// Specify offsets used in the derivation of Qp′Cb and Qp′Cr, respectively. + pub cr_qp_offset_list: [i32; 6], + /// The base 2 logarithm of the scaling parameter that is used to scale + /// sample adaptive offset (SAO) offset values for luma samples. + pub log2_sao_offset_scale_luma: u32, + /// The base 2 logarithm of the scaling parameter that is used to scale SAO + /// offset values for chroma samples. + pub log2_sao_offset_scale_chroma: u32, +} + +/// A H.265 Picture Parameter Set. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pps { + /// Identifies the PPS for reference by other syntax elements. + pub pic_parameter_set_id: u8, + /// Specifies the value of sps_seq_parameter_set_id for the active SPS. + pub seq_parameter_set_id: u8, + /// When set, specifies the presence of the syntax element + /// dependent_slice_segment_flag in the slice segment headers for coded + /// pictures referring to the PPS. When not set, specifies the absence of + /// the syntax element dependent_slice_segment_flag in the slice segment + /// headers for coded pictures referring to the PPS. + pub dependent_slice_segments_enabled_flag: bool, + /// When set, indicates that the pic_output_flag syntax element is present + /// in the associated slice headers. When not set, indicates that the + /// pic_output_flag syntax element is not present in the associated slice + /// headers. + pub output_flag_present_flag: bool, + /// Specifies the number of extra slice header bits that are present in the + /// slice header RBSP for coded pictures referring to the PPS. + pub num_extra_slice_header_bits: u8, + /// When not set, specifies that sign bit hiding is disabled. Whens set, + /// specifies that sign bit hiding is enabled. + pub sign_data_hiding_enabled_flag: bool, + /// When set, specifies that cabac_init_flag is present in slice headers + /// referring to the PPS. When not set, specifies that cabac_init_flag is + /// not present in slice headers referring to the PPS. + pub cabac_init_present_flag: bool, + /// Specifies the inferred value of num_ref_idx_l0_active_minus1 for P and B + /// slices with num_ref_idx_active_override_flag not set. + pub num_ref_idx_l0_default_active_minus1: u8, + /// Specifies the inferred value of num_ref_idx_l1_active_minus1 for B + /// slices with num_ref_idx_active_override_flag not set. + pub num_ref_idx_l1_default_active_minus1: u8, + /// init_qp_minus26 plus 26 specifies the initial value of SliceQpY for each + /// slice referring to the PPS. The initial value of SliceQpY is modified at + /// the slice segment layer when a non-zero value of slice_qp_delta is + /// decoded. + pub init_qp_minus26: i8, + /// When not set, specifies that intra prediction allows usage of residual + /// data and decoded samples of neighbouring coding blocks coded using + /// either intra or inter prediction modes. When set, specifies constrained + /// intra prediction, in which case intra prediction only uses residual data + /// and decoded samples from neighbouring coding blocks coded using intra + /// prediction modes. + pub constrained_intra_pred_flag: bool, + /// When set, specifies that transform_skip_flag may be present in the + /// residual coding syntax. When not set, specifies that transform_skip_flag + /// is not present in the residual coding syntax. + pub transform_skip_enabled_flag: bool, + /// When set, specifies that the diff_cu_qp_delta_depth syntax element is + /// present in the PPS and that cu_qp_delta_abs may be present in the + /// transform unit syntax and the palette syntax. When not set, specifies + /// that the diff_cu_qp_delta_depth syntax element is not present in the PPS + /// and that cu_qp_delta_abs is not present in the transform unit syntax and + /// the palette syntax. + pub cu_qp_delta_enabled_flag: bool, + + /*if cu_qp_delta_enabled_flag */ + /// Specifies the difference between the luma CTB size and the minimum luma + /// coding block size of coding units that convey cu_qp_delta_abs and + /// cu_qp_delta_sign_flag. + pub diff_cu_qp_delta_depth: u8, + /// Specifies the offsets to the luma quantization parameter Qp′Y used for + /// deriving Qp′Cb and Qp′Cr, respectively. + pub cb_qp_offset: i8, + /// Specifies the offsets to the luma quantization parameter Qp′Y used for + /// deriving Qp′Cb and Qp′Cr, respectively. + pub cr_qp_offset: i8, + /// When set, indicates that the slice_cb_qp_offset and slice_cr_qp_offset + /// syntax elements are present in the associated slice headers. When not + /// set, indicates that these syntax elements are not present in the + /// associated slice headers. When ChromaArrayType is equal to 0, + /// pps_slice_chroma_qp_offsets_present_flag shall be equal to 0 + pub slice_chroma_qp_offsets_present_flag: bool, + /// When not set, specifies that weighted prediction is not applied to P + /// slices. When set, specifies that weighted prediction is applied to P + /// slices. + pub weighted_pred_flag: bool, + /// When not set, specifies that the default weighted prediction is applied + /// to B slices. When set, specifies that weighted prediction is applied to + /// B slices. + pub weighted_bipred_flag: bool, + /// When set, specifies that `cu_transquant_bypass_flag` is present, When + /// not set, specifies that `cu_transquant_bypass_flag` is not present. + pub transquant_bypass_enabled_flag: bool, + /// When set, specifies that there is more than one tile in each picture + /// referring to the PPS. When not set, specifies that there is only one + /// tile in each picture referring to the PPS. + pub tiles_enabled_flag: bool, + /// When set, specifies that a specific synchronization process for context + /// variables, and when applicable, Rice parameter initialization states and + /// palette predictor variables, is invoked before decoding the CTU which + /// includes the first CTB of a row of CTBs in each tile in each picture + /// referring to the PPS, and a specific storage process for context + /// variables, and when applicable, Rice parameter initialization states and + /// palette predictor variables, is invoked after decoding the CTU which + /// includes the second CTB of a row of CTBs in each tile in each picture + /// referring to the PPS. When not set, specifies that no specific + /// synchronization process for context variables, and when applicable, Rice + /// parameter initialization states and palette predictor variables, is + /// required to be invoked before decoding the CTU which includes the first + /// CTB of a row of CTBs in each tile in each picture referring to the PPS, + /// and no specific storage process for context variables, and when + /// applicable, Rice parameter initialization states and palette predictor + /// variables, is required to be invoked after decoding the CTU which + /// includes the second CTB of a row of CTBs in each tile in each picture + /// referring to the PPS. + pub entropy_coding_sync_enabled_flag: bool, + /// num_tile_columns_minus1 plus 1 specifies the number of tile columns + /// partitioning the picture. + pub num_tile_columns_minus1: u8, + /// num_tile_rows_minus1 plus 1 specifies the number of tile rows + /// partitioning the picture. + pub num_tile_rows_minus1: u8, + /// When set, specifies that tile column boundaries and likewise tile row + /// boundaries are distributed uniformly across the picture. When not set, + /// specifies that tile column boundaries and likewise tile row boundaries + /// are not distributed uniformly across the picture but signalled + /// explicitly using the syntax elements `column_width_minus1[ i ]` and + /// `row_height_minus1[ i ]`. + pub uniform_spacing_flag: bool, + /// `column_width_minus1[ i ]` plus 1 specifies the width of the i-th tile + /// column in units of CTBs. + pub column_width_minus1: [u32; 19], + /// `row_height_minus1[ i ]` plus 1 specifies the height of the i-th tile row + /// in units of CTBs. + pub row_height_minus1: [u32; 21], + /// When set, specifies that in-loop filtering operations may be performed + /// across tile boundaries in pictures referring to the PPS. When not set, + /// specifies that in-loop filtering operations are not performed across + /// tile boundaries in pictures referring to the PPS. The in-loop filtering + /// operations include the deblocking filter and sample adaptive offset + /// filter operations. + pub loop_filter_across_tiles_enabled_flag: bool, + /// When set, specifies that in-loop filtering operations may be performed + /// across left and upper boundaries of slices referring to the PPS. When + /// not set, specifies that in-loop filtering operations are not performed + /// across left and upper boundaries of slices referring to the PPS. The in- + /// loop filtering operations include the deblocking filter and sample + /// adaptive offset filter operations. + pub loop_filter_across_slices_enabled_flag: bool, + /// When set, specifies the presence of deblocking filter control syntax + /// elements in the PPS. When not set, specifies the absence of deblocking + /// filter control syntax elements in the PPS. + pub deblocking_filter_control_present_flag: bool, + /// When set, specifies the presence of deblocking_filter_override_flag in + /// the slice headers for pictures referring to the PPS. When not set, + /// specifies the absence of deblocking_filter_override_flag in the slice + /// headers for pictures referring to the PPS. + pub deblocking_filter_override_enabled_flag: bool, + /// When set, specifies that the operation of deblocking filter is not + /// applied for slices referring to the PPS in which + /// slice_deblocking_filter_disabled_flag is not present. When not set, + /// specifies that the operation of the deblocking filter is applied for + /// slices referring to the PPS in which + /// slice_deblocking_filter_disabled_flag is not present. + pub deblocking_filter_disabled_flag: bool, + /// Specify the default deblocking parameter offsets for β and tC (divided + /// by 2) that are applied for slices referring to the PPS, unless the + /// default deblocking parameter offsets are overridden by the deblocking + /// parameter offsets present in the slice headers of the slices referring + /// to the PPS. + pub beta_offset_div2: i8, + /// Specify the default deblocking parameter offsets for β and tC (divided + /// by 2) that are applied for slices referring to the PPS, unless the + /// default deblocking parameter offsets are overridden by the deblocking + /// parameter offsets present in the slice headers of the slices referring + /// to the PPS. + pub tc_offset_div2: i8, + /// When set, specifies that the scaling list data used for the pictures + /// referring to the PPS are derived based on the scaling lists specified by + /// the active SPS and the scaling lists specified by the PPS. + /// pps_scaling_list_data_present_flag equal to 0 specifies that the scaling + /// list data used for the pictures referring to the PPS are inferred to be + /// equal to those specified by the active SPS. + pub scaling_list_data_present_flag: bool, + /// The scaling list data. + pub scaling_list: ScalingLists, + /// When set, specifies that the syntax structure + /// ref_pic_lists_modification( ) is present in the slice segment header. + /// When not set, specifies that the syntax structure + /// ref_pic_lists_modification( ) is not present in the slice segment header + pub lists_modification_present_flag: bool, + /// log2_parallel_merge_level_minus2 plus 2 specifies the value of the + /// variable Log2ParMrgLevel, which is used in the derivation process for + /// luma motion vectors for merge mode as specified in clause 8.5.3.2.2 and + /// the derivation process for spatial merging candidates as specified in + /// clause 8.5.3.2.3. + pub log2_parallel_merge_level_minus2: u8, + /// When not set, specifies that no slice segment header extension syntax + /// elements are present in the slice segment headers for coded pictures + /// referring to the PPS. When set, specifies that slice segment header + /// extension syntax elements are present in the slice segment headers for + /// coded pictures referring to the PPS. + pub slice_segment_header_extension_present_flag: bool, + /// When set, specifies that the syntax elements pps_range_extension_flag, + /// pps_multilayer_extension_flag, pps_3d_extension_flag, + /// pps_scc_extension_flag, and pps_extension_4bits are present in the + /// picture parameter set RBSP syntax structure. When not set, specifies + /// that these syntax elements are not present. + pub extension_present_flag: bool, + /// When setspecifies that the pps_range_extension( ) syntax structure is + /// present in the PPS RBSP syntax structure. When not set, specifies that + /// this syntax structure is not present. + pub range_extension_flag: bool, + /// The range extension data. + pub range_extension: PpsRangeExtension, + + pub scc_extension_flag: bool, + /// The SCC extension data. + pub scc_extension: PpsSccExtension, + + // Internal variables. + /// Equivalent to QpBdOffsetY in the specification. + pub qp_bd_offset_y: u32, + + /// The SPS referenced by this PPS. + pub sps: Rc, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScalingLists { + /// plus 8 specifies the value of the variable `ScalingFactor[ 2 ][ matrixId + /// ] [ 0 ][ 0 ]` for the scaling list for the 16x16 size. + pub scaling_list_dc_coef_minus8_16x16: [i16; 6], + /// plus 8 specifies the value of the variable `ScalingFactor[ 3 ][ matrixId + /// ][ 0 ][ 0 ]` for the scaling list for the 32x32 size. + pub scaling_list_dc_coef_minus8_32x32: [i16; 6], + /// The 4x4 scaling list. + pub scaling_list_4x4: [[u8; 16]; 6], + /// The 8x8 scaling list. + pub scaling_list_8x8: [[u8; 64]; 6], + /// The 16x16 scaling list. + pub scaling_list_16x16: [[u8; 64]; 6], + /// The 32x32 scaling list. + pub scaling_list_32x32: [[u8; 64]; 6], +} + +impl Default for ScalingLists { + fn default() -> Self { + Self { + scaling_list_dc_coef_minus8_16x16: Default::default(), + scaling_list_dc_coef_minus8_32x32: Default::default(), + scaling_list_4x4: Default::default(), + scaling_list_8x8: [[0; 64]; 6], + scaling_list_16x16: [[0; 64]; 6], + scaling_list_32x32: [[0; 64]; 6], + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RefPicListModification { + /// Whenset, indicates that reference picture list 0 is specified explicitly + /// by a list of `list_entry_l0[ i ]` values. When not set, indicates that + /// reference picture list 0 is determined implicitly. + pub ref_pic_list_modification_flag_l0: bool, + /// `list_entry_l0[ i ]` specifies the index of the reference picture in + /// RefPicListTemp0 to be placed at the current position of reference + /// picture list 0. + pub list_entry_l0: Vec, + /// Whenset, indicates that reference picture list 1 is specified explicitly + /// by a list of `list_entry_l1[ i ]` values. When not set, indicates that + /// reference picture list 1 is determined implicitly. + pub ref_pic_list_modification_flag_l1: bool, + /// `list_entry_l1[ i ]` specifies the index of the reference picture in + /// RefPicListTemp1 to be placed at the current position of reference + /// picture list 1. + pub list_entry_l1: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PredWeightTable { + /// The base 2 logarithm of the denominator for all luma weighting factors. + pub luma_log2_weight_denom: u8, + /// The difference of the base 2 logarithm of the denominator for all chroma + /// weighting factors. + pub delta_chroma_log2_weight_denom: i8, + /// `luma_weight_l0_flag[ i ]` set specifies that weighting factors for the + /// luma component of list 0 prediction using `RefPicList0[ i ]` are present. + /// `luma_weight_l0_flag[ i ]` not set specifies that these weighting factors + /// are not present. + pub luma_weight_l0_flag: [bool; 15], + /// `chroma_weight_l0_flag[ i ]` set specifies that weighting factors for the + /// chroma prediction values of list 0 prediction using `RefPicList0[ i ]` are + /// present. `chroma_weight_l0_flag[ i ]` not set specifies that these + /// weighting factors are not present. + pub chroma_weight_l0_flag: [bool; 15], + /// `delta_luma_weight_l0[ i ]` is the difference of the weighting factor + /// applied to the luma prediction value for list 0 prediction using + /// `RefPicList0[ i ]`. + pub delta_luma_weight_l0: [i8; 15], + /// `luma_offset_l0[ i ]` is the additive offset applied to the luma + /// prediction value for list 0 prediction using `RefPicList0[ i ]`. + pub luma_offset_l0: [i8; 15], + /// `delta_chroma_weight_l0[ i ][ j ]` is the difference of the weighting + /// factor applied to the chroma prediction values for list 0 prediction + /// using `RefPicList0[ i ]` with j equal to 0 for Cb and j equal to 1 for Cr. + pub delta_chroma_weight_l0: [[i8; 2]; 15], + /// `delta_chroma_offset_l0[ i ][ j ]` is the difference of the additive + /// offset applied to the chroma prediction values for list 0 prediction + /// using `RefPicList0[ i ]` with j equal to 0 for Cb and j equal to 1 for Cr. + pub delta_chroma_offset_l0: [[i16; 2]; 15], + + // `luma_weight_l1_flag[ i ]`, `chroma_weight_l1_flag[ i ]`, + // `delta_luma_weight_l1[ i ]`, `luma_offset_l1[ i ]`, delta_chroma_weight_l1[ i + // `][ j ]` and `delta_chroma_offset_l1[ i ]`[ j ] have the same + // `semanticsasluma_weight_l0_flag[ i ]`, `chroma_weight_l0_flag[ i ]`, + // `delta_luma_weight_l0[ i ]`, `luma_offset_l0[ i ]`, `delta_chroma_weight_l0[ i + // ][ j ]` and `delta_chroma_offset_l0[ i ][ j ]`, respectively, with `l0`, `L0`, + // `list 0` and `List0` replaced by `l1`, `L1`, `list 1` and `List1`, respectively. + pub luma_weight_l1_flag: [bool; 15], + pub chroma_weight_l1_flag: [bool; 15], + pub delta_luma_weight_l1: [i8; 15], + pub luma_offset_l1: [i8; 15], + + pub delta_chroma_weight_l1: [[i8; 2]; 15], + pub delta_chroma_offset_l1: [[i16; 2]; 15], + + // Calculated. + /// Same as ChromaLog2WeightDenom in the specification. + pub chroma_log2_weight_denom: u8, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ShortTermRefPicSet { + /// When set, specifies that the stRpsIdx-th candidate short-term RPS is + /// predicted from another candidate short-term RPS, which is referred to as + /// the source candidate short-term RPS. + pub inter_ref_pic_set_prediction_flag: bool, + /// delta_idx_minus1 plus 1 specifies the difference between the value of + /// stRpsIdx and the index, into the list of the candidate short-term RPSs + /// specified in the SPS, of the source candidate short-term RPS. + pub delta_idx_minus1: u8, + /// delta_rps_sign and abs_delta_rps_minus1 together specify the value of + /// the variable deltaRps. + pub delta_rps_sign: bool, + /// delta_rps_sign and abs_delta_rps_minus1 together specify the value of + /// the variable deltaRps. + pub abs_delta_rps_minus1: u16, + /// specifies the number of entries in the stRpsIdx-th candidate short-term + /// RPS that have picture order count values less than the picture order + /// count value of the current picture. + pub num_negative_pics: u8, + /// specifies the number of entries in the stRpsIdx-th candidate short-term + /// RPS that have picture order count values greater than the picture order + /// count value of the current picture. + pub num_positive_pics: u8, + /// Same as UsedByCurrPicS0 in the specification. + pub used_by_curr_pic_s0: [bool; MAX_SHORT_TERM_REF_PIC_SETS], + /// Same as UsedByCurrPicS1 in the specification. + pub used_by_curr_pic_s1: [bool; MAX_SHORT_TERM_REF_PIC_SETS], + /// Same as DeltaPocS0 in the specification. + pub delta_poc_s0: [i32; MAX_SHORT_TERM_REF_PIC_SETS], + /// Same as DeltaPocS1 in the specification. + pub delta_poc_s1: [i32; MAX_SHORT_TERM_REF_PIC_SETS], + /// Same as NumDeltaPocs in the specification. + pub num_delta_pocs: u32, +} + +impl Default for ShortTermRefPicSet { + fn default() -> Self { + Self { + inter_ref_pic_set_prediction_flag: Default::default(), + delta_idx_minus1: Default::default(), + delta_rps_sign: Default::default(), + abs_delta_rps_minus1: Default::default(), + num_negative_pics: Default::default(), + num_positive_pics: Default::default(), + used_by_curr_pic_s0: [false; MAX_SHORT_TERM_REF_PIC_SETS], + used_by_curr_pic_s1: [false; MAX_SHORT_TERM_REF_PIC_SETS], + delta_poc_s0: [0; MAX_SHORT_TERM_REF_PIC_SETS], + delta_poc_s1: [0; MAX_SHORT_TERM_REF_PIC_SETS], + num_delta_pocs: Default::default(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// See table 7-7 in the specification. +pub enum SliceType { + B = 0, + P = 1, + I = 2, +} + +impl TryFrom for SliceType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(SliceType::B), + 1 => Ok(SliceType::P), + 2 => Ok(SliceType::I), + _ => Err(format!("Invalid SliceType {}", value)), + } + } +} + +impl SliceType { + /// Whether this is a P slice. See table 7-7 in the specification. + pub fn is_p(&self) -> bool { + matches!(self, SliceType::P) + } + + /// Whether this is a B slice. See table 7-7 in the specification. + pub fn is_b(&self) -> bool { + matches!(self, SliceType::B) + } + + /// Whether this is an I slice. See table 7-7 in the specification. + pub fn is_i(&self) -> bool { + matches!(self, SliceType::I) + } +} + +impl Default for SliceType { + fn default() -> Self { + Self::P + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SliceHeader { + /// When set, specifies that the slice segment is the first slice segment of + /// the picture in decoding order. When not set, specifies that the slice + /// segment is not the first slice segment of the picture in decoding order. + pub first_slice_segment_in_pic_flag: bool, + /// Affects the output of previously-decoded pictures in the decoded picture + /// buffer after the decoding of an IDR or a BLA picture that is not the + /// first picture in the bitstream as specified in Annex C. + pub no_output_of_prior_pics_flag: bool, + /// Specifies the value of pps_pic_parameter_set_id for the PPS in use. + pub pic_parameter_set_id: u8, + /// When set, specifies that the value of each slice segment header syntax + /// element that is not present is inferred to be equal to the value of the + /// corresponding slice segment header syntax element in the slice header. + pub dependent_slice_segment_flag: bool, + /// Specifies the address of the first CTB in the slice segment, in CTB + /// raster scan of a picture. + pub segment_address: u32, + /// Specifies the coding type of the slice according to Table 7-7. + pub type_: SliceType, + /// Affects the decoded picture output and removal processes as specified in + /// Annex C. + pub pic_output_flag: bool, + /// Specifies the colour plane associated with the current slice RBSP when + /// separate_colour_plane_flag is set. The value of colour_plane_id shall be + /// in the range of 0 to 2, inclusive. colour_plane_id values 0, 1 and 2 + /// correspond to the Y, Cb and Cr planes, respectively. + pub colour_plane_id: u8, + /// Specifies the picture order count modulo MaxPicOrderCntLsb for the + /// current picture. The length of the slice_pic_order_cnt_lsb syntax + /// element is log2_max_pic_order_cnt_lsb_minus4 + 4 bits. + pub pic_order_cnt_lsb: u16, + /// When set, specifies that the short-term RPS of the current picture is + /// derived based on one of the st_ref_pic_set( ) syntax structures in the + /// active SPS that is identified by the syntax element + /// short_term_ref_pic_set_idx in the slice header. When not set, specifies + /// that the short-term RPS of the current picture is derived based on the + /// st_ref_pic_set( ) syntax structure that is directly included in the + /// slice headers of the current picture. + pub short_term_ref_pic_set_sps_flag: bool, + /// The st_ref_pic_set() data. + pub short_term_ref_pic_set: ShortTermRefPicSet, + /// Specifies the index, into the list of the st_ref_pic_set( ) syntax + /// structures included in the active SPS, of the st_ref_pic_set( ) syntax + /// structure that is used for derivation of the short-term RPS of the + /// current picture. + pub short_term_ref_pic_set_idx: u8, + /// Specifies the number of entries in the long-term RPS of the current + /// picture that are derived based on the candidate long-term reference + /// pictures specified in the active SPS. + pub num_long_term_sps: u8, + /// Specifies the number of entries in the long-term RPS of the current + /// picture that are directly signalled in the slice header. + pub num_long_term_pics: u8, + /// `lt_idx_sps[ i ]` specifies an index, into the list of candidate long-term + /// reference pictures specified in the active SPS, of the i-th entry in the + /// long-term RPS of the current picture. + pub lt_idx_sps: [u8; 16], + /// Same as PocLsbLt in the specification. + pub poc_lsb_lt: [u32; 16], + /// Same as UsedByCurrPicLt in the specification. + pub used_by_curr_pic_lt: [bool; 16], + /// When set, specifies that that `delta_poc_msb_cycle_lt[i]` is present. + pub delta_poc_msb_present_flag: [bool; 16], + /// Same as DeltaPocMsbCycleLt in the specification. + pub delta_poc_msb_cycle_lt: [u32; 16], + /// Specifies whether temporal motion vector predictors can be used for + /// inter prediction. If slice_temporal_mvp_enabled_flag is not set, the + /// syntax elements of the current picture shall be constrained such that no + /// temporal motion vector predictor is used in decoding of the current + /// picture. Otherwise (slice_temporal_mvp_enabled_flag is set), temporal + /// motion vector predictors may be used in decoding of the current picture. + pub temporal_mvp_enabled_flag: bool, + /// When set, specifies that SAO is enabled for the luma component in the + /// current slice; slice_sao_luma_flag not set specifies that SAO is + /// disabled for the luma component in the current slice. + pub sao_luma_flag: bool, + /// When set, specifies that SAO is enabled for the chroma component in the + /// current slice; When not set, specifies that SAO is disabled for the + /// chroma component in the current slice. + pub sao_chroma_flag: bool, + /// When set, specifies that the syntax element num_ref_idx_l0_active_minus1 + /// is present for P and B slices and that the syntax element + /// num_ref_idx_l1_active_minus1 is present for B slices. When not set, + /// specifies that the syntax elements num_ref_idx_l0_active_minus1 and + /// num_ref_idx_l1_active_minus1 are not present. + pub num_ref_idx_active_override_flag: bool, + /// Specifies the maximum reference index for + /// reference picture list 0 that may be used to decode the slice. + pub num_ref_idx_l0_active_minus1: u8, + /// Specifies the maximum reference index for reference picture list 1 that + /// may be used to decode the slice. + pub num_ref_idx_l1_active_minus1: u8, + /// The RefPicListModification data. + pub ref_pic_list_modification: RefPicListModification, + /// When set, indicates that the mvd_coding( x0, y0, 1 ) syntax structure is + /// not parsed and `MvdL1[ x0 ]`[ y0 `][ compIdx ]` is set equal to 0 for + /// compIdx = 0..1. When not set, indicates that the mvd_coding( x0, y0, 1 ) + /// syntax structure is parsed. + pub mvd_l1_zero_flag: bool, + /// Specifies the method for determining the initialization table used in + /// the initialization process for context variables. + pub cabac_init_flag: bool, + /// When set, specifies that the collocated picture used for temporal motion + /// vector prediction is derived from reference picture list 0. When not + /// set, specifies that the collocated picture used for temporal motion + /// vector prediction is derived from reference picture list 1. + pub collocated_from_l0_flag: bool, + /// Specifies the reference index of the collocated picture used for + /// temporal motion vector prediction. + pub collocated_ref_idx: u8, + /// The PredWeightTable data. + pub pred_weight_table: PredWeightTable, + /// Specifies the maximum number of merging motion vector prediction (MVP) + /// candidates supported in the slice subtracted from 5. + pub five_minus_max_num_merge_cand: u8, + /// Specifies that the resolution of motion vectors for inter prediction in + /// the current slice is integer. When not set, specifies + /// that the resolution of motion vectors for inter prediction in the + /// current slice that refer to pictures other than the current picture is + /// fractional with quarter-sample precision in units of luma samples. + pub use_integer_mv_flag: bool, + /// Specifies the initial value of QpY to be used for the coding blocks in + /// the slice until modified by the value of CuQpDeltaVal in the coding unit + /// layer. + pub qp_delta: i8, + /// Specifies a difference to be added to the value of pps_cb_qp_offset when + /// determining the value of the Qp′Cb quantization parameter. + pub cb_qp_offset: i8, + /// Specifies a difference to be added to the value of pps_cb_qr_offset when + /// determining the value of the Qp′Cr quantization parameter. + pub cr_qp_offset: i8, + /// Specifies offsets to the quantization parameter values qP derived in + /// clause 8.6.2 for luma, Cb, and Cr components, respectively. + pub slice_act_y_qp_offset: i8, + /// Specifies offsets to the quantization parameter values qP derived in + /// clause 8.6.2 for luma, Cb, and Cr components, respectively. + pub slice_act_cb_qp_offset: i8, + /// Specifies offsets to the quantization parameter values qP derived in + /// clause 8.6.2 for luma, Cb, and Cr components, respectively. + pub slice_act_cr_qp_offset: i8, + /// When set, specifies that the cu_chroma_qp_offset_flag may be present in + /// the transform unit syntax. When not set, specifies that the + /// cu_chroma_qp_offset_flag is not present in the transform unit syntax. + pub cu_chroma_qp_offset_enabled_flag: bool, + /// When set, specifies that deblocking parameters are present in the slice + /// header. When not set, specifies that deblocking parameters are not + /// present in the slice header. + pub deblocking_filter_override_flag: bool, + /// When set, specifies that the operation of the deblocking filter is not + /// applied for the current slice. When not set, specifies that the + /// operation of the deblocking filter is applied for the current slice. + pub deblocking_filter_disabled_flag: bool, + /// Specifies the deblocking parameter offsets for β and tC (divided by 2) + /// for the current slice. + pub beta_offset_div2: i8, + /// Specifies the deblocking parameter offsets for β and tC (divided by 2) + /// for the current slice. + pub tc_offset_div2: i8, + /// When set, specifies that in-loop filtering operations may be performed + /// across the left and upper boundaries of the current slice. When not + /// set, specifies that in-loop operations are not performed across left and + /// upper boundaries of the current slice. The in-loop filtering operations + /// include the deblocking filter and sample adaptive offset filter. + pub loop_filter_across_slices_enabled_flag: bool, + /// Specifies the number of `entry_point_offset_minus1[ i ]` syntax elements + /// in the slice header. + pub num_entry_point_offsets: u32, + /// offset_len_minus1 plus 1 specifies the length, in bits, of the + /// `entry_point_offset_minus1[ i ]` syntax elements. + pub offset_len_minus1: u8, + /// `entry_point_offset_minus1[ i ]` plus 1 specifies the i-th entry point + /// offset in bytes, and is represented by offset_len_minus1 plus 1 bits. + /// The slice segment data that follow the slice segment header consists of + /// num_entry_point_offsets + 1 subsets, with subset index values ranging + /// from 0 to num_entry_point_offsets, inclusive. See the specification for + /// more details. + pub entry_point_offset_minus1: [u32; 32], + /// Same as NumPicTotalCurr in the specification. + pub num_pic_total_curr: u32, + // Size of slice_header() in bits. + pub header_bit_size: u32, + // Number of emulation prevention bytes (EPB) in this slice_header(). + pub n_emulation_prevention_bytes: u32, + /// Same as CurrRpsIdx in the specification. + pub curr_rps_idx: u8, + /// Number of bits taken by st_ref_pic_set minus Emulation Prevention Bytes. + pub st_rps_bits: u32, +} + +impl Default for SliceHeader { + fn default() -> Self { + Self { + first_slice_segment_in_pic_flag: Default::default(), + no_output_of_prior_pics_flag: Default::default(), + pic_parameter_set_id: Default::default(), + dependent_slice_segment_flag: Default::default(), + segment_address: Default::default(), + type_: Default::default(), + pic_output_flag: true, + colour_plane_id: Default::default(), + pic_order_cnt_lsb: Default::default(), + short_term_ref_pic_set_sps_flag: Default::default(), + short_term_ref_pic_set: Default::default(), + short_term_ref_pic_set_idx: Default::default(), + num_long_term_sps: Default::default(), + num_long_term_pics: Default::default(), + lt_idx_sps: Default::default(), + poc_lsb_lt: Default::default(), + used_by_curr_pic_lt: Default::default(), + delta_poc_msb_present_flag: Default::default(), + delta_poc_msb_cycle_lt: Default::default(), + temporal_mvp_enabled_flag: Default::default(), + sao_luma_flag: Default::default(), + sao_chroma_flag: Default::default(), + num_ref_idx_active_override_flag: Default::default(), + num_ref_idx_l0_active_minus1: Default::default(), + num_ref_idx_l1_active_minus1: Default::default(), + ref_pic_list_modification: Default::default(), + mvd_l1_zero_flag: Default::default(), + cabac_init_flag: Default::default(), + collocated_from_l0_flag: true, + collocated_ref_idx: Default::default(), + pred_weight_table: Default::default(), + five_minus_max_num_merge_cand: Default::default(), + use_integer_mv_flag: Default::default(), + qp_delta: Default::default(), + cb_qp_offset: Default::default(), + cr_qp_offset: Default::default(), + slice_act_y_qp_offset: Default::default(), + slice_act_cb_qp_offset: Default::default(), + slice_act_cr_qp_offset: Default::default(), + cu_chroma_qp_offset_enabled_flag: Default::default(), + deblocking_filter_override_flag: Default::default(), + deblocking_filter_disabled_flag: Default::default(), + beta_offset_div2: Default::default(), + tc_offset_div2: Default::default(), + loop_filter_across_slices_enabled_flag: Default::default(), + num_entry_point_offsets: Default::default(), + offset_len_minus1: Default::default(), + entry_point_offset_minus1: Default::default(), + num_pic_total_curr: Default::default(), + header_bit_size: Default::default(), + n_emulation_prevention_bytes: Default::default(), + curr_rps_idx: Default::default(), + st_rps_bits: Default::default(), + } + } +} + +/// A H265 slice. An integer number of macroblocks or macroblock pairs ordered +/// consecutively in the raster scan within a particular slice group +pub struct Slice<'a> { + /// The slice header. + pub header: SliceHeader, + /// The NAL unit backing this slice. + pub nalu: Nalu<'a>, +} + +impl<'a> Slice<'a> { + /// Sets the header for dependent slices by copying from an independent + /// slice. + pub fn replace_header(&mut self, header: SliceHeader) -> Result<(), String> { + if !self.header.dependent_slice_segment_flag { + Err("Replacing the slice header is only possible for dependent slices".into()) + } else { + let first_slice_segment_in_pic_flag = self.header.first_slice_segment_in_pic_flag; + let no_output_of_prior_pics_flag = self.header.no_output_of_prior_pics_flag; + let pic_parameter_set_id = self.header.pic_parameter_set_id; + let dependent_slice_segment_flag = self.header.dependent_slice_segment_flag; + let segment_address = self.header.segment_address; + + let offset_len_minus1 = self.header.offset_len_minus1; + let entry_point_offset_minus1 = self.header.entry_point_offset_minus1; + let num_pic_total_curr = self.header.num_pic_total_curr; + let header_bit_size = self.header.header_bit_size; + let n_emulation_prevention_bytes = self.header.n_emulation_prevention_bytes; + let curr_rps_idx = self.header.curr_rps_idx; + let st_rps_bits = self.header.st_rps_bits; + + self.header = header; + + self.header.first_slice_segment_in_pic_flag = first_slice_segment_in_pic_flag; + self.header.no_output_of_prior_pics_flag = no_output_of_prior_pics_flag; + self.header.pic_parameter_set_id = pic_parameter_set_id; + self.header.dependent_slice_segment_flag = dependent_slice_segment_flag; + self.header.segment_address = segment_address; + self.header.offset_len_minus1 = offset_len_minus1; + self.header.entry_point_offset_minus1 = entry_point_offset_minus1; + self.header.num_pic_total_curr = num_pic_total_curr; + self.header.header_bit_size = header_bit_size; + self.header.n_emulation_prevention_bytes = n_emulation_prevention_bytes; + self.header.curr_rps_idx = curr_rps_idx; + self.header.st_rps_bits = st_rps_bits; + + Ok(()) + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SublayerHrdParameters { + // NOTE: The value of CpbCnt is cpb_cnt_minus1[i] + 1, and cpb_cnt_minus1 + // ranges from 0..=31 + /// `bit_rate_value_minus1[ i ]` (together with bit_rate_scale) specifies the + /// maximum input bit rate for the i-th CPB when the CPB operates at the + /// access unit level + pub bit_rate_value_minus1: [u32; 32], + /// `cpb_size_value_minus1[ i ]` is used together with cpb_size_scale to + /// specify the i-th CPB size when the CPB operates at the access unit + /// level. + pub cpb_size_value_minus1: [u32; 32], + /// `cpb_size_du_value_minus1[ i ]` is used together with cpb_size_du_scale to + /// specify the i-th CPB size when the CPB operates at sub-picture level. + pub cpb_size_du_value_minus1: [u32; 32], + /// `bit_rate_du_value_minus1[ i ]` (together with bit_rate_scale) specifies + /// the maximum input bit rate for the i-th CPB when the CPB operates at the + /// sub-picture level. + pub bit_rate_du_value_minus1: [u32; 32], + /// `cbr_flag[ i ]` not set specifies that to decode this CVS by the HRD using + /// the i-th CPB specification. + pub cbr_flag: [bool; 32], +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HrdParams { + /// When set, specifies that NAL HRD parameters (pertaining to the Type II + /// bitstream conformance point) are present in the hrd_parameters( ) syntax + /// structure. When not set, specifies that NAL HRD parameters are not + /// present in the hrd_parameters( ) syntax structure. + pub nal_hrd_parameters_present_flag: bool, + /// When set, specifies that VCL HRD parameters (pertaining to the Type I + /// bitstream conformance point) are present in the hrd_parameters( ) syntax + /// structure. When not set, specifies that VCL HRD parameters are not + /// present in the hrd_parameters( ) syntax structure. + pub vcl_hrd_parameters_present_flag: bool, + /// When set, specifies that sub-picture level HRD parameters are present + /// and the HRD may operate at access unit level or sub-picture level. When + /// not set, specifies that sub-picture level HRD parameters are not present + /// and the HRD operates at access unit level. + pub sub_pic_hrd_params_present_flag: bool, + /// Used to specify the clock sub-tick. A clock sub-tick is the minimum + /// interval of time that can be represented in the coded data when + /// sub_pic_hrd_params_present_flag is set. + pub tick_divisor_minus2: u8, + /// du_cpb_removal_delay_increment_length_minus1 plus 1 specifies the + /// length, in bits, of the `du_cpb_removal_delay_increment_minus1[ i ]` and + /// du_common_cpb_removal_delay_increment_minus1 syntax elements of the + /// picture timing SEI message and the du_spt_cpb_removal_delay_increment + /// syntax element in the decoding unit information SEI message. + pub du_cpb_removal_delay_increment_length_minus1: u8, + /// When set, specifies that sub-picture level CPB removal delay parameters + /// are present in picture timing SEI messages and no decoding unit + /// information SEI message is available (in the CVS or provided through + /// external means not specified in this Specification). When not set, + /// specifies that sub-picture level CPB removal delay parameters are + /// present in decoding unit information SEI messages and picture timing SEI + /// messages do not include sub-picture level CPB removal delay parameters. + pub sub_pic_cpb_params_in_pic_timing_sei_flag: bool, + /// dpb_output_delay_du_length_minus1 plus 1 specifies the length, in bits, + /// of the pic_dpb_output_du_delay syntax element in the picture timing SEI + /// message and the pic_spt_dpb_output_du_delay syntax element in the + /// decoding unit information SEI message. + pub dpb_output_delay_du_length_minus1: u8, + /// Together with `bit_rate_value_minus1[ i ]`, specifies the maximum input + /// bit rate of the i-th CPB. + pub bit_rate_scale: u8, + /// Together with `cpb_size_du_value_minus1[ i ]`, specifies the CPB size of + /// the i-th CPB when the CPB operates at sub-picture level. + pub cpb_size_scale: u8, + /// Together with `cpb_size_du_value_minus1[ i ]`, specifies the CPB size of + /// the i-th CPB when the CPB operates at sub-picture level. + pub cpb_size_du_scale: u8, + /// initial_cpb_removal_delay_length_minus1 plus 1 specifies the length, in + /// bits, of the `nal_initial_cpb_removal_delay[ i ]`, + /// `nal_initial_cpb_removal_offset[ i ]`, `vcl_initial_cpb_removal_delay[ i ]` + /// and `vcl_initial_cpb_removal_offset[ i ]` syntax elements of the buffering + /// period SEI message. + pub initial_cpb_removal_delay_length_minus1: u8, + /// au_cpb_removal_delay_length_minus1 plus 1 specifies the length, in bits, + /// of the cpb_delay_offset syntax element in the buffering period SEI + /// message and the au_cpb_removal_delay_minus1 syntax element in the + /// picture timing SEI message. + pub au_cpb_removal_delay_length_minus1: u8, + /// dpb_output_delay_length_minus1 plus 1 specifies the length, in bits, of + /// the dpb_delay_offset syntax element in the buffering period SEI message + /// and the pic_dpb_output_delay syntax element in the picture timing SEI + /// message. + pub dpb_output_delay_length_minus1: u8, + /// `fixed_pic_rate_general_flag[ i ]` set indicates that, when HighestTid is + /// equal to i, the temporal distance between the HRD output times of + /// consecutive pictures in output order is constrained as specified in the + /// specification. `fixed_pic_rate_general_flag[ i ]` not set indicates that + /// this constraint may not apply. + pub fixed_pic_rate_general_flag: [bool; 7], + /// `fixed_pic_rate_within_cvs_flag[ i ]` set indicates that, when HighestTid + /// is equal to i, the temporal distance between the HRD output times of + /// consecutive pictures in output order is constrained as specified in the + /// specification. `fixed_pic_rate_within_cvs_flag[ i ]` not set indicates + /// that this constraint may not apply. + pub fixed_pic_rate_within_cvs_flag: [bool; 7], + /// `elemental_duration_in_tc_minus1[ i ]` plus 1 (when present) specifies, + /// when HighestTid is equal to i, the temporal distance, in clock ticks, + /// between the elemental units that specify the HRD output times of + /// consecutive pictures in output order as specified in the specification. + pub elemental_duration_in_tc_minus1: [u32; 7], + /// `low_delay_hrd_flag[ i ]` specifies the HRD operational mode, when + /// HighestTid is equal to i, as specified in Annex C or clause F.13. + pub low_delay_hrd_flag: [bool; 7], + /// `cpb_cnt_minus1[ i ]` plus 1 specifies the number of alternative CPB + /// specifications in the bitstream of the CVS when HighestTid is equal to + /// i. + pub cpb_cnt_minus1: [u32; 7], + /// The NAL HRD data. + pub nal_hrd: [SublayerHrdParameters; 7], + /// The VCL HRD data. + pub vcl_hrd: [SublayerHrdParameters; 7], +} + +impl Default for HrdParams { + fn default() -> Self { + Self { + initial_cpb_removal_delay_length_minus1: 23, + au_cpb_removal_delay_length_minus1: 23, + dpb_output_delay_du_length_minus1: 23, + nal_hrd_parameters_present_flag: Default::default(), + vcl_hrd_parameters_present_flag: Default::default(), + sub_pic_hrd_params_present_flag: Default::default(), + tick_divisor_minus2: Default::default(), + du_cpb_removal_delay_increment_length_minus1: Default::default(), + sub_pic_cpb_params_in_pic_timing_sei_flag: Default::default(), + bit_rate_scale: Default::default(), + cpb_size_scale: Default::default(), + cpb_size_du_scale: Default::default(), + dpb_output_delay_length_minus1: Default::default(), + fixed_pic_rate_general_flag: Default::default(), + fixed_pic_rate_within_cvs_flag: Default::default(), + elemental_duration_in_tc_minus1: Default::default(), + low_delay_hrd_flag: Default::default(), + cpb_cnt_minus1: Default::default(), + nal_hrd: Default::default(), + vcl_hrd: Default::default(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VuiParams { + /// When set, specifies that aspect_ratio_idc is present. When not set, + /// specifies that aspect_ratio_idc is not present. + pub aspect_ratio_info_present_flag: bool, + /// Specifies the value of the sample aspect ratio of the luma samples. + pub aspect_ratio_idc: u32, + /// Indicates the horizontal size of the sample aspect ratio (in arbitrary + /// units). + pub sar_width: u32, + /// Indicates the vertical size of the sample aspect ratio (in arbitrary + /// units). + pub sar_height: u32, + /// When set, specifies that the overscan_appropriate_flag is present. When + /// not set, the preferred display method for the video signal is + /// unspecified. + pub overscan_info_present_flag: bool, + /// When set indicates that the cropped decoded pictures output are suitable + /// for display using overscan. When not set, indicates that the cropped + /// decoded pictures output contain visually important information in the + /// entire region out to the edges of the conformance cropping window of the + /// picture, such that the cropped decoded pictures output should not be + /// displayed using overscan. + pub overscan_appropriate_flag: bool, + /// When set, specifies that video_format, video_full_range_flag and + /// colour_description_present_flag are present. When not set, specify that + /// video_format, video_full_range_flag and colour_description_present_flag + /// are not present. + pub video_signal_type_present_flag: bool, + /// Indicates the representation of the pictures as specified in Table E.2, + /// before being coded in accordance with this Specification. + pub video_format: u8, + /// Indicates the black level and range of the luma and chroma signals as + /// derived from E′Y, E′PB, and E′PR or E′R, E′G, and E′B real-valued + /// component signals. + pub video_full_range_flag: bool, + /// When set, specifies that colour_primaries, transfer_characteristics, and + /// matrix_coeffs are present. When not set, specifies that + /// colour_primaries, transfer_characteristics, and matrix_coeffs are not + /// present. + pub colour_description_present_flag: bool, + /// Indicates the chromaticity coordinates of the source primaries as + /// specified in Table E.3 in terms of the CIE 1931 definition of x and y as + /// specified in ISO 11664-1. + pub colour_primaries: u32, + /// See table E.4 in the specification. + pub transfer_characteristics: u32, + /// Describes the matrix coefficients used in deriving luma and chroma + /// signals from the green, blue, and red, or Y, Z, and X primaries, as + /// specified in Table E.5. + pub matrix_coeffs: u32, + /// When true, specifies that chroma_sample_loc_type_top_field and + /// chroma_sample_loc_type_bottom_field are present. When false, specifies + /// that chroma_sample_loc_type_top_field and + /// chroma_sample_loc_type_bottom_field are not present. + pub chroma_loc_info_present_flag: bool, + /// See the specification for more details. + pub chroma_sample_loc_type_top_field: u32, + /// See the specification for more details. + pub chroma_sample_loc_type_bottom_field: u32, + /// When true, indicates that the value of all decoded chroma samples is + /// equal to 1 << ( BitDepthC − 1 ). When false, provides no indication of + /// decoded chroma sample values. + pub neutral_chroma_indication_flag: bool, + /// When true, indicates that the CVS conveys pictures that represent + /// fields, and specifies that a picture timing SEI message shall be present + /// in every access unit of the current CVS. When false, indicates that the + /// CVS conveys pictures that represent frames and that a picture timing SEI + /// message may or may not be present in any access unit of the current CVS. + pub field_seq_flag: bool, + /// When true, specifies that picture timing SEI messages are present for + /// every picture and include the pic_struct, source_scan_type and + /// duplicate_flag syntax elements. When false, specifies that the + /// pic_struct syntax element is not present in picture timing SEI messages. + pub frame_field_info_present_flag: bool, + /// When true, indicates that the default display window parameters follow + /// next in the VUI. When false, indicates that the default display window + /// parameters are not present. + pub default_display_window_flag: bool, + /// Specifies the samples of the pictures in the CVS that are within the + /// default display window, in terms of a rectangular region specified in + /// picture coordinates for display. + pub def_disp_win_left_offset: u32, + /// Specifies the samples of the pictures in the CVS that are within the + /// default display window, in terms of a rectangular region specified in + /// picture coordinates for display. + pub def_disp_win_right_offset: u32, + /// Specifies the samples of the pictures in the CVS that are within the + /// default display window, in terms of a rectangular region specified in + /// picture coordinates for display. + pub def_disp_win_top_offset: u32, + /// Specifies the samples of the pictures in the CVS that are within the + /// default display window, in terms of a rectangular region specified in + /// picture coordinates for display. + pub def_disp_win_bottom_offset: u32, + /// When set, specifies that vui_num_units_in_tick, vui_time_scale, + /// vui_poc_proportional_to_timing_flag and vui_hrd_parameters_present_flag + /// are present in the vui_parameters( ) syntax structure. When not set, + /// specifies that vui_num_units_in_tick, vui_time_scale, + /// vui_poc_proportional_to_timing_flag and vui_hrd_parameters_present_flag + /// are not present in the vui_parameters( ) syntax structure + pub timing_info_present_flag: bool, + /// The number of time units of a clock operating at the frequency + /// vui_time_scale Hz that corresponds to one increment (called a clock + /// tick) of a clock tick counter. + pub num_units_in_tick: u32, + /// Is the number of time units that pass in one second. For example, a time + /// coordinate system that measures time using a 27 MHz clock has a + /// vui_time_scale of 27 000 000. + pub time_scale: u32, + /// When set, indicates that the picture order count value for each picture + /// in the CVS that is not the first picture in the CVS, in decoding order, + /// is proportional to the output time of the picture relative to the output + /// time of the first picture in the CVS. When not set, indicates that the + /// picture order count value for each picture in the CVS that is not the + /// first picture in the CVS, in decoding order, may or may not be + /// proportional to the output time of the picture relative to the output + /// time of the first picture in the CVS. + pub poc_proportional_to_timing_flag: bool, + /// vui_num_ticks_poc_diff_one_minus1 plus 1 specifies the number of clock + /// ticks corresponding to a difference of picture order count values equal + /// to 1. + pub num_ticks_poc_diff_one_minus1: u32, + /// When set, specifies that the syntax structure hrd_parameters( ) is + /// present in the vui_parameters( ) syntax structure. When not set, + /// specifies that the syntax structure hrd_parameters( ) is not present in + /// the vui_parameters( ) syntax structure. + pub hrd_parameters_present_flag: bool, + /// The hrd_parameters() data. + pub hrd: HrdParams, + /// When set, specifies that the bitstream restriction parameters for the + /// CVS are present. When not set, specifies that the bitstream restriction + /// parameters for the CVS are not present. + pub bitstream_restriction_flag: bool, + /// When set, indicates that each PPS that is active in the CVS has the same + /// value of the syntax elements num_tile_columns_minus1, + /// num_tile_rows_minus1, uniform_spacing_flag, `column_width_minus1[ i ]`, + /// `row_height_minus1[ i ]` and loop_filter_across_tiles_enabled_flag, when + /// present. When not set, indicates that tiles syntax elements in different + /// PPSs may or may not have the same value + pub tiles_fixed_structure_flag: bool, + /// When not set, indicates that no sample outside the picture boundaries + /// and no sample at a fractional sample position for which the sample value + /// is derived using one or more samples outside the picture boundaries is + /// used for inter prediction of any sample. When set, indicates that one + /// or more samples outside the picture boundaries may be used in inter + /// prediction. + pub motion_vectors_over_pic_boundaries_flag: bool, + /// When set, indicates that all P and B slices (when present) that belong + /// to the same picture have an identical reference picture list 0 and that + /// all B slices (when present) that belong to the same picture have an + /// identical reference picture list 1. + pub restricted_ref_pic_lists_flag: bool, + /// When not equal to 0, establishes a bound on the maximum possible size of + /// distinct coded spatial segmentation regions in the pictures of the CVS. + pub min_spatial_segmentation_idc: u32, + /// Indicates a number of bytes not exceeded by the sum of the sizes of the + /// VCL NAL units associated with any coded picture in the CVS. + pub max_bytes_per_pic_denom: u32, + /// Indicates an upper bound for the number of coded bits of coding_unit( ) + /// data for anycoding block in any picture of the CVS. + pub max_bits_per_min_cu_denom: u32, + /// Indicate the maximum absolute value of a decoded horizontal and vertical + /// motion vector component, respectively, in quarter luma sample units, for + /// all pictures in the CVS. + pub log2_max_mv_length_horizontal: u32, + /// Indicate the maximum absolute value of a decoded horizontal and vertical + /// motion vector component, respectively, in quarter luma sample units, for + /// all pictures in the CVS. + pub log2_max_mv_length_vertical: u32, +} + +impl Default for VuiParams { + fn default() -> Self { + Self { + aspect_ratio_info_present_flag: Default::default(), + aspect_ratio_idc: Default::default(), + sar_width: Default::default(), + sar_height: Default::default(), + overscan_info_present_flag: Default::default(), + overscan_appropriate_flag: Default::default(), + video_signal_type_present_flag: Default::default(), + video_format: 5, + video_full_range_flag: Default::default(), + colour_description_present_flag: Default::default(), + colour_primaries: 2, + transfer_characteristics: 2, + matrix_coeffs: 2, + chroma_loc_info_present_flag: Default::default(), + chroma_sample_loc_type_top_field: Default::default(), + chroma_sample_loc_type_bottom_field: Default::default(), + neutral_chroma_indication_flag: Default::default(), + field_seq_flag: Default::default(), + frame_field_info_present_flag: Default::default(), + default_display_window_flag: Default::default(), + def_disp_win_left_offset: Default::default(), + def_disp_win_right_offset: Default::default(), + def_disp_win_top_offset: Default::default(), + def_disp_win_bottom_offset: Default::default(), + timing_info_present_flag: Default::default(), + num_units_in_tick: Default::default(), + time_scale: Default::default(), + poc_proportional_to_timing_flag: Default::default(), + num_ticks_poc_diff_one_minus1: Default::default(), + hrd_parameters_present_flag: Default::default(), + hrd: Default::default(), + bitstream_restriction_flag: Default::default(), + tiles_fixed_structure_flag: Default::default(), + motion_vectors_over_pic_boundaries_flag: true, + restricted_ref_pic_lists_flag: Default::default(), + min_spatial_segmentation_idc: Default::default(), + max_bytes_per_pic_denom: 2, + max_bits_per_min_cu_denom: 1, + log2_max_mv_length_horizontal: 15, + log2_max_mv_length_vertical: 15, + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct Parser { + active_vpses: BTreeMap>, + active_spses: BTreeMap>, + active_ppses: BTreeMap>, +} + +impl Parser { + /// Parse a VPS NALU. + pub fn parse_vps(&mut self, nalu: &Nalu) -> Result<&Vps, String> { + if !matches!(nalu.header.type_, NaluType::VpsNut) { + return Err(format!( + "Invalid NALU type, expected {:?}, got {:?}", + NaluType::VpsNut, + nalu.header.type_ + )); + } + + let data = nalu.as_ref(); + let header = &nalu.header; + let hdr_len = header.len(); + // Skip the header + let mut r = BitReader::new(&data[hdr_len..], true); + + let mut vps = Vps { + video_parameter_set_id: r.read_bits(4)?, + base_layer_internal_flag: r.read_bit()?, + base_layer_available_flag: r.read_bit()?, + max_layers_minus1: r.read_bits(6)?, + max_sub_layers_minus1: r.read_bits(3)?, + temporal_id_nesting_flag: r.read_bit()?, + ..Default::default() + }; + + r.skip_bits(16)?; // vps_reserved_0xffff_16bits + + let ptl = &mut vps.profile_tier_level; + Self::parse_profile_tier_level(ptl, &mut r, true, vps.max_sub_layers_minus1)?; + + vps.sub_layer_ordering_info_present_flag = r.read_bit()?; + + let start = + if vps.sub_layer_ordering_info_present_flag { 0 } else { vps.max_sub_layers_minus1 } + as usize; + + for i in start..=usize::from(vps.max_sub_layers_minus1) { + vps.max_dec_pic_buffering_minus1[i] = r.read_ue_max(15)?; + vps.max_num_reorder_pics[i] = r.read_ue_max(vps.max_dec_pic_buffering_minus1[i])?; + vps.max_latency_increase_plus1[i] = r.read_ue()?; + + if i > 0 { + if vps.max_dec_pic_buffering_minus1[i] < vps.max_dec_pic_buffering_minus1[i - 1] { + return Err(format!( + "Invalid max_dec_pic_buffering_minus1[{}]: {}", + i, vps.max_dec_pic_buffering_minus1[i] + )); + } + + if vps.max_num_reorder_pics[i] < vps.max_num_reorder_pics[i - 1] { + return Err(format!( + "Invalid max_num_reorder_pics[{}]: {}", + i, vps.max_num_reorder_pics[i] + )); + } + } + } + + // vps_sub_layer_ordering_info_present_flag equal to 0 specifies that + // the values of vps_max_dec_pic_buffering_minus1[ + // vps_max_sub_layers_minus1 ], vps_max_num_reorder_pics[ vps_max_sub_ + // layers_minus1 ] and vps_max_latency_increase_plus1[ + // vps_max_sub_layers_minus1 ] apply to all sub-layers + if !vps.sub_layer_ordering_info_present_flag { + let max_num_sublayers = usize::from(vps.max_sub_layers_minus1); + for i in 0..max_num_sublayers { + vps.max_dec_pic_buffering_minus1[i] = + vps.max_dec_pic_buffering_minus1[max_num_sublayers]; + + vps.max_num_reorder_pics[i] = vps.max_num_reorder_pics[max_num_sublayers]; + + vps.max_latency_increase_plus1[i] = + vps.max_latency_increase_plus1[max_num_sublayers]; + } + } + + vps.max_layer_id = r.read_bits(6)?; + if vps.max_layer_id > 62 { + return Err(format!("Invalid max_layer_id {}", vps.max_layer_id)); + } + + vps.num_layer_sets_minus1 = r.read_ue_max(1023)?; + + for _ in 1..=vps.num_layer_sets_minus1 { + for _ in 0..=vps.max_layer_id { + // Skip layer_id_included_flag[i][j] for now. + r.skip_bits(1)?; + } + } + + vps.timing_info_present_flag = r.read_bit()?; + + if vps.timing_info_present_flag { + vps.num_units_in_tick = r.read_bits::(31)? << 1; + vps.num_units_in_tick |= r.read_bits::(1)?; + + vps.time_scale = r.read_bits::(31)? << 1; + vps.time_scale |= r.read_bits::(1)?; + + vps.poc_proportional_to_timing_flag = r.read_bit()?; + if vps.poc_proportional_to_timing_flag { + vps.num_ticks_poc_diff_one_minus1 = r.read_ue()?; + } + + vps.num_hrd_parameters = r.read_ue()?; + + for i in 0..vps.num_hrd_parameters as usize { + vps.hrd_layer_set_idx.push(r.read_ue()?); + if i > 0 { + vps.cprms_present_flag.push(r.read_bit()?); + } + + let mut hrd = HrdParams::default(); + Self::parse_hrd_parameters( + vps.cprms_present_flag[i], + vps.max_sub_layers_minus1, + &mut hrd, + &mut r, + )?; + + vps.hrd_parameters.push(hrd); + } + } + + vps.extension_flag = r.read_bit()?; + + if self.active_vpses.keys().len() >= MAX_VPS_COUNT { + return Err("Broken data: Number of active VPSs > MAX_VPS_COUNT".into()); + } + + let key = vps.video_parameter_set_id; + let vps = Rc::new(vps); + self.active_vpses.remove(&key); + Ok(self.active_vpses.entry(key).or_insert(vps)) + } + + fn parse_profile_tier_level( + ptl: &mut ProfileTierLevel, + r: &mut BitReader, + profile_present_flag: bool, + sps_max_sub_layers_minus_1: u8, + ) -> Result<(), String> { + if profile_present_flag { + ptl.general_profile_space = r.read_bits(2)?; + ptl.general_tier_flag = r.read_bit()?; + ptl.general_profile_idc = r.read_bits(5)?; + + for i in 0..32 { + ptl.general_profile_compatibility_flag[i] = r.read_bit()?; + } + + ptl.general_progressive_source_flag = r.read_bit()?; + ptl.general_interlaced_source_flag = r.read_bit()?; + ptl.general_non_packed_constraint_flag = r.read_bit()?; + ptl.general_frame_only_constraint_flag = r.read_bit()?; + + if ptl.general_profile_idc == 4 + || ptl.general_profile_compatibility_flag[4] + || ptl.general_profile_idc == 5 + || ptl.general_profile_compatibility_flag[5] + || ptl.general_profile_idc == 6 + || ptl.general_profile_compatibility_flag[6] + || ptl.general_profile_idc == 7 + || ptl.general_profile_compatibility_flag[7] + || ptl.general_profile_idc == 8 + || ptl.general_profile_compatibility_flag[8] + || ptl.general_profile_idc == 9 + || ptl.general_profile_compatibility_flag[9] + || ptl.general_profile_idc == 10 + || ptl.general_profile_compatibility_flag[10] + || ptl.general_profile_idc == 11 + || ptl.general_profile_compatibility_flag[11] + { + ptl.general_max_12bit_constraint_flag = r.read_bit()?; + ptl.general_max_10bit_constraint_flag = r.read_bit()?; + ptl.general_max_8bit_constraint_flag = r.read_bit()?; + ptl.general_max_422chroma_constraint_flag = r.read_bit()?; + ptl.general_max_420chroma_constraint_flag = r.read_bit()?; + ptl.general_max_monochrome_constraint_flag = r.read_bit()?; + ptl.general_intra_constraint_flag = r.read_bit()?; + ptl.general_one_picture_only_constraint_flag = r.read_bit()?; + ptl.general_lower_bit_rate_constraint_flag = r.read_bit()?; + if ptl.general_profile_idc == 5 + || ptl.general_profile_compatibility_flag[5] + || ptl.general_profile_idc == 9 + || ptl.general_profile_compatibility_flag[9] + || ptl.general_profile_idc == 10 + || ptl.general_profile_compatibility_flag[10] + || ptl.general_profile_idc == 11 + || ptl.general_profile_compatibility_flag[11] + { + ptl.general_max_14bit_constraint_flag = r.read_bit()?; + // Skip general_reserved_zero_33bits + r.skip_bits(31)?; + r.skip_bits(2)?; + } else { + // Skip general_reserved_zero_34bits + r.skip_bits(31)?; + r.skip_bits(3)?; + } + } else if ptl.general_profile_idc == 2 || ptl.general_profile_compatibility_flag[2] { + // Skip general_reserved_zero_7bits + r.skip_bits(7)?; + ptl.general_one_picture_only_constraint_flag = r.read_bit()?; + // Skip general_reserved_zero_35bits + r.skip_bits(31)?; + r.skip_bits(4)?; + } else { + r.skip_bits(31)?; + r.skip_bits(12)?; + } + + if ptl.general_profile_idc == 1 + || ptl.general_profile_compatibility_flag[1] + || ptl.general_profile_idc == 2 + || ptl.general_profile_compatibility_flag[2] + || ptl.general_profile_idc == 3 + || ptl.general_profile_compatibility_flag[3] + || ptl.general_profile_idc == 4 + || ptl.general_profile_compatibility_flag[4] + || ptl.general_profile_idc == 5 + || ptl.general_profile_compatibility_flag[5] + || ptl.general_profile_idc == 9 + || ptl.general_profile_compatibility_flag[9] + || ptl.general_profile_idc == 11 + || ptl.general_profile_compatibility_flag[11] + { + ptl.general_inbld_flag = r.read_bit()?; + } else { + r.skip_bits(1)?; + } + } + + let level: u8 = r.read_bits(8)?; + ptl.general_level_idc = Level::try_from(level)?; + + for i in 0..sps_max_sub_layers_minus_1 as usize { + ptl.sub_layer_profile_present_flag[i] = r.read_bit()?; + ptl.sub_layer_level_present_flag[i] = r.read_bit()?; + } + + if sps_max_sub_layers_minus_1 > 0 { + for _ in sps_max_sub_layers_minus_1..8 { + r.skip_bits(2)?; + } + } + + for i in 0..sps_max_sub_layers_minus_1 as usize { + if ptl.sub_layer_level_present_flag[i] { + ptl.sub_layer_profile_space[i] = r.read_bits(2)?; + ptl.sub_layer_tier_flag[i] = r.read_bit()?; + ptl.sub_layer_profile_idc[i] = r.read_bits(5)?; + for j in 0..32 { + ptl.sub_layer_profile_compatibility_flag[i][j] = r.read_bit()?; + } + ptl.sub_layer_progressive_source_flag[i] = r.read_bit()?; + ptl.sub_layer_interlaced_source_flag[i] = r.read_bit()?; + ptl.sub_layer_non_packed_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_frame_only_constraint_flag[i] = r.read_bit()?; + + if ptl.sub_layer_profile_idc[i] == 4 + || ptl.sub_layer_profile_compatibility_flag[i][4] + || ptl.sub_layer_profile_idc[i] == 5 + || ptl.sub_layer_profile_compatibility_flag[i][5] + || ptl.sub_layer_profile_idc[i] == 6 + || ptl.sub_layer_profile_compatibility_flag[i][6] + || ptl.sub_layer_profile_idc[i] == 7 + || ptl.sub_layer_profile_compatibility_flag[i][7] + || ptl.sub_layer_profile_idc[i] == 8 + || ptl.sub_layer_profile_compatibility_flag[i][8] + || ptl.sub_layer_profile_idc[i] == 9 + || ptl.sub_layer_profile_compatibility_flag[i][9] + || ptl.sub_layer_profile_idc[i] == 10 + || ptl.sub_layer_profile_compatibility_flag[i][10] + || ptl.sub_layer_profile_idc[i] == 11 + || ptl.sub_layer_profile_compatibility_flag[i][11] + { + ptl.sub_layer_max_12bit_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_max_10bit_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_max_8bit_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_max_422chroma_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_max_420chroma_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_max_monochrome_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_intra_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_one_picture_only_constraint_flag[i] = r.read_bit()?; + ptl.sub_layer_lower_bit_rate_constraint_flag[i] = r.read_bit()?; + + if ptl.sub_layer_profile_idc[i] == 5 + || ptl.sub_layer_profile_compatibility_flag[i][5] + || ptl.sub_layer_profile_idc[i] == 9 + || ptl.sub_layer_profile_compatibility_flag[i][9] + || ptl.sub_layer_profile_idc[i] == 10 + || ptl.sub_layer_profile_compatibility_flag[i][10] + || ptl.sub_layer_profile_idc[i] == 11 + || ptl.sub_layer_profile_compatibility_flag[i][11] + { + ptl.sub_layer_max_14bit_constraint_flag[i] = r.read_bit()?; + r.skip_bits(33)?; + } else { + r.skip_bits(34)?; + } + } else if ptl.sub_layer_profile_idc[i] == 2 + || ptl.sub_layer_profile_compatibility_flag[i][2] + { + r.skip_bits(7)?; + ptl.sub_layer_one_picture_only_constraint_flag[i] = r.read_bit()?; + r.skip_bits(35)?; + } else { + r.skip_bits(43)?; + } + + if ptl.sub_layer_profile_idc[i] == 1 + || ptl.sub_layer_profile_compatibility_flag[i][1] + || ptl.sub_layer_profile_idc[i] == 2 + || ptl.sub_layer_profile_compatibility_flag[i][2] + || ptl.sub_layer_profile_idc[i] == 3 + || ptl.sub_layer_profile_compatibility_flag[i][3] + || ptl.sub_layer_profile_idc[i] == 4 + || ptl.sub_layer_profile_compatibility_flag[i][4] + || ptl.sub_layer_profile_idc[i] == 5 + || ptl.sub_layer_profile_compatibility_flag[i][5] + || ptl.sub_layer_profile_idc[i] == 9 + || ptl.sub_layer_profile_compatibility_flag[i][9] + || ptl.sub_layer_profile_idc[i] == 11 + || ptl.sub_layer_profile_compatibility_flag[i][11] + { + ptl.sub_layer_inbld_flag[i] = r.read_bit()?; + } else { + r.skip_bits(1)?; + } + + if ptl.sub_layer_level_present_flag[i] { + let level: u8 = r.read_bits(8)?; + ptl.sub_layer_level_idc[i] = Level::try_from(level)?; + } + } + } + Ok(()) + } + + fn fill_default_scaling_list(sl: &mut ScalingLists, size_id: i32, matrix_id: i32) { + if size_id == 0 { + sl.scaling_list_4x4[matrix_id as usize] = DEFAULT_SCALING_LIST_0; + return; + } + + let dst = match size_id { + 1 => &mut sl.scaling_list_8x8[matrix_id as usize], + 2 => &mut sl.scaling_list_16x16[matrix_id as usize], + 3 => &mut sl.scaling_list_32x32[matrix_id as usize], + _ => panic!("Invalid size_id {}", size_id), + }; + + let src = if matrix_id < 3 { + &DEFAULT_SCALING_LIST_1 + } else if matrix_id <= 5 { + &DEFAULT_SCALING_LIST_2 + } else { + panic!("Invalid matrix_id {}", matrix_id); + }; + + *dst = *src; + + // When `scaling_list_pred_mode_flag[ sizeId ]`[ matrixId ] is equal to + // 0, scaling_list_pred_matrix_id_ `delta[ sizeId ]`[ matrixId ] is equal + // to 0 and sizeId is greater than 1, the value of + // scaling_list_dc_coef_minus8[ sizeId − 2 `][ matrixId ]` is inferred to + // be equal to 8. + // + // Since we are using a slightly different layout here, with two + // different field names (i.e. 16x16, and 32x32), we must differentiate + // between size_id == 2 or size_id == 3. + if size_id == 2 { + sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] = 8; + } else if size_id == 3 { + sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] = 8; + } + } + + fn parse_scaling_list_data(sl: &mut ScalingLists, r: &mut BitReader) -> Result<(), String> { + // 7.4.5 + for size_id in 0..4 { + let mut matrix_id = 0; + while matrix_id < 6 { + let scaling_list_pred_mode_flag = r.read_bit()?; + // If `scaling_list_pred_matrix_id_delta[ sizeId ]`[ matrixId ] is + // equal to 0, the scaling list is inferred from the default + // scaling list `ScalingList[ sizeId ]`[ matrixId `][ i ]` as specified + // in Table 7-5 and Table 7-6 for i = 0..Min( 63, ( 1 << ( 4 + ( + // sizeId << 1 ) ) ) − 1 ). + if !scaling_list_pred_mode_flag { + let scaling_list_pred_matrix_id_delta: u32 = r.read_ue()?; + if scaling_list_pred_matrix_id_delta == 0 { + Self::fill_default_scaling_list(sl, size_id, matrix_id); + } else { + // Equation 7-42 + let factor = if size_id == 3 { 3 } else { 1 }; + let ref_matrix_id = + matrix_id as u32 - scaling_list_pred_matrix_id_delta * factor; + if size_id == 0 { + sl.scaling_list_4x4[matrix_id as usize] = + sl.scaling_list_4x4[ref_matrix_id as usize]; + } else { + let src = match size_id { + 1 => sl.scaling_list_8x8[ref_matrix_id as usize], + 2 => sl.scaling_list_16x16[ref_matrix_id as usize], + 3 => sl.scaling_list_32x32[ref_matrix_id as usize], + _ => return Err(format!("Invalid size_id {}", size_id)), + }; + + let dst = match size_id { + 1 => &mut sl.scaling_list_8x8[matrix_id as usize], + 2 => &mut sl.scaling_list_16x16[matrix_id as usize], + 3 => &mut sl.scaling_list_32x32[matrix_id as usize], + _ => return Err(format!("Invalid size_id {}", size_id)), + }; + + *dst = src; + + if size_id == 2 { + sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] = + sl.scaling_list_dc_coef_minus8_16x16[ref_matrix_id as usize]; + } else if size_id == 3 { + sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] = + sl.scaling_list_dc_coef_minus8_32x32[ref_matrix_id as usize]; + } + } + } + } else { + let mut next_coef = 8i32; + let coef_num = std::cmp::min(64, 1 << (4 + (size_id << 1))); + + if size_id > 1 { + if size_id == 2 { + sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] = + r.read_se_bounded(-7, 247)?; + next_coef = + i32::from(sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize]) + + 8; + } else if size_id == 3 { + sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] = + r.read_se_bounded(-7, 247)?; + next_coef = + i32::from(sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize]) + + 8; + } + } + + for i in 0..coef_num as usize { + let scaling_list_delta_coef: i32 = r.read_se_bounded(-128, 127)?; + next_coef = (next_coef + scaling_list_delta_coef + 256) % 256; + match size_id { + 0 => sl.scaling_list_4x4[matrix_id as usize][i] = next_coef as _, + 1 => sl.scaling_list_8x8[matrix_id as usize][i] = next_coef as _, + 2 => sl.scaling_list_16x16[matrix_id as usize][i] = next_coef as _, + 3 => sl.scaling_list_32x32[matrix_id as usize][i] = next_coef as _, + _ => return Err(format!("Invalid size_id {}", size_id)), + } + } + } + let step = if size_id == 3 { 3 } else { 1 }; + matrix_id += step; + } + } + Ok(()) + } + + fn parse_short_term_ref_pic_set( + sps: &Sps, + st: &mut ShortTermRefPicSet, + r: &mut BitReader, + st_rps_idx: u8, + ) -> Result<(), String> { + if st_rps_idx != 0 { + st.inter_ref_pic_set_prediction_flag = r.read_bit()?; + } + + // (7-59) + if st.inter_ref_pic_set_prediction_flag { + if st_rps_idx == sps.num_short_term_ref_pic_sets { + st.delta_idx_minus1 = r.read_ue_max(st_rps_idx as u32 - 1)?; + } + + st.delta_rps_sign = r.read_bit()?; + // The value of abs_delta_rps_minus1 shall be in the range of 0 to + // 2^15 − 1, inclusive. + st.abs_delta_rps_minus1 = r.read_ue_max(32767)?; + + let ref_rps_idx = st_rps_idx - (st.delta_idx_minus1 + 1); + let delta_rps = + (1 - 2 * st.delta_rps_sign as i32) * (st.abs_delta_rps_minus1 as i32 + 1); + + let ref_st = sps + .short_term_ref_pic_set + .get(usize::from(ref_rps_idx)) + .ok_or::("Invalid ref_rps_idx".into())?; + + let mut used_by_curr_pic_flag = [false; 64]; + + // 7.4.8 - defaults to 1 if not present + let mut use_delta_flag = [true; 64]; + + for j in 0..=ref_st.num_delta_pocs as usize { + used_by_curr_pic_flag[j] = r.read_bit()?; + if !used_by_curr_pic_flag[j] { + use_delta_flag[j] = r.read_bit()?; + } + } + + // (7-61) + let mut i = 0; + // Ranges are [a,b[, but the real loop is [b, a], i.e. + // [num_positive_pics - 1, 0]. Use ..= so that b is included when + // rev() is called. + for j in (0..=isize::from(ref_st.num_positive_pics) - 1) + .rev() + .take_while(|j| *j >= 0) + .map(|j| j as usize) + { + let d_poc = ref_st.delta_poc_s1[j] + delta_rps; + if d_poc < 0 && use_delta_flag[usize::from(ref_st.num_negative_pics) + j] { + st.delta_poc_s0[i] = d_poc; + st.used_by_curr_pic_s0[i] = + used_by_curr_pic_flag[usize::from(ref_st.num_negative_pics) + j]; + + i += 1; + } + } + + if delta_rps < 0 && use_delta_flag[ref_st.num_delta_pocs as usize] { + st.delta_poc_s0[i] = delta_rps; + st.used_by_curr_pic_s0[i] = used_by_curr_pic_flag[ref_st.num_delta_pocs as usize]; + + i += 1; + } + + // Let's *not* change the original algorithm in any way. + #[allow(clippy::needless_range_loop)] + for j in 0..ref_st.num_negative_pics as usize { + let d_poc = ref_st.delta_poc_s0[j] + delta_rps; + if d_poc < 0 && use_delta_flag[j] { + st.delta_poc_s0[i] = d_poc; + st.used_by_curr_pic_s0[i] = used_by_curr_pic_flag[j]; + + i += 1; + } + } + + st.num_negative_pics = i as u8; + + // (7-62) + let mut i = 0; + // Ranges are [a,b[, but the real loop is [b, a], i.e. + // [num_negative_pics - 1, 0]. Use ..= so that b is included when + // rev() is called. + for j in (0..=isize::from(ref_st.num_negative_pics) - 1) + .rev() + .take_while(|j| *j >= 0) + .map(|j| j as usize) + { + let d_poc = ref_st.delta_poc_s0[j] + delta_rps; + if d_poc > 0 && use_delta_flag[j] { + st.delta_poc_s1[i] = d_poc; + st.used_by_curr_pic_s1[i] = used_by_curr_pic_flag[j]; + + i += 1; + } + } + + if delta_rps > 0 && use_delta_flag[ref_st.num_delta_pocs as usize] { + st.delta_poc_s1[i] = delta_rps; + st.used_by_curr_pic_s1[i] = used_by_curr_pic_flag[ref_st.num_delta_pocs as usize]; + + i += 1; + } + + for j in 0..usize::from(ref_st.num_positive_pics) { + let d_poc = ref_st.delta_poc_s1[j] + delta_rps; + if d_poc > 0 && use_delta_flag[ref_st.num_negative_pics as usize + j] { + st.delta_poc_s1[i] = d_poc; + st.used_by_curr_pic_s1[i] = + used_by_curr_pic_flag[ref_st.num_negative_pics as usize + j]; + + i += 1; + } + } + + st.num_positive_pics = i as u8; + } else { + st.num_negative_pics = r.read_ue_max(u32::from( + sps.max_dec_pic_buffering_minus1[usize::from(sps.max_sub_layers_minus1)], + ))?; + + st.num_positive_pics = r.read_ue_max(u32::from( + sps.max_dec_pic_buffering_minus1[usize::from(sps.max_sub_layers_minus1)] + - st.num_negative_pics, + ))?; + + for i in 0..usize::from(st.num_negative_pics) { + let delta_poc_s0_minus1: u32 = r.read_ue_max(32767)?; + + if i == 0 { + st.delta_poc_s0[i] = -(delta_poc_s0_minus1 as i32 + 1); + } else { + st.delta_poc_s0[i] = st.delta_poc_s0[i - 1] - (delta_poc_s0_minus1 as i32 + 1); + } + + st.used_by_curr_pic_s0[i] = r.read_bit()?; + } + + for i in 0..usize::from(st.num_positive_pics) { + let delta_poc_s1_minus1: u32 = r.read_ue_max(32767)?; + + if i == 0 { + st.delta_poc_s1[i] = delta_poc_s1_minus1 as i32 + 1; + } else { + st.delta_poc_s1[i] = st.delta_poc_s1[i - 1] + (delta_poc_s1_minus1 as i32 + 1); + } + + st.used_by_curr_pic_s1[i] = r.read_bit()?; + } + } + + st.num_delta_pocs = u32::from(st.num_negative_pics + st.num_positive_pics); + + Ok(()) + } + + fn parse_sublayer_hrd_parameters( + h: &mut SublayerHrdParameters, + cpb_cnt: u32, + sub_pic_hrd_params_present_flag: bool, + r: &mut BitReader, + ) -> Result<(), String> { + for i in 0..cpb_cnt as usize { + h.bit_rate_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?; + h.cpb_size_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?; + if sub_pic_hrd_params_present_flag { + h.cpb_size_du_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?; + h.bit_rate_du_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?; + } + + h.cbr_flag[i] = r.read_bit()?; + } + + Ok(()) + } + + fn parse_hrd_parameters( + common_inf_present_flag: bool, + max_num_sublayers_minus1: u8, + hrd: &mut HrdParams, + r: &mut BitReader, + ) -> Result<(), String> { + if common_inf_present_flag { + hrd.nal_hrd_parameters_present_flag = r.read_bit()?; + hrd.vcl_hrd_parameters_present_flag = r.read_bit()?; + if hrd.nal_hrd_parameters_present_flag || hrd.vcl_hrd_parameters_present_flag { + hrd.sub_pic_hrd_params_present_flag = r.read_bit()?; + if hrd.sub_pic_hrd_params_present_flag { + hrd.tick_divisor_minus2 = r.read_bits(8)?; + hrd.du_cpb_removal_delay_increment_length_minus1 = r.read_bits(5)?; + hrd.sub_pic_cpb_params_in_pic_timing_sei_flag = r.read_bit()?; + hrd.dpb_output_delay_du_length_minus1 = r.read_bits(5)?; + } + hrd.bit_rate_scale = r.read_bits(4)?; + hrd.cpb_size_scale = r.read_bits(4)?; + if hrd.sub_pic_hrd_params_present_flag { + hrd.cpb_size_du_scale = r.read_bits(4)?; + } + hrd.initial_cpb_removal_delay_length_minus1 = r.read_bits(5)?; + hrd.au_cpb_removal_delay_length_minus1 = r.read_bits(5)?; + hrd.dpb_output_delay_length_minus1 = r.read_bits(5)?; + } + } + + for i in 0..=max_num_sublayers_minus1 as usize { + hrd.fixed_pic_rate_general_flag[i] = r.read_bit()?; + if !hrd.fixed_pic_rate_general_flag[i] { + hrd.fixed_pic_rate_within_cvs_flag[i] = r.read_bit()?; + } + if hrd.fixed_pic_rate_within_cvs_flag[i] { + hrd.elemental_duration_in_tc_minus1[i] = r.read_ue_max(2047)?; + } else { + hrd.low_delay_hrd_flag[i] = r.read_bit()?; + } + + if !hrd.low_delay_hrd_flag[i] { + hrd.cpb_cnt_minus1[i] = r.read_ue_max(31)?; + } + + if hrd.nal_hrd_parameters_present_flag { + Self::parse_sublayer_hrd_parameters( + &mut hrd.nal_hrd[i], + hrd.cpb_cnt_minus1[i] + 1, + hrd.sub_pic_hrd_params_present_flag, + r, + )?; + } + + if hrd.vcl_hrd_parameters_present_flag { + Self::parse_sublayer_hrd_parameters( + &mut hrd.vcl_hrd[i], + hrd.cpb_cnt_minus1[i] + 1, + hrd.sub_pic_hrd_params_present_flag, + r, + )?; + } + } + + Ok(()) + } + + fn parse_vui_parameters(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> { + let vui = &mut sps.vui_parameters; + + vui.aspect_ratio_info_present_flag = r.read_bit()?; + if vui.aspect_ratio_info_present_flag { + vui.aspect_ratio_idc = r.read_bits(8)?; + const EXTENDED_SAR: u32 = 255; + if vui.aspect_ratio_idc == EXTENDED_SAR { + vui.sar_width = r.read_bits(16)?; + vui.sar_height = r.read_bits(16)?; + } + } + + vui.overscan_info_present_flag = r.read_bit()?; + if vui.overscan_info_present_flag { + vui.overscan_appropriate_flag = r.read_bit()?; + } + + vui.video_signal_type_present_flag = r.read_bit()?; + if vui.video_signal_type_present_flag { + vui.video_format = r.read_bits(3)?; + vui.video_full_range_flag = r.read_bit()?; + vui.colour_description_present_flag = r.read_bit()?; + if vui.colour_description_present_flag { + vui.colour_primaries = r.read_bits(8)?; + vui.transfer_characteristics = r.read_bits(8)?; + vui.matrix_coeffs = r.read_bits(8)?; + } + } + + vui.chroma_loc_info_present_flag = r.read_bit()?; + if vui.chroma_loc_info_present_flag { + vui.chroma_sample_loc_type_top_field = r.read_ue_max(5)?; + vui.chroma_sample_loc_type_bottom_field = r.read_ue_max(5)?; + } + + vui.neutral_chroma_indication_flag = r.read_bit()?; + vui.field_seq_flag = r.read_bit()?; + vui.frame_field_info_present_flag = r.read_bit()?; + vui.default_display_window_flag = r.read_bit()?; + + if vui.default_display_window_flag { + vui.def_disp_win_left_offset = r.read_ue()?; + vui.def_disp_win_right_offset = r.read_ue()?; + vui.def_disp_win_top_offset = r.read_ue()?; + vui.def_disp_win_bottom_offset = r.read_ue()?; + } + + vui.timing_info_present_flag = r.read_bit()?; + if vui.timing_info_present_flag { + vui.num_units_in_tick = r.read_bits::(31)? << 1; + vui.num_units_in_tick |= r.read_bits::(1)?; + + if vui.num_units_in_tick == 0 { + log::warn!("Incompliant value for num_units_in_tick {}", vui.num_units_in_tick); + } + + vui.time_scale = r.read_bits::(31)? << 1; + vui.time_scale |= r.read_bits::(1)?; + + if vui.time_scale == 0 { + log::warn!("Incompliant value for time_scale {}", vui.time_scale); + } + + vui.poc_proportional_to_timing_flag = r.read_bit()?; + if vui.poc_proportional_to_timing_flag { + vui.num_ticks_poc_diff_one_minus1 = r.read_ue_max((2u64.pow(32) - 2) as u32)?; + } + + vui.hrd_parameters_present_flag = r.read_bit()?; + if vui.hrd_parameters_present_flag { + let sps_max_sub_layers_minus1 = sps.max_sub_layers_minus1; + Self::parse_hrd_parameters(true, sps_max_sub_layers_minus1, &mut vui.hrd, r)?; + } + } + + vui.bitstream_restriction_flag = r.read_bit()?; + if vui.bitstream_restriction_flag { + vui.tiles_fixed_structure_flag = r.read_bit()?; + vui.motion_vectors_over_pic_boundaries_flag = r.read_bit()?; + vui.restricted_ref_pic_lists_flag = r.read_bit()?; + + vui.min_spatial_segmentation_idc = r.read_ue_max(4095)?; + vui.max_bytes_per_pic_denom = r.read_ue()?; + vui.max_bits_per_min_cu_denom = r.read_ue()?; + vui.log2_max_mv_length_horizontal = r.read_ue_max(16)?; + vui.log2_max_mv_length_vertical = r.read_ue_max(15)?; + } + + Ok(()) + } + + fn parse_sps_scc_extension(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> { + let scc = &mut sps.scc_extension; + + scc.curr_pic_ref_enabled_flag = r.read_bit()?; + scc.palette_mode_enabled_flag = r.read_bit()?; + if scc.palette_mode_enabled_flag { + scc.palette_max_size = r.read_ue_max(64)?; + scc.delta_palette_max_predictor_size = + r.read_ue_max(128 - u32::from(scc.palette_max_size))?; + scc.palette_predictor_initializers_present_flag = r.read_bit()?; + if scc.palette_predictor_initializers_present_flag { + let max = + u32::from(scc.palette_max_size + scc.delta_palette_max_predictor_size - 1); + scc.num_palette_predictor_initializer_minus1 = r.read_ue_max(max)?; + + let num_comps = if sps.chroma_format_idc == 0 { 1 } else { 3 }; + for comp in 0..num_comps { + for i in 0..=usize::from(scc.num_palette_predictor_initializer_minus1) { + let num_bits = if comp == 0 { + sps.bit_depth_luma_minus8 + 8 + } else { + sps.bit_depth_chroma_minus8 + 8 + }; + scc.palette_predictor_initializer[comp][i] = + r.read_bits(usize::from(num_bits))?; + } + } + } + } + + scc.motion_vector_resolution_control_idc = r.read_bits(2)?; + scc.intra_boundary_filtering_disabled_flag = r.read_bit()?; + + Ok(()) + } + + fn parse_sps_range_extension(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> { + let ext = &mut sps.range_extension; + + ext.transform_skip_rotation_enabled_flag = r.read_bit()?; + ext.transform_skip_context_enabled_flag = r.read_bit()?; + ext.implicit_rdpcm_enabled_flag = r.read_bit()?; + ext.explicit_rdpcm_enabled_flag = r.read_bit()?; + ext.extended_precision_processing_flag = r.read_bit()?; + ext.intra_smoothing_disabled_flag = r.read_bit()?; + ext.high_precision_offsets_enabled_flag = r.read_bit()?; + ext.persistent_rice_adaptation_enabled_flag = r.read_bit()?; + ext.cabac_bypass_alignment_enabled_flag = r.read_bit()?; + + Ok(()) + } + + /// Parse a SPS NALU. + pub fn parse_sps(&mut self, nalu: &Nalu) -> Result<&Sps, String> { + if !matches!(nalu.header.type_, NaluType::SpsNut) { + return Err(format!( + "Invalid NALU type, expected {:?}, got {:?}", + NaluType::SpsNut, + nalu.header.type_ + )); + } + + let data = nalu.as_ref(); + let header = &nalu.header; + let hdr_len = header.len(); + // Skip the header + let mut r = BitReader::new(&data[hdr_len..], true); + + let video_parameter_set_id = r.read_bits(4)?; + + // A non-existing VPS means the SPS is not using any VPS. + let vps = self.get_vps(video_parameter_set_id).cloned(); + + let mut sps = Sps { + video_parameter_set_id, + max_sub_layers_minus1: r.read_bits(3)?, + temporal_id_nesting_flag: r.read_bit()?, + vps, + ..Default::default() + }; + + Self::parse_profile_tier_level( + &mut sps.profile_tier_level, + &mut r, + true, + sps.max_sub_layers_minus1, + )?; + + sps.seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?; + sps.chroma_format_idc = r.read_ue_max(3)?; + + if sps.chroma_format_idc == 3 { + sps.separate_colour_plane_flag = r.read_bit()?; + } + + sps.chroma_array_type = + if sps.separate_colour_plane_flag { 0 } else { sps.chroma_format_idc }; + + sps.pic_width_in_luma_samples = r.read_ue_bounded(1, 16888)?; + sps.pic_height_in_luma_samples = r.read_ue_bounded(1, 16888)?; + + sps.conformance_window_flag = r.read_bit()?; + if sps.conformance_window_flag { + sps.conf_win_left_offset = r.read_ue()?; + sps.conf_win_right_offset = r.read_ue()?; + sps.conf_win_top_offset = r.read_ue()?; + sps.conf_win_bottom_offset = r.read_ue()?; + } + + sps.bit_depth_luma_minus8 = r.read_ue_max(6)?; + sps.bit_depth_chroma_minus8 = r.read_ue_max(6)?; + sps.log2_max_pic_order_cnt_lsb_minus4 = r.read_ue_max(12)?; + sps.sub_layer_ordering_info_present_flag = r.read_bit()?; + + { + let i = if sps.sub_layer_ordering_info_present_flag { + 0 + } else { + sps.max_sub_layers_minus1 + }; + + for j in i..=sps.max_sub_layers_minus1 { + sps.max_dec_pic_buffering_minus1[j as usize] = r.read_ue_max(16)?; + sps.max_num_reorder_pics[j as usize] = + r.read_ue_max(sps.max_dec_pic_buffering_minus1[j as usize] as _)?; + sps.max_latency_increase_plus1[j as usize] = r.read_ue_max(u32::MAX - 1)?; + } + } + + sps.log2_min_luma_coding_block_size_minus3 = r.read_ue_max(3)?; + sps.log2_diff_max_min_luma_coding_block_size = r.read_ue_max(6)?; + sps.log2_min_luma_transform_block_size_minus2 = r.read_ue_max(3)?; + sps.log2_diff_max_min_luma_transform_block_size = r.read_ue_max(3)?; + + // (7-10) + sps.min_cb_log2_size_y = u32::from(sps.log2_min_luma_coding_block_size_minus3 + 3); + // (7-11) + sps.ctb_log2_size_y = + sps.min_cb_log2_size_y + u32::from(sps.log2_diff_max_min_luma_coding_block_size); + // (7-12) + sps.ctb_size_y = 1 << sps.ctb_log2_size_y; + // (7-17) + sps.pic_height_in_ctbs_y = + (sps.pic_height_in_luma_samples as f64 / sps.ctb_size_y as f64).ceil() as u32; + // (7-15) + sps.pic_width_in_ctbs_y = + (sps.pic_width_in_luma_samples as f64 / sps.ctb_size_y as f64).ceil() as u32; + + sps.max_tb_log2_size_y = u32::from( + sps.log2_min_luma_transform_block_size_minus2 + + 2 + + sps.log2_diff_max_min_luma_transform_block_size, + ); + + sps.pic_size_in_samples_y = + u32::from(sps.pic_width_in_luma_samples) * u32::from(sps.pic_height_in_luma_samples); + + if sps.max_tb_log2_size_y > std::cmp::min(sps.ctb_log2_size_y, 5) { + return Err(format!("Invalid value for MaxTbLog2SizeY: {}", sps.max_tb_log2_size_y)); + } + + sps.pic_size_in_ctbs_y = sps.pic_width_in_ctbs_y * sps.pic_height_in_ctbs_y; + + sps.max_transform_hierarchy_depth_inter = r.read_ue_max(4)?; + sps.max_transform_hierarchy_depth_intra = r.read_ue_max(4)?; + + sps.scaling_list_enabled_flag = r.read_bit()?; + if sps.scaling_list_enabled_flag { + sps.scaling_list_data_present_flag = r.read_bit()?; + if sps.scaling_list_data_present_flag { + Self::parse_scaling_list_data(&mut sps.scaling_list, &mut r)?; + } + } + + sps.amp_enabled_flag = r.read_bit()?; + sps.sample_adaptive_offset_enabled_flag = r.read_bit()?; + + sps.pcm_enabled_flag = r.read_bit()?; + if sps.pcm_enabled_flag { + sps.pcm_sample_bit_depth_luma_minus1 = r.read_bits(4)?; + sps.pcm_sample_bit_depth_chroma_minus1 = r.read_bits(4)?; + sps.log2_min_pcm_luma_coding_block_size_minus3 = r.read_ue_max(2)?; + sps.log2_diff_max_min_pcm_luma_coding_block_size = r.read_ue_max(2)?; + sps.pcm_loop_filter_disabled_flag = r.read_bit()?; + } + + sps.num_short_term_ref_pic_sets = r.read_ue_max(64)?; + + for i in 0..sps.num_short_term_ref_pic_sets { + let mut st = ShortTermRefPicSet::default(); + Self::parse_short_term_ref_pic_set(&sps, &mut st, &mut r, i)?; + sps.short_term_ref_pic_set.push(st); + } + + sps.long_term_ref_pics_present_flag = r.read_bit()?; + if sps.long_term_ref_pics_present_flag { + sps.num_long_term_ref_pics_sps = r.read_ue_max(32)?; + for i in 0..usize::from(sps.num_long_term_ref_pics_sps) { + sps.lt_ref_pic_poc_lsb_sps[i] = + r.read_bits(usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4)?; + sps.used_by_curr_pic_lt_sps_flag[i] = r.read_bit()?; + } + } + + sps.temporal_mvp_enabled_flag = r.read_bit()?; + sps.strong_intra_smoothing_enabled_flag = r.read_bit()?; + + sps.vui_parameters_present_flag = r.read_bit()?; + if sps.vui_parameters_present_flag { + Self::parse_vui_parameters(&mut sps, &mut r)?; + } + + sps.extension_present_flag = r.read_bit()?; + if sps.extension_present_flag { + sps.range_extension_flag = r.read_bit()?; + if sps.range_extension_flag { + Self::parse_sps_range_extension(&mut sps, &mut r)?; + } + + let multilayer_extension_flag = r.read_bit()?; + if multilayer_extension_flag { + return Err("Multilayer extension not supported.".into()); + } + + let three_d_extension_flag = r.read_bit()?; + if three_d_extension_flag { + return Err("3D extension not supported.".into()); + } + + sps.scc_extension_flag = r.read_bit()?; + if sps.scc_extension_flag { + Self::parse_sps_scc_extension(&mut sps, &mut r)?; + } + } + + let shift = if sps.range_extension.high_precision_offsets_enabled_flag { + sps.bit_depth_luma_minus8 + 7 + } else { + 7 + }; + + sps.wp_offset_half_range_y = 1 << shift; + + let shift = if sps.range_extension.high_precision_offsets_enabled_flag { + sps.bit_depth_chroma_minus8 + 7 + } else { + 7 + }; + + sps.wp_offset_half_range_c = 1 << shift; + + log::debug!( + "Parsed SPS({}), resolution: ({}, {}): NAL size was {}", + sps.seq_parameter_set_id, + sps.width(), + sps.height(), + nalu.size + ); + + if self.active_spses.keys().len() >= MAX_SPS_COUNT { + return Err("Broken data: Number of active SPSs > MAX_SPS_COUNT".into()); + } + + let key = sps.seq_parameter_set_id; + let sps = Rc::new(sps); + self.active_spses.remove(&key); + Ok(self.active_spses.entry(key).or_insert(sps)) + } + + fn parse_pps_scc_extension(pps: &mut Pps, sps: &Sps, r: &mut BitReader) -> Result<(), String> { + let scc = &mut pps.scc_extension; + scc.curr_pic_ref_enabled_flag = r.read_bit()?; + scc.residual_adaptive_colour_transform_enabled_flag = r.read_bit()?; + if scc.residual_adaptive_colour_transform_enabled_flag { + scc.slice_act_qp_offsets_present_flag = r.read_bit()?; + scc.act_y_qp_offset_plus5 = r.read_se_bounded(-7, 17)?; + scc.act_cb_qp_offset_plus5 = r.read_se_bounded(-7, 17)?; + scc.act_cr_qp_offset_plus3 = r.read_se_bounded(-9, 15)?; + } + + scc.palette_predictor_initializers_present_flag = r.read_bit()?; + if scc.palette_predictor_initializers_present_flag { + let max = sps.scc_extension.palette_max_size + + sps.scc_extension.delta_palette_max_predictor_size; + scc.num_palette_predictor_initializers = r.read_ue_max(max.into())?; + if scc.num_palette_predictor_initializers > 0 { + scc.monochrome_palette_flag = r.read_bit()?; + scc.luma_bit_depth_entry_minus8 = r.read_ue_bounded( + sps.bit_depth_luma_minus8.into(), + sps.bit_depth_luma_minus8.into(), + )?; + if !scc.monochrome_palette_flag { + scc.chroma_bit_depth_entry_minus8 = r.read_ue_bounded( + sps.bit_depth_chroma_minus8.into(), + sps.bit_depth_chroma_minus8.into(), + )?; + } + + let num_comps = if scc.monochrome_palette_flag { 1 } else { 3 }; + for comp in 0..num_comps { + let num_bits = if comp == 0 { + scc.luma_bit_depth_entry_minus8 + 8 + } else { + scc.chroma_bit_depth_entry_minus8 + 8 + }; + for i in 0..usize::from(scc.num_palette_predictor_initializers) { + scc.palette_predictor_initializer[comp][i] = + r.read_bits(num_bits.into())?; + } + } + } + } + Ok(()) + } + + fn parse_pps_range_extension( + pps: &mut Pps, + sps: &Sps, + r: &mut BitReader, + ) -> Result<(), String> { + let rext = &mut pps.range_extension; + + if pps.transform_skip_enabled_flag { + rext.log2_max_transform_skip_block_size_minus2 = + r.read_ue_max(sps.max_tb_log2_size_y - 2)?; + } + + rext.cross_component_prediction_enabled_flag = r.read_bit()?; + rext.chroma_qp_offset_list_enabled_flag = r.read_bit()?; + if rext.chroma_qp_offset_list_enabled_flag { + rext.diff_cu_chroma_qp_offset_depth = r.read_ue()?; + rext.chroma_qp_offset_list_len_minus1 = r.read_ue_max(5)?; + for i in 0..=rext.chroma_qp_offset_list_len_minus1 as usize { + rext.cb_qp_offset_list[i] = r.read_se_bounded(-12, 12)?; + rext.cr_qp_offset_list[i] = r.read_se_bounded(-12, 12)?; + } + } + + let bit_depth_y = sps.bit_depth_luma_minus8 + 8; + let max = u32::from(std::cmp::max(0, bit_depth_y - 10)); + + rext.log2_sao_offset_scale_luma = r.read_ue_max(max)?; + rext.log2_sao_offset_scale_chroma = r.read_ue_max(max)?; + + Ok(()) + } + + /// Parse a PPS NALU. + pub fn parse_pps(&mut self, nalu: &Nalu) -> Result<&Pps, String> { + if !matches!(nalu.header.type_, NaluType::PpsNut) { + return Err(format!( + "Invalid NALU type, expected {:?}, got {:?}", + NaluType::PpsNut, + nalu.header.type_ + )); + } + + let data = nalu.as_ref(); + let header = &nalu.header; + let hdr_len = header.len(); + // Skip the header + let mut r = BitReader::new(&data[hdr_len..], true); + + let pic_parameter_set_id = r.read_ue_max(MAX_PPS_COUNT as u32 - 1)?; + let seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?; + + let sps = self.get_sps(seq_parameter_set_id).ok_or::(format!( + "Could not get SPS for seq_parameter_set_id {}", + seq_parameter_set_id + ))?; + + let mut pps = Pps { + pic_parameter_set_id, + seq_parameter_set_id, + dependent_slice_segments_enabled_flag: Default::default(), + output_flag_present_flag: Default::default(), + num_extra_slice_header_bits: Default::default(), + sign_data_hiding_enabled_flag: Default::default(), + cabac_init_present_flag: Default::default(), + num_ref_idx_l0_default_active_minus1: Default::default(), + num_ref_idx_l1_default_active_minus1: Default::default(), + init_qp_minus26: Default::default(), + constrained_intra_pred_flag: Default::default(), + transform_skip_enabled_flag: Default::default(), + cu_qp_delta_enabled_flag: Default::default(), + diff_cu_qp_delta_depth: Default::default(), + cb_qp_offset: Default::default(), + cr_qp_offset: Default::default(), + slice_chroma_qp_offsets_present_flag: Default::default(), + weighted_pred_flag: Default::default(), + weighted_bipred_flag: Default::default(), + transquant_bypass_enabled_flag: Default::default(), + tiles_enabled_flag: Default::default(), + entropy_coding_sync_enabled_flag: Default::default(), + num_tile_columns_minus1: Default::default(), + num_tile_rows_minus1: Default::default(), + uniform_spacing_flag: true, + column_width_minus1: Default::default(), + row_height_minus1: Default::default(), + loop_filter_across_tiles_enabled_flag: true, + loop_filter_across_slices_enabled_flag: Default::default(), + deblocking_filter_control_present_flag: Default::default(), + deblocking_filter_override_enabled_flag: Default::default(), + deblocking_filter_disabled_flag: Default::default(), + beta_offset_div2: Default::default(), + tc_offset_div2: Default::default(), + scaling_list_data_present_flag: Default::default(), + scaling_list: Default::default(), + lists_modification_present_flag: Default::default(), + log2_parallel_merge_level_minus2: Default::default(), + slice_segment_header_extension_present_flag: Default::default(), + extension_present_flag: Default::default(), + range_extension_flag: Default::default(), + range_extension: Default::default(), + qp_bd_offset_y: Default::default(), + scc_extension: Default::default(), + scc_extension_flag: Default::default(), + sps: Rc::clone(sps), + }; + + pps.dependent_slice_segments_enabled_flag = r.read_bit()?; + pps.output_flag_present_flag = r.read_bit()?; + pps.num_extra_slice_header_bits = r.read_bits(3)?; + pps.sign_data_hiding_enabled_flag = r.read_bit()?; + pps.cabac_init_present_flag = r.read_bit()?; + + // 7.4.7.1 + pps.num_ref_idx_l0_default_active_minus1 = r.read_ue_max(14)?; + pps.num_ref_idx_l1_default_active_minus1 = r.read_ue_max(14)?; + + // (7-5) + let qp_bd_offset_y = 6 * i32::from(sps.bit_depth_luma_minus8); + + pps.init_qp_minus26 = r.read_se_bounded(-(26 + qp_bd_offset_y), 25)?; + pps.qp_bd_offset_y = qp_bd_offset_y as u32; + pps.constrained_intra_pred_flag = r.read_bit()?; + pps.transform_skip_enabled_flag = r.read_bit()?; + pps.cu_qp_delta_enabled_flag = r.read_bit()?; + + if pps.cu_qp_delta_enabled_flag { + pps.diff_cu_qp_delta_depth = + r.read_ue_max(u32::from(sps.log2_diff_max_min_luma_coding_block_size))?; + } + + pps.cb_qp_offset = r.read_se_bounded(-12, 12)?; + pps.cr_qp_offset = r.read_se_bounded(-12, 12)?; + + pps.slice_chroma_qp_offsets_present_flag = r.read_bit()?; + pps.weighted_pred_flag = r.read_bit()?; + pps.weighted_bipred_flag = r.read_bit()?; + pps.transquant_bypass_enabled_flag = r.read_bit()?; + pps.tiles_enabled_flag = r.read_bit()?; + pps.entropy_coding_sync_enabled_flag = r.read_bit()?; + + // A mix of the rbsp data and the algorithm in 6.5.1 + if pps.tiles_enabled_flag { + pps.num_tile_columns_minus1 = r.read_ue_max(sps.pic_width_in_ctbs_y - 1)?; + pps.num_tile_rows_minus1 = r.read_ue_max(sps.pic_height_in_ctbs_y - 1)?; + pps.uniform_spacing_flag = r.read_bit()?; + if !pps.uniform_spacing_flag { + pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] = + sps.pic_width_in_ctbs_y - 1; + + for i in 0..usize::from(pps.num_tile_columns_minus1) { + pps.column_width_minus1[i] = r.read_ue_max( + pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] - 1, + )?; + pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] -= + pps.column_width_minus1[i] + 1; + } + + pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] = + sps.pic_height_in_ctbs_y - 1; + + for i in 0..usize::from(pps.num_tile_rows_minus1) { + pps.row_height_minus1[i] = r.read_ue_max( + pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] - 1, + )?; + pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] -= + pps.row_height_minus1[i] + 1; + } + } else { + let nrows = u32::from(pps.num_tile_rows_minus1) + 1; + let ncols = u32::from(pps.num_tile_columns_minus1) + 1; + + for j in 0..ncols { + pps.column_width_minus1[j as usize] = ((j + 1) * sps.pic_width_in_ctbs_y) + / ncols + - j * sps.pic_width_in_ctbs_y / ncols + - 1; + } + + for j in 0..nrows { + pps.row_height_minus1[j as usize] = ((j + 1) * sps.pic_height_in_ctbs_y) + / nrows + - j * sps.pic_height_in_ctbs_y / nrows + - 1; + } + } + + pps.loop_filter_across_tiles_enabled_flag = r.read_bit()?; + } + + pps.loop_filter_across_slices_enabled_flag = r.read_bit()?; + pps.deblocking_filter_control_present_flag = r.read_bit()?; + + if pps.deblocking_filter_control_present_flag { + pps.deblocking_filter_override_enabled_flag = r.read_bit()?; + pps.deblocking_filter_disabled_flag = r.read_bit()?; + if !pps.deblocking_filter_disabled_flag { + pps.beta_offset_div2 = r.read_se_bounded(-6, 6)?; + pps.tc_offset_div2 = r.read_se_bounded(-6, 6)?; + } + } + + pps.scaling_list_data_present_flag = r.read_bit()?; + + if pps.scaling_list_data_present_flag { + Self::parse_scaling_list_data(&mut pps.scaling_list, &mut r)?; + } else { + for size_id in 0..4 { + let mut matrix_id = 0; + while matrix_id < 6 { + Self::fill_default_scaling_list(&mut pps.scaling_list, size_id, matrix_id); + let step = if size_id == 3 { 3 } else { 1 }; + matrix_id += step; + } + } + } + + pps.lists_modification_present_flag = r.read_bit()?; + pps.log2_parallel_merge_level_minus2 = r.read_ue_max(sps.ctb_log2_size_y - 2)?; + pps.slice_segment_header_extension_present_flag = r.read_bit()?; + + pps.extension_present_flag = r.read_bit()?; + if pps.extension_present_flag { + pps.range_extension_flag = r.read_bit()?; + + if pps.range_extension_flag { + Self::parse_pps_range_extension(&mut pps, sps, &mut r)?; + } + + let multilayer_extension_flag = r.read_bit()?; + if multilayer_extension_flag { + return Err("Multilayer extension is not supported".into()); + } + + let three_d_extension_flag = r.read_bit()?; + if three_d_extension_flag { + return Err("3D extension is not supported".into()); + } + + pps.scc_extension_flag = r.read_bit()?; + if pps.scc_extension_flag { + Self::parse_pps_scc_extension(&mut pps, sps, &mut r)?; + } + + r.skip_bits(4)?; // pps_extension_4bits + } + + log::debug!("Parsed PPS({}), NAL size was {}", pps.pic_parameter_set_id, nalu.size); + + if self.active_ppses.keys().len() >= MAX_PPS_COUNT { + return Err("Broken Data: number of active PPSs > MAX_PPS_COUNT".into()); + } + + let key = pps.pic_parameter_set_id; + let pps = Rc::new(pps); + self.active_ppses.remove(&key); + Ok(self.active_ppses.entry(key).or_insert(pps)) + } + + fn parse_pred_weight_table( + hdr: &mut SliceHeader, + r: &mut BitReader, + sps: &Sps, + ) -> Result<(), String> { + let pwt = &mut hdr.pred_weight_table; + + pwt.luma_log2_weight_denom = r.read_ue_max(7)?; + if sps.chroma_array_type != 0 { + pwt.delta_chroma_log2_weight_denom = r.read_se()?; + pwt.chroma_log2_weight_denom = (pwt.luma_log2_weight_denom as i32 + + pwt.delta_chroma_log2_weight_denom as i32) + .try_into() + .map_err(|_| { + String::from("Integer overflow on chroma_log2_weight_denom calculation") + })?; + } + + for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { + pwt.luma_weight_l0_flag[i] = r.read_bit()?; + } + + if sps.chroma_array_type != 0 { + for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { + pwt.chroma_weight_l0_flag[i] = r.read_bit()?; + } + } + + for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { + if pwt.luma_weight_l0_flag[i] { + pwt.delta_luma_weight_l0[i] = r.read_se_bounded(-128, 127)?; + pwt.luma_offset_l0[i] = r.read_se_bounded(-128, 127)?; + } + + if pwt.chroma_weight_l0_flag[i] { + for j in 0..2 { + pwt.delta_chroma_weight_l0[i][j] = r.read_se_bounded(-128, 127)?; + pwt.delta_chroma_offset_l0[i][j] = r.read_se_bounded( + -4 * sps.wp_offset_half_range_c as i32, + 4 * sps.wp_offset_half_range_c as i32 - 1, + )?; + } + } + } + + if hdr.type_.is_b() { + for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { + pwt.luma_weight_l1_flag[i] = r.read_bit()?; + } + + if sps.chroma_format_idc != 0 { + for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { + pwt.chroma_weight_l1_flag[i] = r.read_bit()?; + } + } + + for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { + if pwt.luma_weight_l1_flag[i] { + pwt.delta_luma_weight_l1[i] = r.read_se_bounded(-128, 127)?; + pwt.luma_offset_l1[i] = r.read_se_bounded(-128, 127)?; + } + + if pwt.chroma_weight_l1_flag[i] { + for j in 0..2 { + pwt.delta_chroma_weight_l1[i][j] = r.read_se_bounded(-128, 127)?; + pwt.delta_chroma_offset_l1[i][j] = r.read_se_bounded( + -4 * sps.wp_offset_half_range_c as i32, + 4 * sps.wp_offset_half_range_c as i32 - 1, + )?; + } + } + } + } + + Ok(()) + } + + fn parse_ref_pic_lists_modification( + hdr: &mut SliceHeader, + r: &mut BitReader, + ) -> Result<(), String> { + let rplm = &mut hdr.ref_pic_list_modification; + + rplm.ref_pic_list_modification_flag_l0 = r.read_bit()?; + if rplm.ref_pic_list_modification_flag_l0 { + for _ in 0..=hdr.num_ref_idx_l0_active_minus1 { + let num_bits = (hdr.num_pic_total_curr as f64).log2().ceil() as _; + + let entry = r.read_bits(num_bits)?; + + if entry > hdr.num_pic_total_curr - 1 { + return Err(format!( + "Invalid list_entry_l0 {}, expected at max NumPicTotalCurr - 1: {}", + entry, + hdr.num_pic_total_curr - 1 + )); + } + + rplm.list_entry_l0.push(entry); + } + } + + if hdr.type_.is_b() { + rplm.ref_pic_list_modification_flag_l1 = r.read_bit()?; + if rplm.ref_pic_list_modification_flag_l1 { + for _ in 0..=hdr.num_ref_idx_l1_active_minus1 { + let num_bits = (hdr.num_pic_total_curr as f64).log2().ceil() as _; + + let entry = r.read_bits(num_bits)?; + + if entry > hdr.num_pic_total_curr - 1 { + return Err(format!( + "Invalid list_entry_l1 {}, expected at max NumPicTotalCurr - 1: {}", + entry, + hdr.num_pic_total_curr - 1 + )); + } + + rplm.list_entry_l1.push(entry); + } + } + } + + Ok(()) + } + + /// Further sets default values given `sps` and `pps`. + pub fn slice_header_set_defaults(hdr: &mut SliceHeader, sps: &Sps, pps: &Pps) { + // Set some defaults that can't be defined in Default::default(). + hdr.deblocking_filter_disabled_flag = pps.deblocking_filter_disabled_flag; + hdr.beta_offset_div2 = pps.beta_offset_div2; + hdr.tc_offset_div2 = pps.tc_offset_div2; + hdr.loop_filter_across_slices_enabled_flag = pps.loop_filter_across_slices_enabled_flag; + hdr.curr_rps_idx = sps.num_short_term_ref_pic_sets; + hdr.use_integer_mv_flag = sps.scc_extension.motion_vector_resolution_control_idc != 0; + } + + /// Parses a slice header from a slice NALU. + pub fn parse_slice_header<'a>(&mut self, nalu: Nalu<'a>) -> Result, String> { + if !matches!( + nalu.header.type_, + NaluType::TrailN + | NaluType::TrailR + | NaluType::TsaN + | NaluType::TsaR + | NaluType::StsaN + | NaluType::StsaR + | NaluType::RadlN + | NaluType::RadlR + | NaluType::RaslN + | NaluType::RaslR + | NaluType::BlaWLp + | NaluType::BlaWRadl + | NaluType::BlaNLp + | NaluType::IdrWRadl + | NaluType::IdrNLp + | NaluType::CraNut, + ) { + return Err(format!("Invalid NALU type: {:?} is not a slice NALU", nalu.header.type_)); + } + + let data = nalu.as_ref(); + let nalu_header = &nalu.header; + let hdr_len = nalu_header.len(); + // Skip the header + let mut r = BitReader::new(&data[hdr_len..], true); + + let mut hdr = + SliceHeader { first_slice_segment_in_pic_flag: r.read_bit()?, ..Default::default() }; + + if nalu.header.type_.is_irap() { + hdr.no_output_of_prior_pics_flag = r.read_bit()?; + } + + hdr.pic_parameter_set_id = r.read_ue_max(63)?; + + let pps = self.get_pps(hdr.pic_parameter_set_id).ok_or::(format!( + "Could not get PPS for pic_parameter_set_id {}", + hdr.pic_parameter_set_id + ))?; + + let sps = &pps.sps; + + Self::slice_header_set_defaults(&mut hdr, sps, pps); + + if !hdr.first_slice_segment_in_pic_flag { + if pps.dependent_slice_segments_enabled_flag { + hdr.dependent_slice_segment_flag = r.read_bit()?; + } + + let num_bits = (sps.pic_size_in_ctbs_y as f64).log2().ceil() as _; + hdr.segment_address = r.read_bits(num_bits)?; + + if hdr.segment_address > sps.pic_size_in_ctbs_y - 1 { + return Err(format!("Invalid slice_segment_address {}", hdr.segment_address)); + } + } + + if !hdr.dependent_slice_segment_flag { + r.skip_bits(usize::from(pps.num_extra_slice_header_bits))?; + + let slice_type: u32 = r.read_ue()?; + hdr.type_ = SliceType::try_from(slice_type)?; + + if pps.output_flag_present_flag { + hdr.pic_output_flag = r.read_bit()?; + } + + if sps.separate_colour_plane_flag { + hdr.colour_plane_id = r.read_bits(2)?; + } + + if !matches!(nalu_header.type_, NaluType::IdrWRadl | NaluType::IdrNLp) { + let num_bits = usize::from(sps.log2_max_pic_order_cnt_lsb_minus4 + 4); + hdr.pic_order_cnt_lsb = r.read_bits(num_bits)?; + + if u32::from(hdr.pic_order_cnt_lsb) + > 2u32.pow(u32::from(sps.log2_max_pic_order_cnt_lsb_minus4 + 4)) + { + return Err(format!("Invalid pic_order_cnt_lsb {}", hdr.pic_order_cnt_lsb)); + } + + hdr.short_term_ref_pic_set_sps_flag = r.read_bit()?; + + if !hdr.short_term_ref_pic_set_sps_flag { + let epb_before = r.num_epb(); + let bits_left_before = r.num_bits_left(); + + let st_rps_idx = sps.num_short_term_ref_pic_sets; + + Self::parse_short_term_ref_pic_set( + sps, + &mut hdr.short_term_ref_pic_set, + &mut r, + st_rps_idx, + )?; + + hdr.st_rps_bits = ((bits_left_before - r.num_bits_left()) + - 8 * (r.num_epb() - epb_before)) + as u32; + } else if sps.num_short_term_ref_pic_sets > 1 { + let num_bits = (sps.num_short_term_ref_pic_sets as f64).log2().ceil() as _; + hdr.short_term_ref_pic_set_idx = r.read_bits(num_bits)?; + + if hdr.short_term_ref_pic_set_idx > sps.num_short_term_ref_pic_sets - 1 { + return Err(format!( + "Invalid short_term_ref_pic_set_idx {}", + hdr.short_term_ref_pic_set_idx + )); + } + } + + if hdr.short_term_ref_pic_set_sps_flag { + hdr.curr_rps_idx = hdr.short_term_ref_pic_set_idx; + } + + if sps.long_term_ref_pics_present_flag { + if sps.num_long_term_ref_pics_sps > 0 { + hdr.num_long_term_sps = + r.read_ue_max(u32::from(sps.num_long_term_ref_pics_sps))?; + } + + hdr.num_long_term_pics = r.read_ue_max( + MAX_LONG_TERM_REF_PIC_SETS as u32 - u32::from(hdr.num_long_term_sps), + )?; + + let num_lt = hdr.num_long_term_sps + hdr.num_long_term_pics; + for i in 0..usize::from(num_lt) { + // The variables `PocLsbLt[ i ]` and `UsedByCurrPicLt[ i ]` are derived as follows: + // + // – If i is less than num_long_term_sps, `PocLsbLt[ i ]` is set equal to + // lt_ref_pic_poc_lsb_sps[ `lt_idx_sps[ i ]` ] and `UsedByCurrPicLt[ i ]` is set equal + // to used_by_curr_pic_lt_sps_flag[ `lt_idx_sps[ i ]` ]. + // + // – Otherwise, `PocLsbLt[ i ]` + // is set equal to `poc_lsb_lt[ i ]` and `UsedByCurrPicLt[ i ]` is set equal to + // `used_by_curr_pic_lt_flag[ i ]`. + if i < usize::from(hdr.num_long_term_sps) { + if sps.num_long_term_ref_pics_sps > 1 { + let num_bits = + (sps.num_long_term_ref_pics_sps as f64).log2().ceil() as _; + + hdr.lt_idx_sps[i] = r.read_bits(num_bits)?; + + if hdr.lt_idx_sps[i] > sps.num_long_term_ref_pics_sps - 1 { + return Err(format!( + "Invalid lt_idx_sps[{}] {}", + i, hdr.lt_idx_sps[i] + )); + } + } + + hdr.poc_lsb_lt[i] = + sps.lt_ref_pic_poc_lsb_sps[usize::from(hdr.lt_idx_sps[i])]; + hdr.used_by_curr_pic_lt[i] = + sps.used_by_curr_pic_lt_sps_flag[usize::from(hdr.lt_idx_sps[i])]; + } else { + let num_bits = usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4; + hdr.poc_lsb_lt[i] = r.read_bits(num_bits)?; + hdr.used_by_curr_pic_lt[i] = r.read_bit()?; + } + + hdr.delta_poc_msb_present_flag[i] = r.read_bit()?; + if hdr.delta_poc_msb_present_flag[i] { + // The value of `delta_poc_msb_cycle_lt[ i ]` shall be + // in the range of 0 to 2(32 − + // log2_max_pic_order_cnt_lsb_minus4 − 4 ), + // inclusive. When `delta_poc_msb_cycle_lt[ i ]` is + // not present, it is inferred to be equal to 0. + let max = + 2u32.pow(32 - u32::from(sps.log2_max_pic_order_cnt_lsb_minus4) - 4); + hdr.delta_poc_msb_cycle_lt[i] = r.read_ue_max(max)?; + } + // Equation 7-52 (simplified) + if i != 0 && i != usize::from(hdr.num_long_term_sps) { + hdr.delta_poc_msb_cycle_lt[i] += hdr.delta_poc_msb_cycle_lt[i - 1]; + } + } + } + + if sps.temporal_mvp_enabled_flag { + hdr.temporal_mvp_enabled_flag = r.read_bit()?; + } + } + + if sps.sample_adaptive_offset_enabled_flag { + hdr.sao_luma_flag = r.read_bit()?; + if sps.chroma_array_type != 0 { + hdr.sao_chroma_flag = r.read_bit()?; + } + } + + if hdr.type_.is_p() || hdr.type_.is_b() { + hdr.num_ref_idx_active_override_flag = r.read_bit()?; + if hdr.num_ref_idx_active_override_flag { + hdr.num_ref_idx_l0_active_minus1 = r.read_ue_max(MAX_REF_IDX_ACTIVE - 1)?; + if hdr.type_.is_b() { + hdr.num_ref_idx_l1_active_minus1 = r.read_ue_max(MAX_REF_IDX_ACTIVE - 1)?; + } + } else { + hdr.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1; + hdr.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1; + } + + // 7-57 + let mut num_pic_total_curr = 0; + let rps = if hdr.short_term_ref_pic_set_sps_flag { + sps.short_term_ref_pic_set + .get(usize::from(hdr.curr_rps_idx)) + .ok_or::("Invalid RPS".into())? + } else { + &hdr.short_term_ref_pic_set + }; + + for i in 0..usize::from(rps.num_negative_pics) { + if rps.used_by_curr_pic_s0[i] { + num_pic_total_curr += 1; + } + } + + for i in 0..usize::from(rps.num_positive_pics) { + if rps.used_by_curr_pic_s1[i] { + num_pic_total_curr += 1; + } + } + + for i in 0..usize::from(hdr.num_long_term_sps + hdr.num_long_term_pics) { + if hdr.used_by_curr_pic_lt[i] { + num_pic_total_curr += 1; + } + } + + if pps.scc_extension.curr_pic_ref_enabled_flag { + num_pic_total_curr += 1; + } + + hdr.num_pic_total_curr = num_pic_total_curr; + + if pps.lists_modification_present_flag && hdr.num_pic_total_curr > 1 { + Self::parse_ref_pic_lists_modification(&mut hdr, &mut r)?; + } + + if hdr.type_.is_b() { + hdr.mvd_l1_zero_flag = r.read_bit()?; + } + + if pps.cabac_init_present_flag { + hdr.cabac_init_flag = r.read_bit()?; + } + + if hdr.temporal_mvp_enabled_flag { + if hdr.type_.is_b() { + hdr.collocated_from_l0_flag = r.read_bit()?; + } + + if (hdr.collocated_from_l0_flag && hdr.num_ref_idx_l0_active_minus1 > 0) + || (!hdr.collocated_from_l0_flag && hdr.num_ref_idx_l1_active_minus1 > 0) + { + let max = if (hdr.type_.is_p() || hdr.type_.is_b()) + && hdr.collocated_from_l0_flag + { + hdr.num_ref_idx_l0_active_minus1 + } else if hdr.type_.is_b() && !hdr.collocated_from_l0_flag { + hdr.num_ref_idx_l1_active_minus1 + } else { + return Err("Invalid value for collocated_ref_idx".into()); + }; + + { + hdr.collocated_ref_idx = r.read_ue_max(u32::from(max))?; + } + } + } + + if (pps.weighted_pred_flag && hdr.type_.is_p()) + || (pps.weighted_bipred_flag && hdr.type_.is_b()) + { + Self::parse_pred_weight_table(&mut hdr, &mut r, sps)?; + } + + hdr.five_minus_max_num_merge_cand = r.read_ue()?; + + if sps.scc_extension.motion_vector_resolution_control_idc == 2 { + hdr.use_integer_mv_flag = r.read_bit()?; + } + } + + hdr.qp_delta = r.read_se_bounded(-87, 77)?; + + let slice_qp_y = (26 + pps.init_qp_minus26 + hdr.qp_delta) as i32; + if slice_qp_y < -(pps.qp_bd_offset_y as i32) || slice_qp_y > 51 { + return Err(format!("Invalid slice_qp_delta: {}", hdr.qp_delta)); + } + + if pps.slice_chroma_qp_offsets_present_flag { + hdr.cb_qp_offset = r.read_se_bounded(-12, 12)?; + + let qp_offset = pps.cb_qp_offset + hdr.cb_qp_offset; + if !(-12..=12).contains(&qp_offset) { + return Err(format!( + "Invalid value for slice_cb_qp_offset: {}", + hdr.cb_qp_offset + )); + } + + hdr.cr_qp_offset = r.read_se_bounded(-12, 12)?; + + let qp_offset = pps.cr_qp_offset + hdr.cr_qp_offset; + if !(-12..=12).contains(&qp_offset) { + return Err(format!( + "Invalid value for slice_cr_qp_offset: {}", + hdr.cr_qp_offset + )); + } + } + + if pps.scc_extension.slice_act_qp_offsets_present_flag { + hdr.slice_act_y_qp_offset = r.read_se_bounded(-12, 12)?; + hdr.slice_act_cb_qp_offset = r.read_se_bounded(-12, 12)?; + hdr.slice_act_cr_qp_offset = r.read_se_bounded(-12, 12)?; + } + + if pps.range_extension.chroma_qp_offset_list_enabled_flag { + hdr.cu_chroma_qp_offset_enabled_flag = r.read_bit()?; + } + + if pps.deblocking_filter_override_enabled_flag { + hdr.deblocking_filter_override_flag = r.read_bit()?; + } + + if hdr.deblocking_filter_override_flag { + hdr.deblocking_filter_disabled_flag = r.read_bit()?; + if !hdr.deblocking_filter_disabled_flag { + hdr.beta_offset_div2 = r.read_se_bounded(-6, 6)?; + hdr.tc_offset_div2 = r.read_se_bounded(-6, 6)?; + } + } + + if pps.loop_filter_across_slices_enabled_flag + && (hdr.sao_luma_flag + || hdr.sao_chroma_flag + || !hdr.deblocking_filter_disabled_flag) + { + hdr.loop_filter_across_slices_enabled_flag = r.read_bit()?; + } + } + + if pps.tiles_enabled_flag || pps.entropy_coding_sync_enabled_flag { + let max = if !pps.tiles_enabled_flag && pps.entropy_coding_sync_enabled_flag { + sps.pic_height_in_ctbs_y - 1 + } else if pps.tiles_enabled_flag && !pps.entropy_coding_sync_enabled_flag { + u32::from((pps.num_tile_columns_minus1 + 1) * (pps.num_tile_rows_minus1 + 1) - 1) + } else { + (u32::from(pps.num_tile_columns_minus1) + 1) * sps.pic_height_in_ctbs_y - 1 + }; + + hdr.num_entry_point_offsets = r.read_ue_max(max)?; + if hdr.num_entry_point_offsets > 0 { + hdr.offset_len_minus1 = r.read_ue_max(31)?; + for i in 0..hdr.num_entry_point_offsets as usize { + let num_bits = usize::from(hdr.offset_len_minus1 + 1); + hdr.entry_point_offset_minus1[i] = r.read_bits(num_bits)?; + } + } + } + + if pps.slice_segment_header_extension_present_flag { + let segment_header_extension_length = r.read_ue_max(256)?; + for _ in 0..segment_header_extension_length { + r.skip_bits(8)?; // slice_segment_header_extension_data_byte[i] + } + } + + // byte_alignment() + r.skip_bits(1)?; // Alignment bit + let num_bits = r.num_bits_left() % 8; + r.skip_bits(num_bits)?; + + let epb = r.num_epb(); + hdr.header_bit_size = ((nalu.size - epb) * 8 - r.num_bits_left()) as u32; + + hdr.n_emulation_prevention_bytes = epb as u32; + + log::debug!("Parsed slice {:?}, NAL size was {}", nalu_header.type_, nalu.size); + + Ok(Slice { header: hdr, nalu }) + } + + /// Returns a previously parsed vps given `vps_id`, if any. + pub fn get_vps(&self, vps_id: u8) -> Option<&Rc> { + self.active_vpses.get(&vps_id) + } + + /// Returns a previously parsed sps given `sps_id`, if any. + pub fn get_sps(&self, sps_id: u8) -> Option<&Rc> { + self.active_spses.get(&sps_id) + } + + /// Returns a previously parsed pps given `pps_id`, if any. + pub fn get_pps(&self, pps_id: u8) -> Option<&Rc> { + self.active_ppses.get(&pps_id) + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use crate::codec::h264::nalu::Nalu; + use crate::codec::h265::parser::Level; + use crate::codec::h265::parser::NaluHeader; + use crate::codec::h265::parser::NaluType; + use crate::codec::h265::parser::Parser; + use crate::codec::h265::parser::SliceType; + + const STREAM_BEAR: &[u8] = include_bytes!("test_data/bear.h265"); + const STREAM_BEAR_NUM_NALUS: usize = 35; + + const STREAM_BBB: &[u8] = include_bytes!("test_data/bbb.h265"); + const STREAM_BBB_NUM_NALUS: usize = 64; + + const STREAM_TEST25FPS: &[u8] = include_bytes!("test_data/test-25fps.h265"); + const STREAM_TEST25FPS_NUM_NALUS: usize = 254; + + const STREAM_TEST_25_FPS_SLICE_0: &[u8] = + include_bytes!("test_data/test-25fps-h265-slice-data-0.bin"); + const STREAM_TEST_25_FPS_SLICE_1: &[u8] = + include_bytes!("test_data/test-25fps-h265-slice-data-1.bin"); + + fn dispatch_parse_call(parser: &mut Parser, nalu: Nalu) -> Result<(), String> { + match nalu.header.type_ { + NaluType::TrailN + | NaluType::TrailR + | NaluType::TsaN + | NaluType::TsaR + | NaluType::StsaN + | NaluType::StsaR + | NaluType::RadlN + | NaluType::RadlR + | NaluType::RaslN + | NaluType::RaslR + | NaluType::BlaWLp + | NaluType::BlaWRadl + | NaluType::BlaNLp + | NaluType::IdrWRadl + | NaluType::IdrNLp + | NaluType::CraNut => { + parser.parse_slice_header(nalu).unwrap(); + } + NaluType::VpsNut => { + parser.parse_vps(&nalu).unwrap(); + } + NaluType::SpsNut => { + parser.parse_sps(&nalu).unwrap(); + } + NaluType::PpsNut => { + parser.parse_pps(&nalu).unwrap(); + } + _ => { /* ignore */ } + } + Ok(()) + } + + fn find_nalu_by_type( + bitstream: &[u8], + nalu_type: NaluType, + mut nskip: i32, + ) -> Option> { + let mut cursor = Cursor::new(bitstream); + while let Ok(nalu) = Nalu::::next(&mut cursor) { + if nalu.header.type_ == nalu_type { + if nskip == 0 { + return Some(nalu); + } else { + nskip -= 1; + } + } + } + + None + } + + /// This test is adapted from chromium, available at media/video/h265_parser_unittest.cc + #[test] + fn parse_nalus_from_stream_file() { + let mut cursor = Cursor::new(STREAM_BEAR); + let mut num_nalus = 0; + while Nalu::::next(&mut cursor).is_ok() { + num_nalus += 1; + } + + assert_eq!(num_nalus, STREAM_BEAR_NUM_NALUS); + + let mut cursor = Cursor::new(STREAM_BBB); + let mut num_nalus = 0; + while Nalu::::next(&mut cursor).is_ok() { + num_nalus += 1; + } + + assert_eq!(num_nalus, STREAM_BBB_NUM_NALUS); + + let mut cursor = Cursor::new(STREAM_TEST25FPS); + let mut num_nalus = 0; + while Nalu::::next(&mut cursor).is_ok() { + num_nalus += 1; + } + + assert_eq!(num_nalus, STREAM_TEST25FPS_NUM_NALUS); + } + + /// Parse the syntax, making sure we can parse the files without crashing. + /// Does not check whether the parsed values are correct. + #[test] + fn parse_syntax_from_nals() { + let mut cursor = Cursor::new(STREAM_BBB); + let mut parser = Parser::default(); + + while let Ok(nalu) = Nalu::::next(&mut cursor) { + dispatch_parse_call(&mut parser, nalu).unwrap(); + } + + let mut cursor = Cursor::new(STREAM_BEAR); + let mut parser = Parser::default(); + + while let Ok(nalu) = Nalu::::next(&mut cursor) { + dispatch_parse_call(&mut parser, nalu).unwrap(); + } + + let mut cursor = Cursor::new(STREAM_TEST25FPS); + let mut parser = Parser::default(); + + while let Ok(nalu) = Nalu::::next(&mut cursor) { + dispatch_parse_call(&mut parser, nalu).unwrap(); + } + } + + /// Adapted from Chromium (media/video/h265_parser_unittest.cc::VpsParsing()) + #[test] + fn chromium_vps_parsing() { + let mut cursor = Cursor::new(STREAM_BEAR); + let mut parser = Parser::default(); + + let vps_nalu = Nalu::::next(&mut cursor).unwrap(); + let vps = parser.parse_vps(&vps_nalu).unwrap(); + + assert!(vps.base_layer_internal_flag); + assert!(vps.base_layer_available_flag); + assert_eq!(vps.max_layers_minus1, 0); + assert_eq!(vps.max_sub_layers_minus1, 0); + assert!(vps.temporal_id_nesting_flag); + assert_eq!(vps.profile_tier_level.general_profile_idc, 1); + assert_eq!(vps.profile_tier_level.general_level_idc, Level::L2); + assert_eq!(vps.max_dec_pic_buffering_minus1[0], 4); + assert_eq!(vps.max_num_reorder_pics[0], 2); + assert_eq!(vps.max_latency_increase_plus1[0], 0); + for i in 1..7 { + assert_eq!(vps.max_dec_pic_buffering_minus1[i], 0); + assert_eq!(vps.max_num_reorder_pics[i], 0); + assert_eq!(vps.max_latency_increase_plus1[i], 0); + } + assert_eq!(vps.max_layer_id, 0); + assert_eq!(vps.num_layer_sets_minus1, 0); + assert!(!vps.timing_info_present_flag); + } + + /// Adapted from Chromium (media/video/h265_parser_unittest.cc::SpsParsing()) + #[test] + fn chromium_sps_parsing() { + let mut parser = Parser::default(); + let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap(); + let sps = parser.parse_sps(&sps_nalu).unwrap(); + + assert_eq!(sps.max_sub_layers_minus1, 0); + assert_eq!(sps.profile_tier_level.general_profile_idc, 1); + assert_eq!(sps.profile_tier_level.general_level_idc, Level::L2); + assert_eq!(sps.seq_parameter_set_id, 0); + assert_eq!(sps.chroma_format_idc, 1); + assert!(!sps.separate_colour_plane_flag); + assert_eq!(sps.pic_width_in_luma_samples, 320); + assert_eq!(sps.pic_height_in_luma_samples, 184); + assert_eq!(sps.conf_win_left_offset, 0); + assert_eq!(sps.conf_win_right_offset, 0); + assert_eq!(sps.conf_win_top_offset, 0); + assert_eq!(sps.conf_win_bottom_offset, 2); + assert_eq!(sps.bit_depth_luma_minus8, 0); + assert_eq!(sps.bit_depth_chroma_minus8, 0); + assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 4); + assert_eq!(sps.max_dec_pic_buffering_minus1[0], 4); + assert_eq!(sps.max_num_reorder_pics[0], 2); + assert_eq!(sps.max_latency_increase_plus1[0], 0); + for i in 1..7 { + assert_eq!(sps.max_dec_pic_buffering_minus1[i], 0); + assert_eq!(sps.max_num_reorder_pics[i], 0); + assert_eq!(sps.max_latency_increase_plus1[i], 0); + } + assert_eq!(sps.log2_min_luma_coding_block_size_minus3, 0); + assert_eq!(sps.log2_diff_max_min_luma_coding_block_size, 3); + assert_eq!(sps.log2_min_luma_transform_block_size_minus2, 0); + assert_eq!(sps.log2_diff_max_min_luma_transform_block_size, 3); + assert_eq!(sps.max_transform_hierarchy_depth_inter, 0); + assert_eq!(sps.max_transform_hierarchy_depth_intra, 0); + assert!(!sps.scaling_list_enabled_flag); + assert!(!sps.scaling_list_data_present_flag); + assert!(!sps.amp_enabled_flag); + assert!(sps.sample_adaptive_offset_enabled_flag); + assert!(!sps.pcm_enabled_flag); + assert_eq!(sps.pcm_sample_bit_depth_luma_minus1, 0); + assert_eq!(sps.pcm_sample_bit_depth_chroma_minus1, 0); + assert_eq!(sps.log2_min_pcm_luma_coding_block_size_minus3, 0); + assert_eq!(sps.log2_diff_max_min_pcm_luma_coding_block_size, 0); + assert!(!sps.pcm_loop_filter_disabled_flag); + assert_eq!(sps.num_short_term_ref_pic_sets, 0); + assert_eq!(sps.num_long_term_ref_pics_sps, 0); + assert!(sps.temporal_mvp_enabled_flag); + assert!(sps.strong_intra_smoothing_enabled_flag); + assert_eq!(sps.vui_parameters.sar_width, 0); + assert_eq!(sps.vui_parameters.sar_height, 0); + assert!(!sps.vui_parameters.video_full_range_flag); + assert!(!sps.vui_parameters.colour_description_present_flag); + + // Note: the original test has 0 for the three variables below, but they + // have valid defaults in the spec (i.e.: 2). + assert_eq!(sps.vui_parameters.colour_primaries, 2); + assert_eq!(sps.vui_parameters.transfer_characteristics, 2); + assert_eq!(sps.vui_parameters.matrix_coeffs, 2); + + assert_eq!(sps.vui_parameters.def_disp_win_left_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_right_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_top_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_bottom_offset, 0); + } + + /// Adapted from Chromium (media/video/h265_parser_unittest.cc::PpsParsing()) + #[test] + fn chromium_pps_parsing() { + let mut parser = Parser::default(); + + // Have to parse the SPS to set up the parser's internal state. + let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap(); + parser.parse_sps(&sps_nalu).unwrap(); + + let pps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::PpsNut, 0).unwrap(); + let pps = parser.parse_pps(&pps_nalu).unwrap(); + + assert_eq!(pps.pic_parameter_set_id, 0); + assert_eq!(pps.seq_parameter_set_id, 0); + assert!(!pps.dependent_slice_segments_enabled_flag); + assert!(!pps.output_flag_present_flag); + assert_eq!(pps.num_extra_slice_header_bits, 0); + assert!(pps.sign_data_hiding_enabled_flag); + assert!(!pps.cabac_init_present_flag); + assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0); + assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0); + assert_eq!(pps.init_qp_minus26, 0); + assert!(!pps.constrained_intra_pred_flag); + assert!(!pps.transform_skip_enabled_flag); + assert!(pps.cu_qp_delta_enabled_flag); + assert_eq!(pps.diff_cu_qp_delta_depth, 0); + assert_eq!(pps.cb_qp_offset, 0); + assert_eq!(pps.cr_qp_offset, 0); + assert!(!pps.slice_chroma_qp_offsets_present_flag); + assert!(pps.weighted_pred_flag); + assert!(!pps.weighted_bipred_flag); + assert!(!pps.transquant_bypass_enabled_flag); + assert!(!pps.tiles_enabled_flag); + assert!(pps.entropy_coding_sync_enabled_flag); + assert!(pps.loop_filter_across_tiles_enabled_flag); + assert!(!pps.scaling_list_data_present_flag); + assert!(!pps.lists_modification_present_flag); + assert_eq!(pps.log2_parallel_merge_level_minus2, 0); + assert!(!pps.slice_segment_header_extension_present_flag); + } + + /// Adapted from Chromium (media/video/h265_parser_unittest.cc::SliceHeaderParsing()) + #[test] + fn chromium_slice_header_parsing() { + let mut parser = Parser::default(); + + // Have to parse the SPS/VPS/PPS to set up the parser's internal state. + let vps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::VpsNut, 0).unwrap(); + parser.parse_vps(&vps_nalu).unwrap(); + + let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap(); + parser.parse_sps(&sps_nalu).unwrap(); + + let pps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::PpsNut, 0).unwrap(); + parser.parse_pps(&pps_nalu).unwrap(); + + // Just like the Chromium test, do an IDR slice, then a non IDR slice. + let slice_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::IdrWRadl, 0).unwrap(); + let slice = parser.parse_slice_header(slice_nalu).unwrap(); + let hdr = &slice.header; + assert!(hdr.first_slice_segment_in_pic_flag); + assert!(!hdr.no_output_of_prior_pics_flag); + assert_eq!(hdr.pic_parameter_set_id, 0); + assert!(!hdr.dependent_slice_segment_flag); + assert_eq!(hdr.type_, SliceType::I); + assert!(hdr.sao_luma_flag); + assert!(hdr.sao_chroma_flag); + assert_eq!(hdr.qp_delta, 8); + assert!(hdr.loop_filter_across_slices_enabled_flag); + + let slice_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::TrailR, 0).unwrap(); + let slice = parser.parse_slice_header(slice_nalu).unwrap(); + let hdr = &slice.header; + assert!(hdr.first_slice_segment_in_pic_flag); + assert_eq!(hdr.pic_parameter_set_id, 0); + assert!(!hdr.dependent_slice_segment_flag); + assert_eq!(hdr.type_, SliceType::P); + assert_eq!(hdr.pic_order_cnt_lsb, 4); + assert!(!hdr.short_term_ref_pic_set_sps_flag); + assert_eq!(hdr.short_term_ref_pic_set.num_negative_pics, 1); + assert_eq!(hdr.short_term_ref_pic_set.num_positive_pics, 0); + assert_eq!(hdr.short_term_ref_pic_set.delta_poc_s0[0], -4); + assert!(hdr.short_term_ref_pic_set.used_by_curr_pic_s0[0]); + assert!(hdr.temporal_mvp_enabled_flag); + assert!(hdr.sao_luma_flag); + assert!(hdr.sao_chroma_flag); + assert!(!hdr.num_ref_idx_active_override_flag); + assert_eq!(hdr.pred_weight_table.luma_log2_weight_denom, 0); + assert_eq!(hdr.pred_weight_table.delta_chroma_log2_weight_denom, 7); + assert_eq!(hdr.pred_weight_table.delta_luma_weight_l0[0], 0); + assert_eq!(hdr.pred_weight_table.luma_offset_l0[0], -2); + assert_eq!(hdr.pred_weight_table.delta_chroma_weight_l0[0][0], -9); + assert_eq!(hdr.pred_weight_table.delta_chroma_weight_l0[0][1], -9); + assert_eq!(hdr.pred_weight_table.delta_chroma_offset_l0[0][0], 0); + assert_eq!(hdr.pred_weight_table.delta_chroma_offset_l0[0][1], 0); + assert_eq!(hdr.five_minus_max_num_merge_cand, 3); + assert_eq!(hdr.qp_delta, 8); + assert!(hdr.loop_filter_across_slices_enabled_flag); + } + + /// A custom test for VPS parsing with data manually extracted from + /// GStreamer using GDB. + #[test] + fn test25fps_vps_header_parsing() { + let mut cursor = Cursor::new(STREAM_TEST25FPS); + let mut parser = Parser::default(); + + let vps_nalu = Nalu::::next(&mut cursor).unwrap(); + let vps = parser.parse_vps(&vps_nalu).unwrap(); + assert!(vps.base_layer_internal_flag); + assert!(vps.base_layer_available_flag); + assert_eq!(vps.max_layers_minus1, 0); + assert_eq!(vps.max_sub_layers_minus1, 0); + assert!(vps.temporal_id_nesting_flag); + assert_eq!(vps.profile_tier_level.general_profile_space, 0); + assert!(!vps.profile_tier_level.general_tier_flag); + assert_eq!(vps.profile_tier_level.general_profile_idc, 1); + for i in 0..32 { + let val = i == 1 || i == 2; + assert_eq!(vps.profile_tier_level.general_profile_compatibility_flag[i], val); + } + assert!(vps.profile_tier_level.general_progressive_source_flag); + assert!(!vps.profile_tier_level.general_interlaced_source_flag); + assert!(!vps.profile_tier_level.general_non_packed_constraint_flag,); + assert!(vps.profile_tier_level.general_frame_only_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_12bit_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_10bit_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_8bit_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_422chroma_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_420chroma_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_monochrome_constraint_flag,); + assert!(!vps.profile_tier_level.general_intra_constraint_flag); + assert!(!vps.profile_tier_level.general_one_picture_only_constraint_flag,); + assert!(!vps.profile_tier_level.general_lower_bit_rate_constraint_flag,); + assert!(!vps.profile_tier_level.general_max_14bit_constraint_flag,); + assert_eq!(vps.profile_tier_level.general_level_idc, Level::L2); + + assert!(vps.sub_layer_ordering_info_present_flag); + assert_eq!(vps.max_dec_pic_buffering_minus1[0], 4); + assert_eq!(vps.max_num_reorder_pics[0], 2); + assert_eq!(vps.max_latency_increase_plus1[0], 5); + for i in 1..7 { + assert_eq!(vps.max_dec_pic_buffering_minus1[i], 0); + assert_eq!(vps.max_num_reorder_pics[i], 0); + assert_eq!(vps.max_latency_increase_plus1[i], 0); + } + + assert_eq!(vps.max_layer_id, 0); + assert_eq!(vps.num_layer_sets_minus1, 0); + assert!(!vps.timing_info_present_flag); + assert_eq!(vps.num_units_in_tick, 0); + assert_eq!(vps.time_scale, 0); + assert!(!vps.poc_proportional_to_timing_flag); + assert_eq!(vps.num_ticks_poc_diff_one_minus1, 0); + assert_eq!(vps.num_hrd_parameters, 0); + } + + /// A custom test for SPS parsing with data manually extracted from + /// GStreamer using GDB. + #[test] + fn test25fps_sps_header_parsing() { + let mut parser = Parser::default(); + + let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap(); + let sps = parser.parse_sps(&sps_nalu).unwrap(); + + assert_eq!(sps.max_sub_layers_minus1, 0); + + assert_eq!(sps.profile_tier_level.general_profile_space, 0); + assert!(!sps.profile_tier_level.general_tier_flag); + assert_eq!(sps.profile_tier_level.general_profile_idc, 1); + for i in 0..32 { + let val = i == 1 || i == 2; + assert_eq!(sps.profile_tier_level.general_profile_compatibility_flag[i], val); + } + assert!(sps.profile_tier_level.general_progressive_source_flag); + assert!(!sps.profile_tier_level.general_interlaced_source_flag); + assert!(!sps.profile_tier_level.general_non_packed_constraint_flag,); + assert!(sps.profile_tier_level.general_frame_only_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_12bit_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_10bit_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_8bit_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_422chroma_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_420chroma_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_monochrome_constraint_flag,); + assert!(!sps.profile_tier_level.general_intra_constraint_flag); + assert!(!sps.profile_tier_level.general_one_picture_only_constraint_flag,); + assert!(!sps.profile_tier_level.general_lower_bit_rate_constraint_flag,); + assert!(!sps.profile_tier_level.general_max_14bit_constraint_flag,); + assert_eq!(sps.profile_tier_level.general_level_idc, Level::L2); + + assert_eq!(sps.seq_parameter_set_id, 0); + assert_eq!(sps.chroma_format_idc, 1); + assert!(!sps.separate_colour_plane_flag); + assert_eq!(sps.pic_width_in_luma_samples, 320); + assert_eq!(sps.pic_height_in_luma_samples, 240); + assert_eq!(sps.conf_win_left_offset, 0); + assert_eq!(sps.conf_win_right_offset, 0); + assert_eq!(sps.conf_win_top_offset, 0); + assert_eq!(sps.conf_win_bottom_offset, 0); + assert_eq!(sps.bit_depth_luma_minus8, 0); + assert_eq!(sps.bit_depth_chroma_minus8, 0); + assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 4); + assert!(sps.sub_layer_ordering_info_present_flag); + assert_eq!(sps.max_dec_pic_buffering_minus1[0], 4); + assert_eq!(sps.max_num_reorder_pics[0], 2); + assert_eq!(sps.max_latency_increase_plus1[0], 5); + for i in 1..7 { + assert_eq!(sps.max_dec_pic_buffering_minus1[i], 0); + assert_eq!(sps.max_num_reorder_pics[i], 0); + assert_eq!(sps.max_latency_increase_plus1[i], 0); + } + assert_eq!(sps.log2_min_luma_coding_block_size_minus3, 0); + assert_eq!(sps.log2_diff_max_min_luma_coding_block_size, 3); + assert_eq!(sps.log2_min_luma_transform_block_size_minus2, 0); + assert_eq!(sps.log2_diff_max_min_luma_transform_block_size, 3); + assert_eq!(sps.max_transform_hierarchy_depth_inter, 0); + assert_eq!(sps.max_transform_hierarchy_depth_intra, 0); + assert!(!sps.scaling_list_enabled_flag); + assert!(!sps.scaling_list_data_present_flag); + assert!(!sps.amp_enabled_flag); + assert!(sps.sample_adaptive_offset_enabled_flag); + assert!(!sps.pcm_enabled_flag); + assert_eq!(sps.pcm_sample_bit_depth_luma_minus1, 0); + assert_eq!(sps.pcm_sample_bit_depth_chroma_minus1, 0); + assert_eq!(sps.log2_min_pcm_luma_coding_block_size_minus3, 0); + assert_eq!(sps.log2_diff_max_min_pcm_luma_coding_block_size, 0); + assert!(!sps.pcm_loop_filter_disabled_flag); + assert_eq!(sps.num_short_term_ref_pic_sets, 0); + assert_eq!(sps.num_long_term_ref_pics_sps, 0); + assert!(sps.temporal_mvp_enabled_flag); + assert!(sps.strong_intra_smoothing_enabled_flag); + assert_eq!(sps.vui_parameters.sar_width, 0); + assert_eq!(sps.vui_parameters.sar_height, 0); + assert!(!sps.vui_parameters.video_full_range_flag); + assert!(!sps.vui_parameters.colour_description_present_flag); + assert!(sps.vui_parameters.video_signal_type_present_flag); + assert!(sps.vui_parameters.timing_info_present_flag); + assert_eq!(sps.vui_parameters.num_units_in_tick, 1); + assert_eq!(sps.vui_parameters.time_scale, 25); + assert!(!sps.vui_parameters.poc_proportional_to_timing_flag); + assert_eq!(sps.vui_parameters.num_ticks_poc_diff_one_minus1, 0); + assert!(!sps.vui_parameters.hrd_parameters_present_flag); + assert_eq!(sps.vui_parameters.colour_primaries, 2); + assert_eq!(sps.vui_parameters.transfer_characteristics, 2); + assert_eq!(sps.vui_parameters.matrix_coeffs, 2); + assert_eq!(sps.vui_parameters.def_disp_win_left_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_right_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_top_offset, 0); + assert_eq!(sps.vui_parameters.def_disp_win_bottom_offset, 0); + } + + /// A custom test for PPS parsing with data manually extracted from + /// GStreamer using GDB. + #[test] + fn test25fps_pps_header_parsing() { + let mut parser = Parser::default(); + + let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap(); + parser.parse_sps(&sps_nalu).unwrap(); + + let pps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::PpsNut, 0).unwrap(); + let pps = parser.parse_pps(&pps_nalu).unwrap(); + + assert!(!pps.dependent_slice_segments_enabled_flag); + assert!(!pps.output_flag_present_flag); + assert_eq!(pps.num_extra_slice_header_bits, 0); + assert!(pps.sign_data_hiding_enabled_flag); + assert!(!pps.cabac_init_present_flag); + assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0); + assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0); + assert_eq!(pps.init_qp_minus26, 0); + assert!(!pps.constrained_intra_pred_flag); + assert!(!pps.transform_skip_enabled_flag); + assert!(pps.cu_qp_delta_enabled_flag); + assert_eq!(pps.diff_cu_qp_delta_depth, 1); + assert_eq!(pps.cb_qp_offset, 0); + assert_eq!(pps.cr_qp_offset, 0); + assert!(!pps.slice_chroma_qp_offsets_present_flag); + assert!(pps.weighted_pred_flag); + assert!(!pps.weighted_bipred_flag); + assert!(!pps.transquant_bypass_enabled_flag); + assert!(!pps.tiles_enabled_flag); + assert!(pps.entropy_coding_sync_enabled_flag); + assert_eq!(pps.num_tile_rows_minus1, 0); + assert_eq!(pps.num_tile_columns_minus1, 0); + assert!(pps.uniform_spacing_flag); + assert_eq!(pps.column_width_minus1, [0; 19]); + assert_eq!(pps.row_height_minus1, [0; 21]); + assert!(pps.loop_filter_across_slices_enabled_flag); + assert!(pps.loop_filter_across_tiles_enabled_flag); + assert!(!pps.deblocking_filter_control_present_flag); + assert!(!pps.deblocking_filter_override_enabled_flag); + assert!(!pps.deblocking_filter_disabled_flag); + assert_eq!(pps.beta_offset_div2, 0); + assert_eq!(pps.tc_offset_div2, 0); + assert!(!pps.lists_modification_present_flag); + assert_eq!(pps.log2_parallel_merge_level_minus2, 0); + assert!(!pps.slice_segment_header_extension_present_flag); + assert!(!pps.extension_present_flag); + } + + /// A custom test for slice header parsing with data manually extracted from + /// GStreamer using GDB. + #[test] + fn test25fps_slice_header_parsing() { + let mut parser = Parser::default(); + + // Have to parse the SPS/VPS/PPS to set up the parser's internal state. + let vps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::VpsNut, 0).unwrap(); + parser.parse_vps(&vps_nalu).unwrap(); + + let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap(); + parser.parse_sps(&sps_nalu).unwrap(); + + let pps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::PpsNut, 0).unwrap(); + parser.parse_pps(&pps_nalu).unwrap(); + + let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::IdrNLp, 0).unwrap(); + let slice = parser.parse_slice_header(slice_nalu).unwrap(); + let hdr = &slice.header; + + assert!(hdr.first_slice_segment_in_pic_flag); + assert!(!hdr.no_output_of_prior_pics_flag); + assert!(!hdr.dependent_slice_segment_flag); + assert_eq!(hdr.type_, SliceType::I); + assert!(hdr.pic_output_flag); + assert_eq!(hdr.colour_plane_id, 0); + assert_eq!(hdr.pic_order_cnt_lsb, 0); + assert!(!hdr.short_term_ref_pic_set_sps_flag); + assert_eq!(hdr.lt_idx_sps, [0; 16]); + assert_eq!(hdr.poc_lsb_lt, [0; 16]); + assert_eq!(hdr.used_by_curr_pic_lt, [false; 16]); + assert_eq!(hdr.delta_poc_msb_cycle_lt, [0; 16]); + assert_eq!(hdr.delta_poc_msb_present_flag, [false; 16]); + assert!(!hdr.temporal_mvp_enabled_flag); + assert!(hdr.sao_luma_flag); + assert!(hdr.sao_chroma_flag); + assert!(!hdr.num_ref_idx_active_override_flag); + assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0); + assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0); + assert!(!hdr.cabac_init_flag); + assert!(hdr.collocated_from_l0_flag); + assert_eq!(hdr.five_minus_max_num_merge_cand, 0); + assert!(!hdr.use_integer_mv_flag); + assert_eq!(hdr.qp_delta, 7); + assert_eq!(hdr.cb_qp_offset, 0); + assert_eq!(hdr.cr_qp_offset, 0); + assert!(!hdr.cu_chroma_qp_offset_enabled_flag); + assert!(!hdr.deblocking_filter_override_flag); + assert!(!hdr.deblocking_filter_override_flag); + assert_eq!(hdr.beta_offset_div2, 0); + assert_eq!(hdr.tc_offset_div2, 0); + assert!(hdr.loop_filter_across_slices_enabled_flag); + assert_eq!(hdr.num_entry_point_offsets, 3); + assert_eq!(hdr.offset_len_minus1, 11); + assert_eq!(hdr.num_pic_total_curr, 0); + + // Remove the 2 bytes from the NALU header. + assert_eq!(hdr.header_bit_size - 16, 72); + + assert_eq!(hdr.n_emulation_prevention_bytes, 0); + + assert_eq!(slice.nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_0); + + // Next slice + let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::TrailR, 0).unwrap(); + let slice = parser.parse_slice_header(slice_nalu).unwrap(); + let hdr = &slice.header; + + assert!(hdr.first_slice_segment_in_pic_flag); + assert!(!hdr.no_output_of_prior_pics_flag); + assert!(!hdr.dependent_slice_segment_flag); + assert_eq!(hdr.type_, SliceType::P); + assert!(hdr.pic_output_flag); + assert_eq!(hdr.colour_plane_id, 0); + assert_eq!(hdr.pic_order_cnt_lsb, 3); + assert!(!hdr.short_term_ref_pic_set_sps_flag); + assert_eq!(hdr.short_term_ref_pic_set.num_delta_pocs, 1); + assert_eq!(hdr.short_term_ref_pic_set.num_negative_pics, 1); + assert_eq!(hdr.short_term_ref_pic_set.num_positive_pics, 0); + assert!(hdr.short_term_ref_pic_set.used_by_curr_pic_s0[0]); + assert_eq!(hdr.short_term_ref_pic_set.delta_poc_s0[0], -3); + assert_eq!(hdr.lt_idx_sps, [0; 16]); + assert_eq!(hdr.poc_lsb_lt, [0; 16]); + assert_eq!(hdr.used_by_curr_pic_lt, [false; 16]); + assert_eq!(hdr.delta_poc_msb_cycle_lt, [0; 16]); + assert_eq!(hdr.delta_poc_msb_present_flag, [false; 16]); + assert!(hdr.temporal_mvp_enabled_flag); + assert!(hdr.sao_luma_flag); + assert!(hdr.sao_chroma_flag); + assert!(!hdr.num_ref_idx_active_override_flag); + assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0); + assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0); + assert!(!hdr.cabac_init_flag); + assert!(hdr.collocated_from_l0_flag); + assert_eq!(hdr.pred_weight_table.luma_log2_weight_denom, 7); + assert_eq!(hdr.five_minus_max_num_merge_cand, 2); + assert!(!hdr.use_integer_mv_flag); + assert_eq!(hdr.num_entry_point_offsets, 3); + assert_eq!(hdr.qp_delta, 7); + assert_eq!(hdr.cb_qp_offset, 0); + assert_eq!(hdr.cr_qp_offset, 0); + assert!(!hdr.cu_chroma_qp_offset_enabled_flag); + assert!(!hdr.deblocking_filter_override_flag); + assert!(!hdr.deblocking_filter_override_flag); + assert_eq!(hdr.beta_offset_div2, 0); + assert_eq!(hdr.tc_offset_div2, 0); + assert!(!hdr.loop_filter_across_slices_enabled_flag); + assert_eq!(hdr.num_entry_point_offsets, 3); + assert_eq!(hdr.offset_len_minus1, 10); + assert_eq!(hdr.num_pic_total_curr, 1); + + assert_eq!(slice.nalu.size, 2983); + // Subtract 2 bytes to account for the header size. + assert_eq!(hdr.header_bit_size - 16, 96); + assert_eq!(slice.nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_1); + + // Next slice + let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::TrailR, 1).unwrap(); + let slice = parser.parse_slice_header(slice_nalu).unwrap(); + let hdr = &slice.header; + + assert_eq!(slice.nalu.size, 290); + // Subtract 2 bytes to account for the header size. + assert_eq!(hdr.header_bit_size - 16, 80); + } +} diff --git a/vendor/cros-codecs/src/codec/h265/picture.rs b/vendor/cros-codecs/src/codec/h265/picture.rs new file mode 100644 index 0000000..ecb86f2 --- /dev/null +++ b/vendor/cros-codecs/src/codec/h265/picture.rs @@ -0,0 +1,154 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::h265::parser::NaluType; +use crate::codec::h265::parser::Slice; + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum Reference { + #[default] + None, + ShortTerm, + LongTerm, +} + +/// Data associated with an h.265 picture. Most fields are extracted from the +/// slice header and kept for future processing. +#[derive(Debug, Default, Clone, Eq, PartialEq)] +pub struct PictureData { + // Fields extracted from the slice header. These are the CamelCase + // variables, unless noted otherwise. + pub nalu_type: NaluType, + pub no_rasl_output_flag: bool, + pub pic_output_flag: bool, + pub valid_for_prev_tid0_pic: bool, + pub slice_pic_order_cnt_lsb: i32, + pub pic_order_cnt_msb: i32, + pub pic_order_cnt_val: i32, + pub no_output_of_prior_pics_flag: bool, + + // Internal state. + pub first_picture_after_eos: bool, + reference: Reference, + pub pic_latency_cnt: i32, + pub needed_for_output: bool, + pub short_term_ref_pic_set_size_bits: u32, +} + +impl PictureData { + /// Instantiates a new `PictureData` from a slice. + /// + /// See 8.1.3 Decoding process for a coded picture with nuh_layer_id equal + /// to 0. + /// + /// This will also call the picture order count process (clause 8.3.1) to + /// correctly initialize the POC values. + pub fn new_from_slice( + slice: &Slice, + first_picture_in_bitstream: bool, + first_picture_after_eos: bool, + prev_tid0_pic: Option<&PictureData>, + max_pic_order_cnt_lsb: i32, + ) -> Self { + let hdr = &slice.header; + let nalu_type = slice.nalu.header.type_; + + // We assume HandleCraAsBlafFLag == 0, as it is only set through + // external means, which we do not provide. + + let mut pic_order_cnt_msb = 0; + let slice_pic_order_cnt_lsb: i32 = hdr.pic_order_cnt_lsb.into(); + + // Compute the output flags: + // The value of NoRaslOutputFlag is equal to 1 for each IDR access + // unit, each BLA access unit, and each CRA access unit that is the + // first access unit in the bitstream in decoding order, is the first + // access unit that follows an end of sequence NAL unit in decoding + // order, or has HandleCraAsBlaFlag equal to 1. + let no_rasl_output_flag = nalu_type.is_idr() + || nalu_type.is_bla() + || (nalu_type.is_cra() && first_picture_in_bitstream) + || first_picture_after_eos; + + let pic_output_flag = if slice.nalu.header.type_.is_rasl() && no_rasl_output_flag { + false + } else { + hdr.pic_output_flag + }; + + // Compute the Picture Order Count. See 8.3.1 Decoding Process for + // Picture Order Count + if !(nalu_type.is_irap() && no_rasl_output_flag) { + if let Some(prev_tid0_pic) = prev_tid0_pic { + // Equation (8-1) + let prev_pic_order_cnt_lsb = prev_tid0_pic.slice_pic_order_cnt_lsb; + let prev_pic_order_cnt_msb = prev_tid0_pic.pic_order_cnt_msb; + if (slice_pic_order_cnt_lsb < prev_pic_order_cnt_lsb) + && (prev_pic_order_cnt_lsb - slice_pic_order_cnt_lsb) + >= (max_pic_order_cnt_lsb / 2) + { + pic_order_cnt_msb = prev_pic_order_cnt_msb + max_pic_order_cnt_lsb; + } else if (slice_pic_order_cnt_lsb > prev_pic_order_cnt_lsb) + && (slice_pic_order_cnt_lsb - prev_pic_order_cnt_lsb) + > (max_pic_order_cnt_lsb / 2) + { + pic_order_cnt_msb = prev_pic_order_cnt_msb - max_pic_order_cnt_lsb; + } else { + pic_order_cnt_msb = prev_pic_order_cnt_msb; + } + } + } + + // Compute whether this picture will be a valid prevTid0Pic, i.e.: + // + // Let prevTid0Pic be the previous picture in decoding order that has + // TemporalId equal to 0 and that is not a RASL, RADL or SLNR picture. + // + // Use this flag to correctly set up the field in the decoder during + // `finish_picture`. + let valid_for_prev_tid0_pic = slice.nalu.header.nuh_temporal_id() == 0 + && !nalu_type.is_radl() + && !nalu_type.is_rasl() + && !nalu_type.is_slnr(); + + let no_output_of_prior_pics_flag = + if nalu_type.is_irap() && no_rasl_output_flag && !first_picture_in_bitstream { + nalu_type.is_cra() || hdr.no_output_of_prior_pics_flag + } else { + false + }; + + Self { + nalu_type, + no_rasl_output_flag, + no_output_of_prior_pics_flag, + pic_output_flag, + valid_for_prev_tid0_pic, + slice_pic_order_cnt_lsb, + pic_order_cnt_msb, + // Equation (8-2) + pic_order_cnt_val: pic_order_cnt_msb + slice_pic_order_cnt_lsb, + first_picture_after_eos, + reference: Default::default(), + pic_latency_cnt: 0, + needed_for_output: false, + short_term_ref_pic_set_size_bits: hdr.st_rps_bits, + } + } + + /// Whether the current picture is a reference, either ShortTerm or LongTerm. + pub fn is_ref(&self) -> bool { + !matches!(self.reference, Reference::None) + } + + pub fn set_reference(&mut self, reference: Reference) { + log::debug!("Set reference of POC {} to {:?}", self.pic_order_cnt_val, reference); + + self.reference = reference; + } + + pub fn reference(&self) -> &Reference { + &self.reference + } +} diff --git a/vendor/cros-codecs/src/codec/vp8.rs b/vendor/cros-codecs/src/codec/vp8.rs new file mode 100644 index 0000000..c8db8ff --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp8.rs @@ -0,0 +1,11 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#![warn(clippy::missing_panics_doc)] +#![warn(clippy::panic)] +#![warn(clippy::unwrap_used)] + +mod bool_decoder; +pub mod parser; +mod probs; diff --git a/vendor/cros-codecs/src/codec/vp8/bool_decoder.rs b/vendor/cros-codecs/src/codec/vp8/bool_decoder.rs new file mode 100644 index 0000000..eebe2a5 --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp8/bool_decoder.rs @@ -0,0 +1,309 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! A VP8 boolean decoder based on the implementation in Chromium and GStreamer. + +use std::convert::TryFrom; +use std::fmt; + +use crate::bitstream_utils::BitReader; + +const LOTS_OF_BITS: u32 = 0x40000000; +const U8_BITS: usize = u8::BITS as usize; +const BD_VALUE_SIZE: usize = std::mem::size_of::() * U8_BITS; + +const NORM: [u8; 256] = [ + 0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +/// Some bits are "encoded" with a 50/50 probability. +const DEFAULT_PROBABILITY: u8 = 128; + +/// A capture of the state of the boolean decoder. +/// +/// A `BoolDecoder` can be consumed and turned into this structure, which captures its state. This +/// is useful to pass that state to the next decoding step, typically a hardware accelerator. +pub struct BoolDecoderState { + pub range: usize, + pub value: usize, + pub count: isize, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum BoolDecoderError { + EndOfInput, + CannotConvert, +} + +impl fmt::Display for BoolDecoderError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + BoolDecoderError::EndOfInput => write!(f, "end of input reached"), + BoolDecoderError::CannotConvert => { + write!(f, "could not convert number of read bits to target type") + } + } + } +} + +pub type BoolDecoderResult = std::result::Result; + +/// The decoder state. +pub struct BoolDecoder<'a> { + data: BitReader<'a>, + range: usize, + value: usize, + count: isize, +} + +impl<'a> BoolDecoder<'a> { + /// Creates a new instance. + pub fn new(data: &'a [u8]) -> Self { + Self { + data: BitReader::new(data, false), + range: 255usize, + value: 0usize, + count: -(U8_BITS as isize), + } + } + + /// Fills more bits from `data` to `value`. We shall keep at least 8 bits of the current `data` + /// in `value`. + /// + /// Returns `Some(())` if there was input data to fill from, `None` if we reached the end of + /// the input. + fn fill(&mut self) -> Option<()> { + let mut shift = + (BD_VALUE_SIZE as isize - U8_BITS as isize - (self.count + U8_BITS as isize)) as i32; + let bits_left = self.data.num_bits_left() as i32; + let x = shift + U8_BITS as i32 - bits_left; + let mut loop_end = 0; + + if x >= 0 { + self.count += LOTS_OF_BITS as isize; + loop_end = x; + } + + if x < 0 || bits_left != 0 { + while shift >= loop_end { + self.count += U8_BITS as isize; + self.value |= self.data.read_bits::(8).ok()? << shift; + shift -= U8_BITS as i32; + } + Some(()) + } else { + None + } + } + + /// Reads the next bit from the coded stream. The probability of the bit to + /// be one is probability / 256. + fn read_bit(&mut self, probability: u8) -> BoolDecoderResult { + let split = 1 + (((self.range - 1) * probability as usize) >> 8); + + if self.count < 0 { + self.fill().ok_or(BoolDecoderError::EndOfInput)?; + } + + let bigsplit = split << (BD_VALUE_SIZE - U8_BITS); + + let bit = if self.value >= bigsplit { + self.range -= split; + self.value -= bigsplit; + true + } else { + self.range = split; + false + }; + + let shift = NORM[self.range]; + self.range <<= shift; + self.value <<= shift; + self.count -= isize::from(shift); + + Ok(bit) + } + + /// Reads a "literal", that is, a "num_bits"-wide unsigned value whose bits + /// come high- to low-order, with each bit encoded at probability 1/2. + /// + /// # Panics + /// + /// Will panic if `nbits > 31`. + fn read_literal(&mut self, nbits: usize) -> BoolDecoderResult { + // This won't perform well if we read more than 31 bits. + assert!(nbits <= 31); + + let mut ret = 0; + + for _ in 0..nbits { + ret = (ret << 1) | self.read_bit(DEFAULT_PROBABILITY)? as i32; + } + + Ok(ret) + } + + /// Reads a boolean from the coded stream. Returns false if it has reached the + /// end of data and failed to read the boolean. The probability of out to + /// be true is probability / 256, e.g., when probability is 0x80, the + /// chance is 1/2 (i.e., 0x80 / 256). + pub fn read_bool(&mut self) -> BoolDecoderResult { + self.read_literal(1).map(|bit| bit != 0) + } + + /// Reads a boolean from the coded stream. Returns false if it has reached the + /// end of data and failed to read the boolean. The probability of out to + /// be true is probability / 256, e.g., when probability is 0x80, the + /// chance is 1/2 (i.e., 0x80 / 256). + pub fn read_bool_with_prob(&mut self, probability: u8) -> BoolDecoderResult { + self.read_bit(probability) + } + + /// Reads an unsigned literal from the coded stream. + /// + /// # Panics + /// + /// Will panic if `nbits > 31`. + pub fn read_uint>(&mut self, nbits: usize) -> BoolDecoderResult { + let value = self.read_literal(nbits)?; + U::try_from(value).map_err(|_| BoolDecoderError::CannotConvert) + } + + /// Reads a literal with sign from the coded stream. This is similar to the + /// read_literal(), it first read a "num_bits"-wide unsigned value, and then + /// read an extra bit as the sign of the literal. + /// + /// # Panics + /// + /// Will panic if `nbits > 31`. + pub fn read_sint>(&mut self, nbits: usize) -> BoolDecoderResult { + let mut value = self.read_literal(nbits)?; + let sign = self.read_bool()?; + + if sign { + value = -value; + } + + U::try_from(value).map_err(|_| BoolDecoderError::CannotConvert) + } + + /// Returns the current bit position. + pub fn pos(&self) -> usize { + let mut bit_count = (self.count + 8) as usize; + + if bit_count > BD_VALUE_SIZE { + bit_count = bit_count.saturating_sub(LOTS_OF_BITS as usize) + } + + let pos = self.data.position() as usize; + pos - bit_count + } +} + +impl From> for BoolDecoderState { + fn from(mut bd: BoolDecoder) -> Self { + if bd.count < 0 { + let _ = bd.fill(); + } + + Self { + value: bd.value >> (BD_VALUE_SIZE - U8_BITS), + count: (U8_BITS as isize + bd.count) % U8_BITS as isize, + range: bd.range, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NUM_BITS_TO_TEST: usize = 100; + + /// 100 zeros with probability of 0x80. + const DATA_ZEROS_AND_EVEN_PROBABILITIES: [u8; 14] = + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + /// 100 ones with probability of 0x80. + const DATA_ONES_AND_EVEN_PROBABILITIES: [u8; 14] = + [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x20]; + + /// [0, 1, 0, 1, ..., 1] with probability [0, 1, 2, 3, ..., 99]. + const DATA_PARITIES_AND_INCREASING_PROBABILITIES: [u8; 21] = [ + 0x00, 0x02, 0x08, 0x31, 0x8e, 0xca, 0xab, 0xe2, 0xc8, 0x31, 0x12, 0xb3, 0x2c, 0x19, 0x90, + 0xc6, 0x6a, 0xeb, 0x17, 0x52, 0x30, + ]; + + // All tests adapted from: + // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/parsers/vp8_bool_decoder_unittest.cc + + #[test] + fn decode_bools_with_zeros_and_even_probabilities() { + let mut bd = BoolDecoder::new(&DATA_ZEROS_AND_EVEN_PROBABILITIES[..]); + assert!(bd.pos() == 0); + + for i in 0..NUM_BITS_TO_TEST { + assert_eq!(bd.read_bool_with_prob(0x80), Ok(false)); + assert_eq!(i, bd.pos()); + } + } + + #[test] + fn decode_literals_with_zeros_and_even_probabilities() { + // Adapted from: + // https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/parsers/vp8_bool_decoder_unittest.cc + let mut bd = BoolDecoder::new(&DATA_ZEROS_AND_EVEN_PROBABILITIES[..]); + assert_eq!(bd.pos(), 0); + + assert_eq!(bd.read_literal(1), Ok(0)); + assert_eq!(bd.read_literal(31), Ok(0)); + assert_eq!(bd.read_sint::(1), Ok(0)); + assert_eq!(bd.read_sint::(31), Ok(0)); + } + + #[test] + fn decode_bools_with_ones_and_even_probabilities() { + let mut bd = BoolDecoder::new(&DATA_ONES_AND_EVEN_PROBABILITIES[..]); + assert!(bd.pos() == 0); + + for i in 0..NUM_BITS_TO_TEST { + assert_eq!(bd.read_bool_with_prob(0x80), Ok(true)); + assert_eq!(i + 1, bd.pos()); + } + } + + #[test] + fn decode_literals_with_ones_and_even_probabilities() { + let mut bd = BoolDecoder::new(&DATA_ONES_AND_EVEN_PROBABILITIES[..]); + assert_eq!(bd.pos(), 0); + + assert_eq!(bd.read_literal(1), Ok(1)); + assert_eq!(bd.read_literal(31), Ok(0x7fffffff)); + assert_eq!(bd.read_sint::(1), Ok(-1)); + assert_eq!(bd.read_sint::(31), Ok(-0x7fffffff)); + } + + #[test] + fn decode_bools_with_parities_and_increasing_probabilities() { + let mut bd = BoolDecoder::new(&DATA_PARITIES_AND_INCREASING_PROBABILITIES[..]); + assert!(bd.pos() == 0); + + for i in 0..NUM_BITS_TO_TEST { + let bit = bd.read_bool_with_prob(i as u8).unwrap(); + + if i % 2 == 0 { + assert!(!bit); + } else { + assert!(bit); + } + } + } +} diff --git a/vendor/cros-codecs/src/codec/vp8/parser.rs b/vendor/cros-codecs/src/codec/vp8/parser.rs new file mode 100644 index 0000000..04266d8 --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp8/parser.rs @@ -0,0 +1,811 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::convert::TryFrom; +use std::fmt; + +use log::debug; + +use crate::bitstream_utils::BitReader; +use crate::codec::vp8::bool_decoder::BoolDecoder; +use crate::codec::vp8::bool_decoder::BoolDecoderError; +use crate::codec::vp8::bool_decoder::BoolDecoderResult; +use crate::codec::vp8::bool_decoder::BoolDecoderState; +use crate::codec::vp8::probs::COEFF_DEFAULT_PROBS; +use crate::codec::vp8::probs::COEFF_UPDATE_PROBS; +use crate::codec::vp8::probs::KF_UV_MODE_PROBS; +use crate::codec::vp8::probs::KF_Y_MODE_PROBS; +use crate::codec::vp8::probs::MV_DEFAULT_PROBS; +use crate::codec::vp8::probs::MV_UPDATE_PROBS; +use crate::codec::vp8::probs::NK_UV_MODE_PROBS; +use crate::codec::vp8::probs::NK_Y_MODE_PROBS; + +/// Dequantization indices as parsed from the quant_indices() syntax. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct QuantIndices { + /// The dequantization table index used for the luma AC coefficients (and + /// other coefficient groups if no delta value is present). + pub y_ac_qi: u8, + /// Indicates the delta value that is added to the baseline index to obtain + /// the luma DC coefficient dequantization index. + pub y_dc_delta: i8, + /// Indicates the delta value that is added to the baseline index to obtain + /// the Y2 block DC coefficient dequantization index. + pub y2_dc_delta: i8, + /// Indicates the delta value that is added to the baseline index to obtain + /// the Y2 block AC coefficient dequantization index. + pub y2_ac_delta: i8, + /// Indicates the delta value that is added to the baseline index to obtain + /// the chroma DC coefficient dequantization index. + pub uv_dc_delta: i8, + /// Indicates the delta value that is added to the baseline index to obtain + /// the chroma AC coefficient dequantization index. + pub uv_ac_delta: i8, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MbLfAdjustments { + /// Indicates if the MB-level loop filter adjustment (based on the used + /// reference frame and coding mode) is on for the current frame. + pub loop_filter_adj_enable: bool, + /// Indicates if the delta values used in adjustment are updated in the + /// current frame. + pub mode_ref_lf_delta_update: bool, + + //if mode_ref_lf_delta_update == 1 + /// Indicates the adjustment delta value corresponding to a certain used + /// reference frame. + pub ref_frame_delta: [i8; 4], + /// Indicates the adjustment delta value corresponding to a certain MB + /// prediction mode + pub mb_mode_delta: [i8; 4], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Segmentation { + /// Enables the segmentation feature for the current frame. + pub segmentation_enabled: bool, + /// Determines if the MB segmentation map is updated in the current frame. + pub update_mb_segmentation_map: bool, + /// indicates if the segment feature data is updated in the current frame. + pub update_segment_feature_data: bool, + + // If update_segment_feature_data == 1 + /// Indicates the feature data update mode, O for delta and 1 for the + /// absolute value. + pub segment_feature_mode: bool, + /// Indicates if the quantizer value is updated for the izh segment. + pub quantizer_update_value: [i8; 4], + /// Indicates the update value for the loop filter level. + pub lf_update_value: [i8; 4], + + // if update_mb_segmentation_map == 1 + /// The branch probabilities of the segment id decoding tree. + pub segment_prob: [u8; 3], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ModeProbs { + /// Branch probabilities of the luma intra prediction mode decoding tree, + /// kept live between frames. + pub intra_16x16_prob: [u8; 4], + /// Branch probabilities of the chroma intra prediction mode decoding tree, + /// kept live between frames. + pub intra_chroma_prob: [u8; 3], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Header { + /// Indicates if the current frame is a key frame or not. + pub key_frame: bool, + /// Determines the bitstream version. + pub version: u8, + /// Indicates if the current frame is meant to be displayed or not. + pub show_frame: bool, + /// The size in bytes of the Uncompressed Data Chunk + pub data_chunk_size: u8, + /// Determines the size of the first partition (control partition) excluding + /// the size of the Uncompressed Data Chunk + pub first_part_size: u32, + + /// The frame's width, in pixels. + pub width: u16, + /// The frame's height, in pixels. + pub height: u16, + /// Horizontal scale code value. + pub horiz_scale_code: u8, + /// Vertical scale code value. + pub vert_scale_code: u8, + /// Defines the YUV color space of the sequence. + pub color_space: bool, + /// Specifies if the decoder is required to clamp the reconstructed pixel + /// values. + pub clamping_type: bool, + /// Determines whether the normal or the simple loop filter is used. + pub filter_type: bool, + /// Controls the deblocking filter. + pub loop_filter_level: u8, + /// Controls the deblocking filter. + pub sharpness_level: u8, + /// Determines the number of separate partitions containing the DCT + /// coefficients of the macroblocks. + log2_nbr_of_dct_partitions: u8, + + pub partition_size: [u32; 8], + + /// Dequantizer indices. + pub quant_indices: QuantIndices, + + /// Determines whether updated token probabilities are used only for this + /// frame or until further update + pub refresh_entropy_probs: bool, + /// Determines if the current decoded frame refreshes the last frame + /// reference buffer + pub refresh_last: bool, + + /// Determines if the current decoded frame refreshes the golden frame. + pub refresh_golden_frame: bool, + /// Determines if the current decoded frame refreshes the alternate + /// reference frame. + pub refresh_alternate_frame: bool, + /// Determines if the golden reference is replaced by another reference. + pub copy_buffer_to_golden: u8, + /// Determines if the alternate reference is replaced by another reference. + pub copy_buffer_to_alternate: u8, + /// Controls the sign of motion vectors when the golden frame is referenced. + pub sign_bias_golden: bool, + /// Controls the sign of motion vectors when the alternate frame is + /// referenced. + pub sign_bias_alternate: bool, + + /// The new branch probability for the DCT/WHT tree. + pub coeff_prob: [[[[u8; 11]; 3]; 8]; 4], + /// MV decoding probability. + pub mv_prob: [[u8; 19]; 2], + + /// Enables or disables the skipping of macroblocks containing no non-zero + /// coefficients. + pub mb_no_coeff_skip: bool, + /// The probability that the macroblock is not skipped (flag indicating + /// skipped macroblock is false). + pub prob_skip_false: u8, + /// The probability of an intra macroblock. + pub prob_intra: u8, + /// The probability that the last reference frame is used for inter + /// prediction. + pub prob_last: u8, + /// The probability that the golden reference frame is used for inter + /// prediction. + pub prob_golden: u8, + /// Branch probabilities kept live across frames. + pub mode_probs: ModeProbs, + + /// Boolean decoder `range` for this frame. + pub bd_range: usize, + /// Boolean decoder `value` for this frame. + pub bd_value: usize, + /// Boolean decoder `count` for this frame. + pub bd_count: isize, + + /// The size in bits of the Frame Header, thus excluding any Uncompressed + /// Data Chunk bytes. + pub header_size: u32, +} + +#[derive(Debug)] +pub enum ParseUncompressedChunkError { + InvalidStartCode(u32), + IoError(String), +} + +impl fmt::Display for ParseUncompressedChunkError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ParseUncompressedChunkError::InvalidStartCode(x) => { + write!(f, "invalid start code {}", x) + } + ParseUncompressedChunkError::IoError(x) => write!(f, "I/O error: {}", x), + } + } +} + +#[derive(Debug)] +pub enum ComputePartitionSizesError { + EndOfHeader, + PartitionTooLarge, +} + +impl fmt::Display for ComputePartitionSizesError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ComputePartitionSizesError::EndOfHeader => write!(f, "unexpected end of header"), + ComputePartitionSizesError::PartitionTooLarge => { + write!(f, "partition size not fitting in a u32") + } + } + } +} + +impl Header { + /// Returns the number of separate partitions containing the DCT coefficients of the + /// macroblocks. + pub fn num_dct_partitions(&self) -> usize { + 1 << self.log2_nbr_of_dct_partitions + } + + /// Returns the total size of the encoded frame in bytes, as computed from the header. + pub fn frame_len(&self) -> usize { + // Uncompressed chunk size. + std::iter::once(self.data_chunk_size as usize) + // Size of first partition. + .chain(std::iter::once(self.first_part_size as usize)) + // Size of the partitions description area. + .chain(std::iter::once(self.num_dct_partitions().saturating_sub(1) * 3)) + // Size of other DCT partitions. + .chain(self.partition_size.iter().take(self.num_dct_partitions()).map(|s| *s as usize)) + .sum() + } + + /// Create a new `Header` by parsing the uncompressed data chunk of a frame. + fn parse_uncompressed_data_chunk( + bitstream: &[u8], + ) -> Result { + debug!("Parsing VP8 uncompressed data chunk."); + + let mut reader = BitReader::new(bitstream, false); + + let frame_tag = + reader.read_le::(3).map_err(|err| ParseUncompressedChunkError::IoError(err))?; + + let mut header = Header { + key_frame: (frame_tag & 0x1) == 0, + version: ((frame_tag >> 1) & 0x07) as u8, + show_frame: ((frame_tag >> 4) & 0x1) != 0, + first_part_size: (frame_tag >> 5) & 0x7ffff, + ..Default::default() + }; + + if header.key_frame { + let start_code = reader + .read_le::(3) + .map_err(|err| ParseUncompressedChunkError::IoError(err))?; + + if start_code != 0x2a019d { + return Err(ParseUncompressedChunkError::InvalidStartCode(start_code)); + } + + let size_code = reader + .read_le::(2) + .map_err(|err| ParseUncompressedChunkError::IoError(err))?; + header.horiz_scale_code = (size_code >> 14) as u8; + header.width = size_code & 0x3fff; + + let size_code = reader + .read_le::(2) + .map_err(|err| ParseUncompressedChunkError::IoError(err))?; + header.vert_scale_code = (size_code >> 14) as u8; + header.height = size_code & 0x3fff; + } + + if reader.position() % 8 != 0 { + Err(ParseUncompressedChunkError::IoError("Misaligned VP8 header".into())) + } else { + header.data_chunk_size = (reader.position() / 8) as u8; + Ok(header) + } + } + + fn compute_partition_sizes(&mut self, data: &[u8]) -> Result<(), ComputePartitionSizesError> { + let num_partitions = self.num_dct_partitions(); + let mut part_size_ofs = self.first_part_size as usize; + let mut ofs = part_size_ofs + 3 * (num_partitions - 1); + + if ofs > data.len() { + return Err(ComputePartitionSizesError::EndOfHeader); + } + + for i in 0..num_partitions - 1 { + let b0 = u32::from(data[part_size_ofs]); + let b1 = u32::from(data[part_size_ofs + 1]) << 8; + let b2 = u32::from(data[part_size_ofs + 2]) << 16; + + let part_size = b0 | b1 | b2; + part_size_ofs += 3; + + self.partition_size[i] = part_size; + ofs += part_size as usize; + } + + if ofs > data.len() { + return Err(ComputePartitionSizesError::EndOfHeader); + } + + self.partition_size[num_partitions - 1] = u32::try_from(data.len() - ofs) + .map_err(|_| ComputePartitionSizesError::PartitionTooLarge)?; + Ok(()) + } +} + +/// A VP8 frame. +pub struct Frame<'a> { + /// The bitstream data for this frame. + bitstream: &'a [u8], + /// The actual length of the frame data within `bitstream`. + frame_len: usize, + /// The parsed frame header. + pub header: Header, +} + +impl<'a> AsRef<[u8]> for Frame<'a> { + fn as_ref(&self) -> &[u8] { + &self.bitstream[..self.frame_len] + } +} + +/// A VP8 parser based on GStreamer's vp8parser and Chromium's VP8 parser. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Parser { + /// Segmentation data kept live across frames. + segmentation: Segmentation, + /// MbLfAdjustments data kept live across frames. + mb_lf_adjust: MbLfAdjustments, + /// Coeff probabilities data kept live across frames. + coeff_prob: [[[[u8; 11]; 3]; 8]; 4], + /// Motion vector probabilities data kept live across frames. + mv_prob: [[u8; 19]; 2], + /// Branch probabilities kept live across frames. + mode_probs: ModeProbs, +} + +#[derive(Debug)] +pub enum ParseFrameError { + ParseUncompressedChunk(ParseUncompressedChunkError), + InvalidPartitionSize(usize, usize), + ParseFrameHeader(BoolDecoderError), + ComputePartitionSizes(ComputePartitionSizesError), + BitstreamTooShort(usize, usize), +} + +impl fmt::Display for ParseFrameError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ParseFrameError::ParseUncompressedChunk(x) => { + write!(f, "error while parsing uncompressed chunk of frame: {}", x) + } + ParseFrameError::InvalidPartitionSize(x, y) => { + write!(f, "partition end {} is bigger than bitstream length {}", x, y) + } + ParseFrameError::ParseFrameHeader(x) => { + write!(f, "error while parsing frame header: {}", x) + } + ParseFrameError::ComputePartitionSizes(x) => { + write!(f, "error while computing frames partitions sizes: {}", x) + } + ParseFrameError::BitstreamTooShort(x, y) => { + write!(f, "bitstream is shorter ({} bytes) than computed length of frame {}", x, y) + } + } + } +} + +impl From for ParseFrameError { + fn from(err: ParseUncompressedChunkError) -> Self { + ParseFrameError::ParseUncompressedChunk(err) + } +} + +impl From for ParseFrameError { + fn from(err: BoolDecoderError) -> Self { + ParseFrameError::ParseFrameHeader(err) + } +} + +impl From for ParseFrameError { + fn from(err: ComputePartitionSizesError) -> Self { + ParseFrameError::ComputePartitionSizes(err) + } +} + +impl Parser { + pub fn segmentation(&self) -> &Segmentation { + &self.segmentation + } + + pub fn mb_lf_adjust(&self) -> &MbLfAdjustments { + &self.mb_lf_adjust + } + + fn mode_probs_init_defaults(mode_probs: &mut ModeProbs, key_frame: bool) { + if key_frame { + mode_probs.intra_16x16_prob = KF_Y_MODE_PROBS; + mode_probs.intra_chroma_prob = KF_UV_MODE_PROBS; + } else { + mode_probs.intra_16x16_prob = NK_Y_MODE_PROBS; + mode_probs.intra_chroma_prob = NK_UV_MODE_PROBS; + } + } + + fn update_segmentation(bd: &mut BoolDecoder, seg: &mut Segmentation) -> BoolDecoderResult<()> { + seg.update_mb_segmentation_map = false; + seg.update_segment_feature_data = false; + + seg.segmentation_enabled = bd.read_bool()?; + if !seg.segmentation_enabled { + return Ok(()); + } + + seg.update_mb_segmentation_map = bd.read_bool()?; + seg.update_segment_feature_data = bd.read_bool()?; + + if seg.update_segment_feature_data { + seg.segment_feature_mode = bd.read_bool()?; + + for value in seg.quantizer_update_value.iter_mut() { + let update = bd.read_bool()?; + if update { + *value = bd.read_sint(7)?; + } else { + // quantizer_update_value defaults to zero if update flag is + // zero (Section 9.3, 4.b) + *value = 0; + } + } + + for value in seg.lf_update_value.iter_mut() { + let update = bd.read_bool()?; + if update { + *value = bd.read_sint(6)?; + } else { + // lf_update_value defaults to zero if update flag is + // zero (Section 9.3, 4.b) + *value = 0; + } + } + + if seg.update_mb_segmentation_map { + for value in seg.segment_prob.iter_mut() { + let update = bd.read_bool()?; + if update { + *value = bd.read_uint(8)?; + } else { + // segment_prob defaults to 255 if update flag is + // zero (Section 9.3, 5) + *value = 255; + } + } + } + } + + Ok(()) + } + + fn parse_mb_lf_adjustments( + bd: &mut BoolDecoder, + adj: &mut MbLfAdjustments, + ) -> BoolDecoderResult<()> { + adj.mode_ref_lf_delta_update = false; + + adj.loop_filter_adj_enable = bd.read_bool()?; + if !adj.loop_filter_adj_enable { + return Ok(()); + } + + adj.mode_ref_lf_delta_update = bd.read_bool()?; + if !adj.mode_ref_lf_delta_update { + return Ok(()); + } + + for value in adj.ref_frame_delta.iter_mut() { + let update = bd.read_bool()?; + if update { + *value = bd.read_sint(6)?; + } + } + + for value in adj.mb_mode_delta.iter_mut() { + let update = bd.read_bool()?; + if update { + *value = bd.read_sint(6)?; + } + } + + Ok(()) + } + + fn parse_quant_indices(bd: &mut BoolDecoder, q: &mut QuantIndices) -> BoolDecoderResult<()> { + q.y_ac_qi = bd.read_uint(7)?; + + let y_dc_delta_present = bd.read_bool()?; + + if y_dc_delta_present { + q.y_dc_delta = bd.read_sint(4)?; + } else { + q.y_dc_delta = 0; + } + + let y2_dc_delta_present = bd.read_bool()?; + if y2_dc_delta_present { + q.y2_dc_delta = bd.read_sint(4)?; + } else { + q.y2_dc_delta = 0; + } + + let y2_ac_delta_present = bd.read_bool()?; + if y2_ac_delta_present { + q.y2_ac_delta = bd.read_sint(4)?; + } else { + q.y2_ac_delta = 0; + } + + let uv_dc_delta_present = bd.read_bool()?; + if uv_dc_delta_present { + q.uv_dc_delta = bd.read_sint(4)?; + } else { + q.uv_dc_delta = 0; + } + + let uv_ac_delta_present = bd.read_bool()?; + if uv_ac_delta_present { + q.uv_ac_delta = bd.read_sint(4)?; + } else { + q.uv_ac_delta = 0; + } + + Ok(()) + } + + fn parse_token_prob_update( + bd: &mut BoolDecoder, + coeff_probs: &mut [[[[u8; 11]; 3]; 8]; 4], + ) -> BoolDecoderResult<()> { + for (i, vi) in coeff_probs.iter_mut().enumerate() { + for (j, vj) in vi.iter_mut().enumerate() { + for (k, vk) in vj.iter_mut().enumerate() { + for (l, prob) in vk.iter_mut().enumerate() { + let update = bd.read_bool_with_prob(COEFF_UPDATE_PROBS[i][j][k][l])?; + if update { + *prob = bd.read_uint(8)?; + } + } + } + } + } + + Ok(()) + } + + fn parse_mv_prob_update( + bd: &mut BoolDecoder, + mv_probs: &mut [[u8; 19]; 2], + ) -> BoolDecoderResult<()> { + for (i, vi) in mv_probs.iter_mut().enumerate() { + for (j, prob) in vi.iter_mut().enumerate() { + let update = bd.read_bool_with_prob(MV_UPDATE_PROBS[i][j])?; + if update { + let mv_prob_update = bd.read_uint::(7)?; + + if mv_prob_update > 0 { + *prob = mv_prob_update << 1; + } else { + *prob = 1; + } + } + } + } + + Ok(()) + } + + fn parse_frame_header(&mut self, data: &[u8], frame: &mut Header) -> BoolDecoderResult<()> { + debug!("Parsing VP8 frame header."); + let mut bd = BoolDecoder::new(data); + + if frame.key_frame { + frame.color_space = bd.read_bool()?; + frame.clamping_type = bd.read_bool()?; + } + + Parser::update_segmentation(&mut bd, &mut self.segmentation)?; + + frame.filter_type = bd.read_bool()?; + frame.loop_filter_level = bd.read_uint(6)?; + frame.sharpness_level = bd.read_uint(3)?; + + Parser::parse_mb_lf_adjustments(&mut bd, &mut self.mb_lf_adjust)?; + + frame.log2_nbr_of_dct_partitions = bd.read_uint(2)?; + + Parser::parse_quant_indices(&mut bd, &mut frame.quant_indices)?; + + frame.copy_buffer_to_golden = 0; + frame.copy_buffer_to_alternate = 0; + + if frame.key_frame { + frame.refresh_entropy_probs = bd.read_bool()?; + + frame.refresh_last = true; + frame.refresh_golden_frame = true; + frame.refresh_alternate_frame = true; + + Parser::mode_probs_init_defaults(&mut frame.mode_probs, true); + } else { + frame.refresh_golden_frame = bd.read_bool()?; + frame.refresh_alternate_frame = bd.read_bool()?; + + if !frame.refresh_golden_frame { + frame.copy_buffer_to_golden = bd.read_uint(2)?; + } + + if !frame.refresh_alternate_frame { + frame.copy_buffer_to_alternate = bd.read_uint(2)?; + } + + frame.sign_bias_golden = bd.read_bool()?; + frame.sign_bias_alternate = bd.read_bool()?; + frame.refresh_entropy_probs = bd.read_bool()?; + frame.refresh_last = bd.read_bool()?; + + frame.mode_probs = self.mode_probs.clone(); + } + + frame.coeff_prob = self.coeff_prob; + frame.mv_prob = self.mv_prob; + + Parser::parse_token_prob_update(&mut bd, &mut frame.coeff_prob)?; + + frame.mb_no_coeff_skip = bd.read_bool()?; + if frame.mb_no_coeff_skip { + frame.prob_skip_false = bd.read_uint(8)?; + } + + if !frame.key_frame { + frame.prob_intra = bd.read_uint(8)?; + frame.prob_last = bd.read_uint(8)?; + frame.prob_golden = bd.read_uint(8)?; + + let intra_16x16_prob_update_flag = bd.read_bool()?; + if intra_16x16_prob_update_flag { + for prob in frame.mode_probs.intra_16x16_prob.iter_mut() { + *prob = bd.read_uint(8)?; + } + } + + let intra_chroma_prob_update_flag = bd.read_bool()?; + if intra_chroma_prob_update_flag { + for prob in frame.mode_probs.intra_chroma_prob.iter_mut() { + *prob = bd.read_uint(8)?; + } + } + + Parser::parse_mv_prob_update(&mut bd, &mut frame.mv_prob)?; + } + + if frame.refresh_entropy_probs { + self.coeff_prob = frame.coeff_prob; + self.mv_prob = frame.mv_prob; + + if !frame.key_frame { + self.mode_probs = frame.mode_probs.clone(); + } + } + + frame.header_size = bd.pos() as u32; + + let state: BoolDecoderState = bd.into(); + frame.bd_range = state.range; + frame.bd_value = state.value; + frame.bd_count = state.count; + + Ok(()) + } + + /// Parse a single frame from the chunk in `data`. + pub fn parse_frame<'a>(&mut self, bitstream: &'a [u8]) -> Result, ParseFrameError> { + let mut header = Header::parse_uncompressed_data_chunk(bitstream)?; + if header.key_frame { + // Reset on every key frame. + *self = Default::default(); + } + + let first_part_end = header.data_chunk_size as usize + header.first_part_size as usize; + + if first_part_end > bitstream.len() { + return Err(ParseFrameError::InvalidPartitionSize(first_part_end, bitstream.len())); + } + + let compressed_area = &bitstream[header.data_chunk_size as usize..]; + + self.parse_frame_header(compressed_area, &mut header)?; + header.compute_partition_sizes(compressed_area)?; + + let frame_len = header.frame_len(); + if frame_len > bitstream.as_ref().len() { + return Err(ParseFrameError::BitstreamTooShort(bitstream.as_ref().len(), frame_len)); + } + + Ok(Frame { bitstream, frame_len, header }) + } +} + +impl Default for Parser { + fn default() -> Self { + Self { + segmentation: Default::default(), + mb_lf_adjust: Default::default(), + coeff_prob: COEFF_DEFAULT_PROBS, + mv_prob: MV_DEFAULT_PROBS, + mode_probs: ModeProbs { + intra_16x16_prob: NK_Y_MODE_PROBS, + intra_chroma_prob: NK_UV_MODE_PROBS, + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::Parser; + + // Test and test data extracted from GStreamer + // subprojects/gst-plugins-bad/tests/check/libs/vp8parser.c + const VP8_TEST_0_INTRA: &[u8] = include_bytes!("test_data/vp8-parser-test-0-intra.bin"); + const VP8_TEST_0_INTER: &[u8] = include_bytes!("test_data/vp8-parser-test-0-inter.bin"); + + #[test] + fn gst_intra() { + let mut parser = Parser::default(); + let frame = parser.parse_frame(VP8_TEST_0_INTRA).expect("Parsing a intra frame failed"); + + assert!(frame.header.key_frame); + + assert_eq!(frame.header.first_part_size, 234); + assert_eq!(frame.header.width, 176); + assert_eq!(frame.header.height, 144); + + assert!(parser.mb_lf_adjust.loop_filter_adj_enable); + assert!(parser.mb_lf_adjust.mode_ref_lf_delta_update); + + assert_eq!(parser.mb_lf_adjust.ref_frame_delta[0], 2); + assert_eq!(parser.mb_lf_adjust.ref_frame_delta[1], 0); + assert_eq!(parser.mb_lf_adjust.ref_frame_delta[2], -2); + assert_eq!(parser.mb_lf_adjust.ref_frame_delta[3], -2); + + assert_eq!(parser.mb_lf_adjust.mb_mode_delta[0], 4); + assert_eq!(parser.mb_lf_adjust.mb_mode_delta[1], -2); + assert_eq!(parser.mb_lf_adjust.mb_mode_delta[2], 2); + assert_eq!(parser.mb_lf_adjust.mb_mode_delta[3], 4); + + assert_eq!(frame.header.quant_indices.y_ac_qi, 4); + assert!(frame.header.mb_no_coeff_skip); + + assert_eq!(frame.header.bd_range, 0xe8); + assert_eq!(frame.header.bd_value, 0x68); + assert_eq!(frame.header.bd_count, 1); + } + + #[test] + fn gst_inter() { + let mut parser = Parser::default(); + let frame = parser.parse_frame(VP8_TEST_0_INTER).expect("Parsing a inter frame failed"); + + assert!(!frame.header.key_frame); + + assert_eq!(frame.header.first_part_size, 98); + assert!(parser.mb_lf_adjust.loop_filter_adj_enable); + assert_eq!(frame.header.quant_indices.y_ac_qi, 4); + + assert!(frame.header.refresh_entropy_probs); + assert!(frame.header.refresh_last); + assert!(frame.header.mb_no_coeff_skip); + + assert_eq!(frame.header.prob_skip_false, 131); + assert_eq!(frame.header.prob_intra, 224); + assert_eq!(frame.header.prob_last, 233); + assert_eq!(frame.header.prob_golden, 1); + + assert_eq!(frame.header.bd_range, 0x8e); + assert_eq!(frame.header.bd_value, 0x85); + assert_eq!(frame.header.bd_count, 5); + } +} diff --git a/vendor/cros-codecs/src/codec/vp8/probs.rs b/vendor/cros-codecs/src/codec/vp8/probs.rs new file mode 100644 index 0000000..3bcc2cf --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp8/probs.rs @@ -0,0 +1,365 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! VP8 probability tables as per the reference software and specification. + +pub const MV_UPDATE_PROBS: [[u8; 19]; 2] = [ + [237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254], + [231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254], +]; + +pub const MV_DEFAULT_PROBS: [[u8; 19]; 2] = [ + [162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254], + [164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254], +]; + +pub const NK_Y_MODE_PROBS: [u8; 4] = [112, 86, 140, 37]; + +pub const KF_Y_MODE_PROBS: [u8; 4] = [145, 156, 163, 128]; + +pub const NK_UV_MODE_PROBS: [u8; 3] = [162, 101, 204]; + +pub const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; + +pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], + [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], + [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], + [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], +]; + +pub const COEFF_DEFAULT_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], + [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], + [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128], + ], + [ + [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], + [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], + [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128], + ], + [ + [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], + [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], + [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128], + ], + [ + [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], + [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], + [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128], + ], + [ + [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], + [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], + [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128], + ], + [ + [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], + [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], + [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], + [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], + [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128], + ], + [ + [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], + [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], + [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128], + ], + [ + [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], + [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], + [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128], + ], + [ + [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], + [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], + [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128], + ], + [ + [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], + [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], + [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128], + ], + [ + [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], + [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], + [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128], + ], + [ + [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], + [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], + [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128], + ], + [ + [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], + [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], + [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], + [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128], + ], + [ + [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], + [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], + [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128], + ], + [ + [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], + [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], + [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128], + ], + [ + [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], + [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], + [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], + [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], + [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], + [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], + [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], + [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128], + ], + [ + [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], + [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], + [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128], + ], + [ + [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], + [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], + [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128], + ], + [ + [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], + [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], + [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128], + ], + [ + [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], + [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], + [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128], + ], + [ + [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], + [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], + [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128], + ], + [ + [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], + [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], + [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], +]; diff --git a/vendor/cros-codecs/src/codec/vp9.rs b/vendor/cros-codecs/src/codec/vp9.rs new file mode 100644 index 0000000..d26271e --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp9.rs @@ -0,0 +1,10 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#![warn(clippy::missing_panics_doc)] +#![warn(clippy::panic)] +#![warn(clippy::unwrap_used)] + +pub mod lookups; +pub mod parser; diff --git a/vendor/cros-codecs/src/codec/vp9/lookups.rs b/vendor/cros-codecs/src/codec/vp9/lookups.rs new file mode 100644 index 0000000..4a189de --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp9/lookups.rs @@ -0,0 +1,116 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The DC Quantization lookup table for bit_depth = 8, as per "8.6.1 Dequantization functions" +pub const DC_QLOOKUP: [i16; 256] = [ + 4, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26, 27, + 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 43, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, 66, 66, 67, + 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, 84, 85, 85, 87, + 88, 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, 113, 114, 116, 117, + 118, 120, 121, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, + 156, 158, 161, 164, 166, 169, 172, 174, 177, 180, 182, 185, 187, 190, 192, 195, 199, 202, 205, + 208, 211, 214, 217, 220, 223, 226, 230, 233, 237, 240, 243, 247, 250, 253, 257, 261, 265, 269, + 272, 276, 280, 284, 288, 292, 296, 300, 304, 309, 313, 317, 322, 326, 330, 335, 340, 344, 349, + 354, 359, 364, 369, 374, 379, 384, 389, 395, 400, 406, 411, 417, 423, 429, 435, 441, 447, 454, + 461, 467, 475, 482, 489, 497, 505, 513, 522, 530, 539, 549, 559, 569, 579, 590, 602, 614, 626, + 640, 654, 668, 684, 700, 717, 736, 755, 775, 796, 819, 843, 869, 896, 925, 955, 988, 1022, + 1058, 1098, 1139, 1184, 1232, 1282, 1336, +]; + +/// The DC Quantization lookup table for bit_depth = 10, as per "8.6.1 Dequantization functions" +pub const DC_QLOOKUP_10: [i16; 256] = [ + 4, 9, 10, 13, 15, 17, 20, 22, 25, 28, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, 68, 71, 75, + 78, 82, 86, 90, 93, 97, 101, 105, 109, 113, 116, 120, 124, 128, 132, 136, 140, 143, 147, 151, + 155, 159, 163, 166, 170, 174, 178, 182, 185, 189, 193, 197, 200, 204, 208, 212, 215, 219, 223, + 226, 230, 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 269, 273, 276, 280, 283, 287, 290, + 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 337, 343, 350, 356, 362, 369, + 375, 381, 387, 394, 400, 406, 412, 418, 424, 430, 436, 442, 448, 454, 460, 466, 472, 478, 484, + 490, 499, 507, 516, 525, 533, 542, 550, 559, 567, 576, 584, 592, 601, 609, 617, 625, 634, 644, + 655, 666, 676, 687, 698, 708, 718, 729, 739, 749, 759, 770, 782, 795, 807, 819, 831, 844, 856, + 868, 880, 891, 906, 920, 933, 947, 961, 975, 988, 1001, 1015, 1030, 1045, 1061, 1076, 1090, + 1105, 1120, 1137, 1153, 1170, 1186, 1202, 1218, 1236, 1253, 1271, 1288, 1306, 1323, 1342, 1361, + 1379, 1398, 1416, 1436, 1456, 1476, 1496, 1516, 1537, 1559, 1580, 1601, 1624, 1647, 1670, 1692, + 1717, 1741, 1766, 1791, 1817, 1844, 1871, 1900, 1929, 1958, 1990, 2021, 2054, 2088, 2123, 2159, + 2197, 2236, 2276, 2319, 2363, 2410, 2458, 2508, 2561, 2616, 2675, 2737, 2802, 2871, 2944, 3020, + 3102, 3188, 3280, 3375, 3478, 3586, 3702, 3823, 3953, 4089, 4236, 4394, 4559, 4737, 4929, 5130, + 5347, +]; + +/// The DC Quantization lookup table for bit_depth = 12, as per "8.6.1 Dequantization functions" +pub const DC_QLOOKUP_12: [i16; 256] = [ + 4, 12, 18, 25, 33, 41, 50, 60, 70, 80, 91, 103, 115, 127, 140, 153, 166, 180, 194, 208, 222, + 237, 251, 266, 281, 296, 312, 327, 343, 358, 374, 390, 405, 421, 437, 453, 469, 484, 500, 516, + 532, 548, 564, 580, 596, 611, 627, 643, 659, 674, 690, 706, 721, 737, 752, 768, 783, 798, 814, + 829, 844, 859, 874, 889, 904, 919, 934, 949, 964, 978, 993, 1008, 1022, 1037, 1051, 1065, 1080, + 1094, 1108, 1122, 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234, 1248, 1261, 1275, 1288, 1302, + 1315, 1329, 1342, 1368, 1393, 1419, 1444, 1469, 1494, 1519, 1544, 1569, 1594, 1618, 1643, 1668, + 1692, 1717, 1741, 1765, 1789, 1814, 1838, 1862, 1885, 1909, 1933, 1957, 1992, 2027, 2061, 2096, + 2130, 2165, 2199, 2233, 2267, 2300, 2334, 2367, 2400, 2434, 2467, 2499, 2532, 2575, 2618, 2661, + 2704, 2746, 2788, 2830, 2872, 2913, 2954, 2995, 3036, 3076, 3127, 3177, 3226, 3275, 3324, 3373, + 3421, 3469, 3517, 3565, 3621, 3677, 3733, 3788, 3843, 3897, 3951, 4005, 4058, 4119, 4181, 4241, + 4301, 4361, 4420, 4479, 4546, 4612, 4677, 4742, 4807, 4871, 4942, 5013, 5083, 5153, 5222, 5291, + 5367, 5442, 5517, 5591, 5665, 5745, 5825, 5905, 5984, 6063, 6149, 6234, 6319, 6404, 6495, 6587, + 6678, 6769, 6867, 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, 7832, 7958, 8085, 8214, 8352, + 8492, 8635, 8788, 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, 10465, 10702, 10946, 11210, + 11482, 11776, 12081, 12409, 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, 16356, + 16943, 17575, 18237, 18949, 19718, 20521, 21387, +]; + +/// The AC Quantization lookup table for bit_depth = 8, as per "8.6.1 Dequantization functions" +pub const AC_QLOOKUP: [i16; 256] = [ + 4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, + 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, + 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, + 140, 142, 144, 146, 148, 150, 152, 155, 158, 161, 164, 167, 170, 173, 176, 179, 182, 185, 188, + 191, 194, 197, 200, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, 255, 260, + 265, 270, 275, 280, 285, 290, 295, 300, 305, 311, 317, 323, 329, 335, 341, 347, 353, 359, 366, + 373, 380, 387, 394, 401, 408, 416, 424, 432, 440, 448, 456, 465, 474, 483, 492, 501, 510, 520, + 530, 540, 550, 560, 571, 582, 593, 604, 615, 627, 639, 651, 663, 676, 689, 702, 715, 729, 743, + 757, 771, 786, 801, 816, 832, 848, 864, 881, 898, 915, 933, 951, 969, 988, 1007, 1026, 1046, + 1066, 1087, 1108, 1129, 1151, 1173, 1196, 1219, 1243, 1267, 1292, 1317, 1343, 1369, 1396, 1423, + 1451, 1479, 1508, 1537, 1567, 1597, 1628, 1660, 1692, 1725, 1759, 1793, 1828, +]; + +/// The AC Quantization lookup table for bit_depth = 10, as per "8.6.1 Dequantization functions" +pub const AC_QLOOKUP_10: [i16; 256] = [ + 4, 9, 11, 13, 16, 18, 21, 24, 27, 30, 33, 37, 40, 44, 48, 51, 55, 59, 63, 67, 71, 75, 79, 83, + 88, 92, 96, 100, 105, 109, 114, 118, 122, 127, 131, 136, 140, 145, 149, 154, 158, 163, 168, + 172, 177, 181, 186, 190, 195, 199, 204, 208, 213, 217, 222, 226, 231, 235, 240, 244, 249, 253, + 258, 262, 267, 271, 275, 280, 284, 289, 293, 297, 302, 306, 311, 315, 319, 324, 328, 332, 337, + 341, 345, 349, 354, 358, 362, 367, 371, 375, 379, 384, 388, 392, 396, 401, 409, 417, 425, 433, + 441, 449, 458, 466, 474, 482, 490, 498, 506, 514, 523, 531, 539, 547, 555, 563, 571, 579, 588, + 596, 604, 616, 628, 640, 652, 664, 676, 688, 700, 713, 725, 737, 749, 761, 773, 785, 797, 809, + 825, 841, 857, 873, 889, 905, 922, 938, 954, 970, 986, 1002, 1018, 1038, 1058, 1078, 1098, + 1118, 1138, 1158, 1178, 1198, 1218, 1242, 1266, 1290, 1314, 1338, 1362, 1386, 1411, 1435, 1463, + 1491, 1519, 1547, 1575, 1603, 1631, 1663, 1695, 1727, 1759, 1791, 1823, 1859, 1895, 1931, 1967, + 2003, 2039, 2079, 2119, 2159, 2199, 2239, 2283, 2327, 2371, 2415, 2459, 2507, 2555, 2603, 2651, + 2703, 2755, 2807, 2859, 2915, 2971, 3027, 3083, 3143, 3203, 3263, 3327, 3391, 3455, 3523, 3591, + 3659, 3731, 3803, 3876, 3952, 4028, 4104, 4184, 4264, 4348, 4432, 4516, 4604, 4692, 4784, 4876, + 4972, 5068, 5168, 5268, 5372, 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, 6388, 6512, 6640, + 6768, 6900, 7036, 7172, 7312, +]; + +/// The AC Quantization lookup table for bit_depth = 12, as per "8.6.1 Dequantization functions" +pub const AC_QLOOKUP_12: [i16; 256] = [ + 4, 13, 19, 27, 35, 44, 54, 64, 75, 87, 99, 112, 126, 139, 154, 168, 183, 199, 214, 230, 247, + 263, 280, 297, 314, 331, 349, 366, 384, 402, 420, 438, 456, 475, 493, 511, 530, 548, 567, 586, + 604, 623, 642, 660, 679, 698, 716, 735, 753, 772, 791, 809, 828, 846, 865, 884, 902, 920, 939, + 957, 976, 994, 1012, 1030, 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175, 1193, 1211, 1229, + 1246, 1264, 1282, 1299, 1317, 1335, 1352, 1370, 1387, 1405, 1422, 1440, 1457, 1474, 1491, 1509, + 1526, 1543, 1560, 1577, 1595, 1627, 1660, 1693, 1725, 1758, 1791, 1824, 1856, 1889, 1922, 1954, + 1987, 2020, 2052, 2085, 2118, 2150, 2183, 2216, 2248, 2281, 2313, 2346, 2378, 2411, 2459, 2508, + 2556, 2605, 2653, 2701, 2750, 2798, 2847, 2895, 2943, 2992, 3040, 3088, 3137, 3185, 3234, 3298, + 3362, 3426, 3491, 3555, 3619, 3684, 3748, 3812, 3876, 3941, 4005, 4069, 4149, 4230, 4310, 4390, + 4470, 4550, 4631, 4711, 4791, 4871, 4967, 5064, 5160, 5256, 5352, 5448, 5544, 5641, 5737, 5849, + 5961, 6073, 6185, 6297, 6410, 6522, 6650, 6778, 6906, 7034, 7162, 7290, 7435, 7579, 7723, 7867, + 8011, 8155, 8315, 8475, 8635, 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, 10220, 10412, + 10604, 10812, 11020, 11228, 11437, 11661, 11885, 12109, 12333, 12573, 12813, 13053, 13309, + 13565, 13821, 14093, 14365, 14637, 14925, 15213, 15502, 15806, 16110, 16414, 16734, 17054, + 17390, 17726, 18062, 18414, 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, 21902, + 22334, 22766, 23214, 23662, 24126, 24590, 25070, 25551, 26047, 26559, 27071, 27599, 28143, + 28687, 29247, +]; diff --git a/vendor/cros-codecs/src/codec/vp9/parser.rs b/vendor/cros-codecs/src/codec/vp9/parser.rs new file mode 100644 index 0000000..3ae1b66 --- /dev/null +++ b/vendor/cros-codecs/src/codec/vp9/parser.rs @@ -0,0 +1,1478 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::bitstream_utils::BitReader; +use crate::codec::vp9::lookups::AC_QLOOKUP; +use crate::codec::vp9::lookups::AC_QLOOKUP_10; +use crate::codec::vp9::lookups::AC_QLOOKUP_12; +use crate::codec::vp9::lookups::DC_QLOOKUP; +use crate::codec::vp9::lookups::DC_QLOOKUP_10; +use crate::codec::vp9::lookups::DC_QLOOKUP_12; + +pub const REFS_PER_FRAME: usize = 3; + +pub const MAX_REF_LF_DELTAS: usize = 4; +pub const MAX_MODE_LF_DELTAS: usize = 2; + +pub const INTRA_FRAME: usize = 0; +pub const LAST_FRAME: usize = 1; +pub const GOLDEN_FRAME: usize = 2; +pub const ALTREF_FRAME: usize = 3; +pub const MAX_REF_FRAMES: usize = 4; + +pub const MAX_SEGMENTS: usize = 8; +pub const SEG_TREE_PROBS: usize = MAX_SEGMENTS - 1; +pub const PREDICTION_PROBS: usize = 3; + +/// Valid segment features values. +#[repr(u8)] +pub enum SegLvl { + AltQ = 0, + AltL = 1, + RefFrame = 2, + LvlSkip = 3, +} +pub const SEG_LVL_MAX: usize = 4; + +pub const MAX_LOOP_FILTER: u32 = 63; + +pub const REF_FRAMES_LOG2: usize = 3; +pub const REF_FRAMES: usize = 1 << REF_FRAMES_LOG2; + +pub const SUPERFRAME_MARKER: u32 = 0x06; +pub const MAX_FRAMES_IN_SUPERFRAME: usize = 8; + +pub const FRAME_MARKER: u32 = 0x02; +pub const SYNC_CODE: u32 = 0x498342; + +pub const MIN_TILE_WIDTH_B64: u32 = 4; +pub const MAX_TILE_WIDTH_B64: u32 = 64; + +/// The number of pictures in the DPB +pub const NUM_REF_FRAMES: usize = 8; + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum InterpolationFilter { + #[default] + EightTap = 0, + EightTapSmooth = 1, + EightTapSharp = 2, + Bilinear = 3, + Switchable = 4, +} + +impl TryFrom for InterpolationFilter { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(InterpolationFilter::EightTap), + 1 => Ok(InterpolationFilter::EightTapSmooth), + 2 => Ok(InterpolationFilter::EightTapSharp), + 3 => Ok(InterpolationFilter::Bilinear), + 4 => Ok(InterpolationFilter::Switchable), + _ => Err(format!("Invalid InterpolationFilter {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ReferenceFrameType { + Intra = 0, + Last = 1, + Golden = 2, + AltRef = 3, +} + +impl TryFrom for ReferenceFrameType { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ReferenceFrameType::Intra), + 1 => Ok(ReferenceFrameType::Last), + 2 => Ok(ReferenceFrameType::Golden), + 3 => Ok(ReferenceFrameType::AltRef), + _ => Err(format!("Invalid ReferenceFrameType {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum FrameType { + #[default] + KeyFrame = 0, + InterFrame = 1, +} + +impl TryFrom for FrameType { + type Error = String; + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(FrameType::KeyFrame), + 1 => Ok(FrameType::InterFrame), + _ => Err(format!("Invalid FrameType {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum Profile { + #[default] + Profile0 = 0, + Profile1 = 1, + Profile2 = 2, + Profile3 = 3, +} + +impl TryFrom for Profile { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(Profile::Profile0), + 1 => Ok(Profile::Profile1), + 2 => Ok(Profile::Profile2), + 3 => Ok(Profile::Profile3), + _ => Err(format!("Invalid Profile {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum BitDepth { + #[default] + Depth8 = 8, + Depth10 = 10, + Depth12 = 12, +} + +impl TryFrom for BitDepth { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 8 => Ok(BitDepth::Depth8), + 10 => Ok(BitDepth::Depth10), + 12 => Ok(BitDepth::Depth12), + _ => Err(format!("Invalid BitDepth {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum ColorSpace { + #[default] + Unknown = 0, + Bt601 = 1, + Bt709 = 2, + Smpte170 = 3, + Smpte240 = 4, + Bt2020 = 5, + Reserved2 = 6, + CsSrgb = 7, +} + +impl TryFrom for ColorSpace { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ColorSpace::Unknown), + 1 => Ok(ColorSpace::Bt601), + 2 => Ok(ColorSpace::Bt709), + 3 => Ok(ColorSpace::Smpte170), + 4 => Ok(ColorSpace::Smpte240), + 5 => Ok(ColorSpace::Bt2020), + 6 => Ok(ColorSpace::Reserved2), + 7 => Ok(ColorSpace::CsSrgb), + _ => Err(format!("Invalid ColorSpace {}", value)), + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum ColorRange { + #[default] + StudioSwing = 0, + FullSwing = 1, +} + +impl TryFrom for ColorRange { + type Error = String; + + fn try_from(value: u32) -> Result { + match value { + 0 => Ok(ColorRange::StudioSwing), + 1 => Ok(ColorRange::FullSwing), + _ => Err(format!("Invalid ColorRange {}", value)), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LoopFilterParams { + /// Indicates the loop filter strength. + pub level: u8, + /// Indicates the sharpness level. The loop filter level and loop + /// filter_sharpness together determine when a block edge is filtered, and + /// by how much the filtering can change the sample values. + pub sharpness: u8, + /// If set, means that the filter level depends on the mode and reference + /// frame used to predict a block. If unset, means that the filter level + /// does not depend on the mode and reference frame. + pub delta_enabled: bool, + /// If set, means that the bitstream contains additional syntax elements + /// that specify which mode and reference frame deltas are to be updated. If + /// unset, means that these syntax elements are not present. + pub delta_update: bool, + /// If set, means that the bitstream contains additional syntax elements + /// that specify which mode and reference frame deltas are to be updated. If + /// unset, means that these syntax elements are not present. + pub update_ref_delta: [bool; MAX_REF_LF_DELTAS], + /// Contains the adjustment needed for the filter level based on the chosen + /// reference frame. If this syntax element is not present in the bitstream, + /// it maintains its previous value. + pub ref_deltas: [i8; MAX_REF_LF_DELTAS], + /// If set, means that the bitstream contains the syntax element + /// loop_filter_mode_deltas. If unset, means that the bitstream does not + /// contain this syntax element. + pub update_mode_delta: [bool; MAX_MODE_LF_DELTAS], + /// Contains the adjustment needed for the filter level based on the chosen + /// mode. If this syntax element is not present in the bitstream, it + /// maintains its previous value. + pub mode_deltas: [i8; MAX_MODE_LF_DELTAS], +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct QuantizationParams { + /// Indicates the base frame qindex. This is used for Y AC coefficients and + /// as the base value for the other quantizers. + pub base_q_idx: u8, + /// Indicates the Y DC quantizer relative to base_q_idx. + pub delta_q_y_dc: i8, + /// Indicates the UV DC quantizer relative to base_q_idx. + pub delta_q_uv_dc: i8, + /// Indicates the UV AC quantizer relative to base_q_idx. + pub delta_q_uv_ac: i8, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SegmentationParams { + /// If set, indicates that this frame makes use of the segmentation tool. + /// If unset, indicates that the frame does not use segmentation. + pub enabled: bool, + /// If set, indicates that the segmentation map should be updated during + /// the decoding of this frame. If unset, means that the segmentation map + /// from the previous frame is used. + pub update_map: bool, + /// Specify the probability values to be used when decoding segment_id. + pub tree_probs: [u8; SEG_TREE_PROBS], + /// Specify the probability values to be used when decoding seg_id_predicted. + pub pred_probs: [u8; PREDICTION_PROBS], + /// If set, indicates that the updates to the segmentation map are coded + /// relative to the existing segmentation map. If unset, + /// indicates that the new segmentation map is coded without + /// reference to the existing segmentation map. + pub temporal_update: bool, + /// If set, indicates that new parameters are about to be specified for each + /// segment. If unset, indicates that the segmentation parameters should + /// keep their existing values. + pub update_data: bool, + /// If unset, indicates that the segmentation parameters represent + /// adjustments relative to the standard values. If set, indicates that the + /// segmentation parameters represent the actual values to be used. + pub abs_or_delta_update: bool, + /// If unset, indicates that the corresponding feature is unused and has + /// value equal to 0. if set, indicates that the feature value is coded in + /// the bitstream. + pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], + /// Specifies the magnitude of the feature data for a segment feature. + pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], +} + +impl SegmentationParams { + /// Returns whether `feature` is enabled for `segment_id`. + fn is_feature_enabled(&self, segment_id: u8, feature: SegLvl) -> bool { + self.feature_enabled[segment_id as usize][feature as usize] + } + + /// An implementation of seg_feature_active as per "6.4.9 Segmentation feature active syntax" + fn is_feature_active(&self, segment_id: u8, feature: SegLvl) -> bool { + self.enabled && self.is_feature_enabled(segment_id, feature) + } + + /// Returns the data for `feature` on `segment_id`. + fn feature_data(&self, segment_id: u8, feature: SegLvl) -> i16 { + self.feature_data[segment_id as usize][feature as usize] + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Segmentation { + /// Loop filter level + pub lvl_lookup: [[u8; MAX_MODE_LF_DELTAS]; MAX_REF_FRAMES], + + /// AC quant scale for luma component + pub luma_ac_quant_scale: i16, + /// DC quant scale for luma component + pub luma_dc_quant_scale: i16, + /// AC quant scale for chroma component + pub chroma_ac_quant_scale: i16, + /// DC quant scale for chroma component + pub chroma_dc_quant_scale: i16, + + /// Whether the alternate reference frame segment feature is enabled (SEG_LVL_REF_FRAME) + pub reference_frame_enabled: bool, + /// The feature data for the reference frame featire + pub reference_frame: i16, + /// Whether the skip segment feature is enabled (SEG_LVL_SKIP) + pub reference_skip_enabled: bool, +} + +impl Segmentation { + /// Update the state of the segmentation parameters after seeing a frame + pub fn update_segmentation(segmentation: &mut [Segmentation; MAX_SEGMENTS], hdr: &Header) { + let lf = &hdr.lf; + let seg = &hdr.seg; + + let n_shift = lf.level >> 5; + + for segment_id in 0..MAX_SEGMENTS as u8 { + let luma_dc_quant_scale = hdr.get_dc_quant(segment_id, true); + let luma_ac_quant_scale = hdr.get_ac_quant(segment_id, true); + let chroma_dc_quant_scale = hdr.get_dc_quant(segment_id, false); + let chroma_ac_quant_scale = hdr.get_ac_quant(segment_id, false); + + let mut lvl_lookup: [[u8; MAX_MODE_LF_DELTAS]; MAX_REF_FRAMES]; + + if lf.level == 0 { + lvl_lookup = Default::default() + } else { + let mut lvl_seg = i32::from(lf.level); + + // 8.8.1 Loop filter frame init process + if hdr.seg.is_feature_active(segment_id, SegLvl::AltL) { + if seg.abs_or_delta_update { + lvl_seg = i32::from(seg.feature_data(segment_id, SegLvl::AltL)); + } else { + lvl_seg += i32::from(seg.feature_data(segment_id, SegLvl::AltL)); + } + } + + let lvl_seg = lvl_seg.clamp(0, MAX_LOOP_FILTER as i32) as u8; + + if !lf.delta_enabled { + lvl_lookup = [[lvl_seg; MAX_MODE_LF_DELTAS]; MAX_REF_FRAMES] + } else { + let intra_delta = lf.ref_deltas[INTRA_FRAME] as i32; + let mut intra_lvl = lvl_seg as i32 + (intra_delta << n_shift); + + lvl_lookup = segmentation[segment_id as usize].lvl_lookup; + lvl_lookup[INTRA_FRAME][0] = intra_lvl.clamp(0, MAX_LOOP_FILTER as i32) as u8; + + // Note, this array has the [0] element unspecified/unused in + // VP9. Confusing, but we do start to index from 1. + #[allow(clippy::needless_range_loop)] + for ref_ in LAST_FRAME..MAX_REF_FRAMES { + for mode in 0..MAX_MODE_LF_DELTAS { + let ref_delta = lf.ref_deltas[ref_] as i32; + let mode_delta = lf.mode_deltas[mode] as i32; + + intra_lvl = + lvl_seg as i32 + (ref_delta << n_shift) + (mode_delta << n_shift); + + lvl_lookup[ref_][mode] = + intra_lvl.clamp(0, MAX_LOOP_FILTER as i32) as u8; + } + } + } + } + + segmentation[usize::from(segment_id)] = Segmentation { + lvl_lookup, + luma_ac_quant_scale, + luma_dc_quant_scale, + chroma_ac_quant_scale, + chroma_dc_quant_scale, + reference_frame_enabled: seg.is_feature_enabled(segment_id, SegLvl::RefFrame), + reference_frame: seg.feature_data(segment_id, SegLvl::RefFrame), + reference_skip_enabled: seg.is_feature_enabled(segment_id, SegLvl::LvlSkip), + } + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct FrameSize { + width: u32, + height: u32, +} + +pub struct Frame<'a> { + /// The bitstream data for this frame. + bitstream: &'a [u8], + /// The frame header. + pub header: Header, + /// The offset into T + offset: usize, + /// The size of the data in T + size: usize, +} + +impl<'a> Frame<'a> { + pub fn new(bitstream: &'a [u8], header: Header, offset: usize, size: usize) -> Self { + Self { bitstream, header, offset, size } + } +} + +impl<'a> AsRef<[u8]> for Frame<'a> { + fn as_ref(&self) -> &[u8] { + let data = self.bitstream; + &data[self.offset..self.offset + self.size] + } +} + +/// A VP9 frame header. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Header { + /// A subset of syntax, semantics and algorithms defined in a part. + pub profile: Profile, + /// The bit depth of the frame. + pub bit_depth: BitDepth, + /// Specifies the chroma subsampling format. + pub subsampling_x: bool, + /// Specifies the chroma subsampling format. + pub subsampling_y: bool, + /// Specifies the color space of the stream. + pub color_space: ColorSpace, + /// Specifies the black level and range of the luma and chroma signals as + /// specified in Rec. ITU-R BT.709-6 and Rec. ITU-R BT.2020-2 + pub color_range: ColorRange, + /// Indicates the frame indexed by frame_to_show_map_idx is to be displayed. + /// If unset, indicates that further processing is required. + pub show_existing_frame: bool, + /// Specifies the frame to be displayed. It is only available if + /// show_existing_frame is set. + pub frame_to_show_map_idx: u8, + /// Indicates whether a frame is a key frame. + pub frame_type: FrameType, + /// Whether this frame should be displayed. + pub show_frame: bool, + /// Whether error resilient mode is enabled. + pub error_resilient_mode: bool, + /// The width of the frame in pixels. + pub width: u32, + /// The height of the frame in pixels. + pub height: u32, + /// If unset, means that the render width and height are inferred from the + /// frame width and height. If set, means that the render width and height + /// are explicitly coded in the bitstream. + pub render_and_frame_size_different: bool, + /// The render width of the frame in pixels. + pub render_width: u32, + /// The render height of the frame in pixels. + pub render_height: u32, + /// If set, indicates that this frame is an intra-only frame. If unset, + /// indicates that this frame is a inter frame. + pub intra_only: bool, + /// Specifies whether the frame context should be reset to default values. + pub reset_frame_context: u8, + /// Contains a bitmask that specifies which reference frame slots will be + /// updated with the current frame after it is decoded. + pub refresh_frame_flags: u8, + /// Specifies which reference frames are used by inter frames. It is a + /// requirement of bitstream conformance that the selected reference frames + /// match the current frame in bit depth, profile, chroma subsampling, and + /// color space. + pub ref_frame_idx: [u8; REFS_PER_FRAME], + /// Specifies the intended direction of the motion vector in time for each + /// reference frame. A sign bias equal to 0 indicates that the reference + /// frame is a backwards reference; a sign bias equal to 1 indicates that + /// the reference frame is a forwards reference + pub ref_frame_sign_bias: [u8; 4], + /// If unset, specifies that motion vectors are specified to quarter pel + /// precision. If set, specifies that motion vectors are specified to eighth + /// pel precision. + pub allow_high_precision_mv: bool, + /// The interpolation filter parameters. + pub interpolation_filter: InterpolationFilter, + /// If set, indicates that the probabilities computed for this frame (after + /// adapting to the observed frequencies if adaption is enabled) should be + /// stored for reference by future frames. If unset, indicates that the + /// probabilities should be discarded at the end of the frame. + pub refresh_frame_context: bool, + /// Whether parallel decoding mode is enabled. + pub frame_parallel_decoding_mode: bool, + /// Indicates the frame context to use. + pub frame_context_idx: u8, + /// The loop filter parameters + pub lf: LoopFilterParams, + /// The quantization parameters. + pub quant: QuantizationParams, + /// The segmentation parameters + pub seg: SegmentationParams, + /// Specifies the base 2 logarithm of the width of each tile (where the + /// width is measured in units of 8x8 blocks). It is a requirement of + /// bitstream conformance that tile_cols_log2 is less than or equal to 6. + pub tile_cols_log2: u8, + /// Specifies the base 2 logarithm of the height of each tile (where the + /// height is measured in units of 8x8 blocks). + pub tile_rows_log2: u8, + /// Computed from the syntax elements. If set, indicates that the frame is + /// coded using a special 4x4 transform designed for encoding frames that + /// are bit-identical with the original frames. + pub lossless: bool, + /// Indicates the size of the compressed header in bytes. + pub header_size_in_bytes: u16, + /// Indicates the size of the uncompressed header in bytes. + pub uncompressed_header_size_in_bytes: u16, +} + +impl Header { + /// An implementation of get_qindex as per "8.6.1 Dequantization functions" + fn get_qindex(&self, segment_id: u8) -> u8 { + let base_q_idx = self.quant.base_q_idx; + + if self.seg.is_feature_active(segment_id, SegLvl::AltQ) { + let mut data = self.seg.feature_data(segment_id, SegLvl::AltQ) as i32; + + if !self.seg.abs_or_delta_update { + data += base_q_idx as i32; + } + + data.clamp(0, 255) as u8 + } else { + base_q_idx + } + } + + /// An implementation of get_dc_quant as per "8.6.1 Dequantization functions" + fn get_dc_quant(&self, segment_id: u8, luma: bool) -> i16 { + let delta_q_dc = + if luma { self.quant.delta_q_y_dc } else { self.quant.delta_q_uv_dc } as i32; + let qindex = self.get_qindex(segment_id); + let q_table_idx = (qindex as i32 + delta_q_dc).clamp(0, 255) as u8; + + let table = match self.bit_depth { + BitDepth::Depth8 => &DC_QLOOKUP, + BitDepth::Depth10 => &DC_QLOOKUP_10, + BitDepth::Depth12 => &DC_QLOOKUP_12, + }; + + table[q_table_idx as usize] + } + + /// An implementation of get_ac_quant as per "8.6.1 Dequantization functions" + fn get_ac_quant(&self, segment_id: u8, luma: bool) -> i16 { + let delta_q_ac = if luma { 0 } else { self.quant.delta_q_uv_ac } as i32; + let qindex = self.get_qindex(segment_id); + let q_table_idx = (qindex as i32 + delta_q_ac).clamp(0, 255) as u8; + + let table = match self.bit_depth { + BitDepth::Depth8 => &AC_QLOOKUP, + BitDepth::Depth10 => &AC_QLOOKUP_10, + BitDepth::Depth12 => &AC_QLOOKUP_12, + }; + + table[q_table_idx as usize] + } +} + +/// The VP9 superframe header as per Annex B, B.2.1, B.2.2 +struct SuperframeHeader { + /// Indicates the number of frames within this superframe. NOTE - It is + /// legal for a superframe to contain just a single frame and have NumFrames + /// equal to 1. + frames_in_superframe: u32, + /// Specifies the size in bytes of frame number i (zero indexed) within this + /// superframe. + frame_sizes: Vec, +} + +/// A VP9 bitstream parser. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Parser { + bit_depth: BitDepth, + subsampling_x: bool, + subsampling_y: bool, + color_space: ColorSpace, + color_range: ColorRange, + + mi_cols: u32, + mi_rows: u32, + sb64_cols: u32, + sb64_rows: u32, + + lf: LoopFilterParams, + seg: SegmentationParams, + + reference_frame_sz: [FrameSize; REF_FRAMES], +} + +impl Parser { + fn parse_superframe_hdr(resource: impl AsRef<[u8]>) -> Result { + let bitstream = resource.as_ref(); + + // Skip to the end of the chunk. + let mut reader = BitReader::new(&bitstream[bitstream.len() - 1..], false); + + // Try reading a superframe marker. + let marker = reader.read_bits::(3)?; + + if marker != SUPERFRAME_MARKER { + // Not a superframe + return Ok(SuperframeHeader { + frames_in_superframe: 1, + frame_sizes: vec![bitstream.len()], + }); + } + + let bytes_per_framesize = reader.read_bits::(2)? + 1; + let frames_in_superframe = reader.read_bits::(3)? + 1; + + if frames_in_superframe > MAX_FRAMES_IN_SUPERFRAME as u32 { + return Err(format!( + "Broken stream: too many frames in superframe, expected a maximum of {:?}, found {:?}", + MAX_FRAMES_IN_SUPERFRAME, + frames_in_superframe + )); + } + + let sz_index = 2 + frames_in_superframe * bytes_per_framesize; + + let data = resource.as_ref(); + let index_offset = data.len() - sz_index as usize; + let first_byte = data[index_offset]; + let last_byte = *data.last().ok_or_else(|| String::from("superframe header is empty"))?; + + if first_byte != last_byte { + // Also not a superframe, we must pass both tests as per the specification. + return Ok(SuperframeHeader { + frames_in_superframe: 1, + frame_sizes: vec![bitstream.len()], + }); + } + + let mut frame_sizes = vec![]; + let mut reader = BitReader::new(&bitstream[index_offset..], false); + + // Skip the superframe header. + let _ = reader.read_bits::(8)?; + + for _ in 0..frames_in_superframe { + let mut frame_size = 0; + + for j in 0..bytes_per_framesize { + frame_size |= reader.read_bits::(8)? << (j * 8); + } + + frame_sizes.push(frame_size as usize); + } + + Ok(SuperframeHeader { frames_in_superframe, frame_sizes }) + } + + fn read_signed_8(r: &mut BitReader, nbits: u8) -> Result { + let value = r.read_bits::(nbits as usize)?; + let negative = r.read_bit()?; + + if negative { + Ok(-(value as i8)) + } else { + Ok(value as i8) + } + } + + fn parse_frame_marker(r: &mut BitReader) -> Result<(), String> { + let marker = r.read_bits::(2)?; + + if marker != FRAME_MARKER { + return Err(format!("Broken stream: expected frame marker, found {:?}", marker)); + } + + Ok(()) + } + + fn parse_profile(r: &mut BitReader) -> Result { + let low = r.read_bits::(1)?; + let high = r.read_bits::(1)?; + + let profile = (high << 1) | low; + + if profile == 3 { + // Skip the reserved bit + let _ = r.read_bit()?; + } + + Profile::try_from(profile) + } + + fn parse_frame_sync_code(r: &mut BitReader) -> Result<(), String> { + let sync_code = r.read_bits::(24)?; + + if sync_code != SYNC_CODE { + return Err(format!( + "Broken stream: expected sync code == {:?}, found {:?}", + SYNC_CODE, sync_code + )); + } + + Ok(()) + } + + fn parse_color_config(&mut self, r: &mut BitReader, hdr: &mut Header) -> Result<(), String> { + if matches!(hdr.profile, Profile::Profile2 | Profile::Profile3) { + let ten_or_twelve_bit = r.read_bit()?; + if ten_or_twelve_bit { + hdr.bit_depth = BitDepth::Depth12; + } else { + hdr.bit_depth = BitDepth::Depth10 + } + } else { + hdr.bit_depth = BitDepth::Depth8; + } + + let color_space = r.read_bits::(3)?; + hdr.color_space = ColorSpace::try_from(color_space)?; + + if !matches!(hdr.color_space, ColorSpace::CsSrgb) { + let color_range = r.read_bits::(1)?; + + hdr.color_range = ColorRange::try_from(color_range)?; + + if matches!(hdr.profile, Profile::Profile1 | Profile::Profile3) { + hdr.subsampling_x = r.read_bit()?; + hdr.subsampling_y = r.read_bit()?; + + // Skip the reserved bit + let _ = r.read_bit()?; + } else { + hdr.subsampling_x = true; + hdr.subsampling_y = true; + } + } else { + hdr.color_range = ColorRange::FullSwing; + if matches!(hdr.profile, Profile::Profile1 | Profile::Profile3) { + hdr.subsampling_x = false; + hdr.subsampling_y = false; + + // Skip the reserved bit + let _ = r.read_bit()?; + } + } + + self.bit_depth = hdr.bit_depth; + self.color_space = hdr.color_space; + self.subsampling_x = hdr.subsampling_x; + self.subsampling_y = hdr.subsampling_y; + self.color_range = hdr.color_range; + + Ok(()) + } + + fn compute_image_size(&mut self, width: u32, height: u32) { + self.mi_cols = (width + 7) >> 3; + self.mi_rows = (height + 7) >> 3; + self.sb64_cols = (self.mi_cols + 7) >> 3; + self.sb64_rows = (self.mi_rows + 7) >> 3; + } + + fn parse_frame_size(&mut self, r: &mut BitReader, hdr: &mut Header) -> Result<(), String> { + hdr.width = r.read_bits::(16)? + 1; + hdr.height = r.read_bits::(16)? + 1; + self.compute_image_size(hdr.width, hdr.height); + Ok(()) + } + + fn parse_render_size(r: &mut BitReader, hdr: &mut Header) -> Result<(), String> { + hdr.render_and_frame_size_different = r.read_bit()?; + if hdr.render_and_frame_size_different { + hdr.render_width = r.read_bits::(16)? + 1; + hdr.render_height = r.read_bits::(16)? + 1; + } else { + hdr.render_width = hdr.width; + hdr.render_height = hdr.height; + } + + Ok(()) + } + + fn parse_frame_size_with_refs( + &mut self, + r: &mut BitReader, + hdr: &mut Header, + ) -> Result<(), String> { + let mut found_ref = false; + + for i in 0..REFS_PER_FRAME { + found_ref = r.read_bit()?; + + if found_ref { + let idx = hdr.ref_frame_idx[i] as usize; + hdr.width = self.reference_frame_sz[idx].width; + hdr.height = self.reference_frame_sz[idx].height; + break; + } + } + + if !found_ref { + self.parse_frame_size(r, hdr)?; + } else { + self.compute_image_size(hdr.width, hdr.height) + } + + Self::parse_render_size(r, hdr) + } + + fn read_interpolation_filter(r: &mut BitReader) -> Result { + const LITERAL_TO_TYPE: [InterpolationFilter; 4] = [ + InterpolationFilter::EightTapSmooth, + InterpolationFilter::EightTap, + InterpolationFilter::EightTapSharp, + InterpolationFilter::Bilinear, + ]; + + let is_filter_switchable = r.read_bit()?; + + Ok(if is_filter_switchable { + InterpolationFilter::Switchable + } else { + let raw_interpolation_filter = r.read_bits::(2)?; + LITERAL_TO_TYPE[raw_interpolation_filter as usize] + }) + } + + fn setup_past_independence(&mut self, hdr: &mut Header) { + self.seg.feature_enabled = Default::default(); + self.seg.feature_data = Default::default(); + self.seg.abs_or_delta_update = false; + + self.lf.delta_enabled = true; + self.lf.ref_deltas[ReferenceFrameType::Intra as usize] = 1; + self.lf.ref_deltas[ReferenceFrameType::Last as usize] = 0; + self.lf.ref_deltas[ReferenceFrameType::Golden as usize] = -1; + self.lf.ref_deltas[ReferenceFrameType::AltRef as usize] = -1; + + self.lf.mode_deltas = Default::default(); + hdr.ref_frame_sign_bias = Default::default(); + } + + fn parse_loop_filter_params( + r: &mut BitReader, + lf: &mut LoopFilterParams, + ) -> Result<(), String> { + lf.level = r.read_bits::(6)?; + lf.sharpness = r.read_bits::(3)?; + lf.delta_enabled = r.read_bit()?; + + if lf.delta_enabled { + lf.delta_update = r.read_bit()?; + if lf.delta_update { + for i in 0..MAX_REF_LF_DELTAS { + lf.update_ref_delta[i] = r.read_bit()?; + if lf.update_ref_delta[i] { + lf.ref_deltas[i] = Self::read_signed_8(r, 6)?; + } + } + + for i in 0..MAX_MODE_LF_DELTAS { + lf.update_mode_delta[i] = r.read_bit()?; + if lf.update_mode_delta[i] { + lf.mode_deltas[i] = Self::read_signed_8(r, 6)?; + } + } + } + } + + Ok(()) + } + + fn read_delta_q(r: &mut BitReader, value: &mut i8) -> Result<(), String> { + let delta_coded = r.read_bit()?; + + if delta_coded { + *value = Self::read_signed_8(r, 4)?; + } else { + *value = 0; + } + + Ok(()) + } + + fn parse_quantization_params(r: &mut BitReader, hdr: &mut Header) -> Result<(), String> { + let quant = &mut hdr.quant; + + quant.base_q_idx = r.read_bits::(8)?; + + Self::read_delta_q(r, &mut quant.delta_q_y_dc)?; + Self::read_delta_q(r, &mut quant.delta_q_uv_dc)?; + Self::read_delta_q(r, &mut quant.delta_q_uv_ac)?; + + hdr.lossless = quant.base_q_idx == 0 + && quant.delta_q_y_dc == 0 + && quant.delta_q_uv_dc == 0 + && quant.delta_q_uv_ac == 0; + + Ok(()) + } + + fn read_prob(r: &mut BitReader) -> Result { + let prob_coded = r.read_bit()?; + + let prob = if prob_coded { r.read_bits::(8)? } else { 255 }; + + Ok(prob) + } + + fn parse_segmentation_params( + r: &mut BitReader, + seg: &mut SegmentationParams, + ) -> Result<(), String> { + const SEGMENTATION_FEATURE_BITS: [u8; SEG_LVL_MAX] = [8, 6, 2, 0]; + const SEGMENTATION_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false]; + + seg.update_map = false; + seg.update_data = false; + + seg.enabled = r.read_bit()?; + + if !seg.enabled { + return Ok(()); + } + + seg.update_map = r.read_bit()?; + + if seg.update_map { + for i in 0..SEG_TREE_PROBS { + seg.tree_probs[i] = Self::read_prob(r)?; + } + + seg.temporal_update = r.read_bit()?; + + for i in 0..PREDICTION_PROBS { + seg.pred_probs[i] = if seg.temporal_update { Self::read_prob(r)? } else { 255 }; + } + } + + seg.update_data = r.read_bit()?; + + if seg.update_data { + seg.abs_or_delta_update = r.read_bit()?; + for i in 0..MAX_SEGMENTS { + for j in 0..SEG_LVL_MAX { + seg.feature_enabled[i][j] = r.read_bit()?; + if seg.feature_enabled[i][j] { + let bits_to_read = SEGMENTATION_FEATURE_BITS[j]; + let mut feature_value = r.read_bits_signed::(bits_to_read as usize)?; + + if SEGMENTATION_FEATURE_SIGNED[j] { + let feature_sign = r.read_bit()?; + + if feature_sign { + feature_value = -feature_value; + } + } + + seg.feature_data[i][j] = feature_value; + } + } + } + } + + Ok(()) + } + + fn calc_min_log2_tile_cols(sb64_cols: u32) -> u8 { + let mut min_log2 = 0; + + while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols { + min_log2 += 1; + } + + min_log2 + } + + fn calc_max_log2_tile_cols(sb64_cols: u32) -> u8 { + let mut max_log2 = 1; + + while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 { + max_log2 += 1; + } + + max_log2 - 1 + } + + fn parse_tile_info(&self, r: &mut BitReader, hdr: &mut Header) -> Result<(), String> { + let max_log2_tile_cols = Self::calc_max_log2_tile_cols(self.sb64_cols); + + hdr.tile_cols_log2 = Self::calc_min_log2_tile_cols(self.sb64_cols); + + while hdr.tile_cols_log2 < max_log2_tile_cols { + let increment_tile_cols_log2 = r.read_bit()?; + + if increment_tile_cols_log2 { + hdr.tile_cols_log2 += 1; + } else { + break; + } + } + + hdr.tile_rows_log2 = r.read_bits::(1)?; + + if hdr.tile_rows_log2 > 0 { + let increment_tile_rows_log2 = r.read_bit()?; + hdr.tile_rows_log2 += increment_tile_rows_log2 as u8; + } + + Ok(()) + } + + fn parse_frame_header( + &mut self, + resource: impl AsRef<[u8]>, + offset: usize, + ) -> Result { + let data = &resource.as_ref()[offset..]; + let mut r = BitReader::new(data, false); + let mut hdr = Header::default(); + + Self::parse_frame_marker(&mut r)?; + hdr.profile = Self::parse_profile(&mut r)?; + + hdr.show_existing_frame = r.read_bit()?; + + if hdr.show_existing_frame { + hdr.frame_to_show_map_idx = r.read_bits::(3)?; + return Ok(hdr); + } + + hdr.frame_type = FrameType::try_from(r.read_bits::(1)?)?; + + hdr.show_frame = r.read_bit()?; + hdr.error_resilient_mode = r.read_bit()?; + + let frame_is_intra; + + if matches!(hdr.frame_type, FrameType::KeyFrame) { + Self::parse_frame_sync_code(&mut r)?; + self.parse_color_config(&mut r, &mut hdr)?; + self.parse_frame_size(&mut r, &mut hdr)?; + Self::parse_render_size(&mut r, &mut hdr)?; + hdr.refresh_frame_flags = 0xff; + frame_is_intra = true; + } else { + if !hdr.show_frame { + hdr.intra_only = r.read_bit()?; + } + + frame_is_intra = hdr.intra_only; + + if !hdr.error_resilient_mode { + hdr.reset_frame_context = r.read_bits::(2)?; + } else { + hdr.reset_frame_context = 0; + } + + if hdr.intra_only { + Self::parse_frame_sync_code(&mut r)?; + + if !matches!(hdr.profile, Profile::Profile0) { + self.parse_color_config(&mut r, &mut hdr)?; + } else { + hdr.color_space = ColorSpace::Bt601; + hdr.subsampling_x = true; + hdr.subsampling_y = true; + hdr.bit_depth = BitDepth::Depth8; + + self.color_space = hdr.color_space; + self.subsampling_x = hdr.subsampling_x; + self.subsampling_y = hdr.subsampling_y; + self.bit_depth = hdr.bit_depth; + } + + hdr.refresh_frame_flags = r.read_bits::(8)?; + self.parse_frame_size(&mut r, &mut hdr)?; + Self::parse_render_size(&mut r, &mut hdr)?; + } else { + // Copy from our cached version + hdr.color_space = self.color_space; + hdr.color_range = self.color_range; + hdr.subsampling_x = self.subsampling_x; + hdr.subsampling_y = self.subsampling_y; + hdr.bit_depth = self.bit_depth; + + hdr.refresh_frame_flags = r.read_bits::(8)?; + + for i in 0..REFS_PER_FRAME { + hdr.ref_frame_idx[i] = r.read_bits::(3)?; + hdr.ref_frame_sign_bias[ReferenceFrameType::Last as usize + i] = + r.read_bits::(1)?; + } + + self.parse_frame_size_with_refs(&mut r, &mut hdr)?; + hdr.allow_high_precision_mv = r.read_bit()?; + hdr.interpolation_filter = Self::read_interpolation_filter(&mut r)?; + } + } + + if !hdr.error_resilient_mode { + hdr.refresh_frame_context = r.read_bit()?; + hdr.frame_parallel_decoding_mode = r.read_bit()?; + } else { + hdr.refresh_frame_context = false; + hdr.frame_parallel_decoding_mode = true; + } + + hdr.frame_context_idx = r.read_bits::(2)?; + + if frame_is_intra || hdr.error_resilient_mode { + self.setup_past_independence(&mut hdr); + } + + Self::parse_loop_filter_params(&mut r, &mut self.lf)?; + Self::parse_quantization_params(&mut r, &mut hdr)?; + Self::parse_segmentation_params(&mut r, &mut self.seg)?; + self.parse_tile_info(&mut r, &mut hdr)?; + + hdr.header_size_in_bytes = r.read_bits::(16)?; + + hdr.lf = self.lf.clone(); + hdr.seg = self.seg.clone(); + + for i in 0..REF_FRAMES { + let flag = 1 << i; + if hdr.refresh_frame_flags & flag != 0 { + self.reference_frame_sz[i].width = hdr.width; + self.reference_frame_sz[i].height = hdr.height; + } + } + + hdr.uncompressed_header_size_in_bytes = (r.position() as u16 + 7) / 8; + + Ok(hdr) + } + + /// Parse a single VP9 frame. + pub fn parse_frame<'a>( + &mut self, + bitstream: &'a [u8], + offset: usize, + size: usize, + ) -> Result, String> { + let header = self.parse_frame_header(bitstream, offset)?; + + Ok(Frame { header, bitstream, offset, size }) + } + + /// Parses VP9 frames from the data in `resource`. This can result in more than one frame if the + /// data passed in contains a VP9 superframe. + pub fn parse_chunk<'a>(&mut self, resource: &'a [u8]) -> Result>, String> { + let superframe_hdr = Parser::parse_superframe_hdr(resource)?; + let mut offset = 0; + + let mut frames = vec![]; + + for i in 0..superframe_hdr.frames_in_superframe { + let frame_sz = superframe_hdr.frame_sizes[i as usize]; + let frame = self.parse_frame(resource, offset, frame_sz)?; + offset += frame_sz; + frames.push(frame); + } + + Ok(frames) + } +} + +#[cfg(test)] +mod tests { + use crate::bitstream_utils::IvfIterator; + use crate::codec::vp9::parser::BitDepth; + use crate::codec::vp9::parser::ColorSpace; + use crate::codec::vp9::parser::FrameType; + use crate::codec::vp9::parser::InterpolationFilter; + use crate::codec::vp9::parser::Parser; + use crate::codec::vp9::parser::Profile; + use crate::codec::vp9::parser::MAX_SEGMENTS; + use crate::codec::vp9::parser::SEG_LVL_MAX; + + #[test] + fn test_parse_superframe() { + // Demuxed, raw vp9 superframe + const VP9_TEST_SUPERFRAME: &[u8] = include_bytes!("test_data/vp9-superframe.bin"); + + let mut parser = Parser::default(); + let frames = parser.parse_chunk(VP9_TEST_SUPERFRAME).expect("Parsing a superframe failed"); + + assert_eq!(frames.len(), 2); + assert_eq!(frames[0].offset, 0); + assert_eq!(frames[0].size, 1333); + assert_eq!(frames[1].offset, 1333); + assert_eq!(frames[1].size, 214); + } + + #[test] + fn test_parse_test25fps() { + // Muxed as IVF + const TEST_STREAM: &[u8] = include_bytes!("test_data/test-25fps.vp9"); + + let mut parser = Parser::default(); + let ivf_iter = IvfIterator::new(TEST_STREAM); + + for (frame_n, packet) in ivf_iter.enumerate() { + let frames = parser.parse_chunk(packet.as_ref()).expect("Parsing a superframe failed"); + + if frame_n == 0 { + assert_eq!(frames.len(), 1); + let h = &frames[0].header; + + assert!(matches!(h.profile, Profile::Profile0)); + assert!(matches!(h.bit_depth, BitDepth::Depth8)); + + assert!(h.subsampling_x); + assert!(h.subsampling_y); + + assert!(matches!(h.color_space, ColorSpace::Unknown)); + assert!(matches!( + h.color_range, + crate::codec::vp9::parser::ColorRange::StudioSwing + )); + + assert!(!h.show_existing_frame); + assert_eq!(h.frame_to_show_map_idx, 0); + + assert!(matches!(h.frame_type, FrameType::KeyFrame)); + assert!(h.show_frame); + assert!(!h.error_resilient_mode); + + assert_eq!(h.width, 320); + assert_eq!(h.height, 240); + + assert!(!h.render_and_frame_size_different); + + assert_eq!(h.render_width, 320); + assert_eq!(h.render_height, 240); + + assert!(!h.intra_only); + assert_eq!(h.reset_frame_context, 0); + + assert_eq!(h.refresh_frame_flags, 0xff); + assert_eq!(h.ref_frame_idx, [0, 0, 0]); + assert_eq!(h.ref_frame_sign_bias, [0, 0, 0, 0]); + + assert!(!h.allow_high_precision_mv); + assert!(matches!(h.interpolation_filter, InterpolationFilter::EightTap)); + + assert!(h.refresh_frame_context); + assert!(h.frame_parallel_decoding_mode); + assert_eq!(h.frame_context_idx, 0); + + let lf = &h.lf; + assert_eq!(lf.level, 9); + assert_eq!(lf.sharpness, 0); + + assert!(lf.delta_enabled); + assert!(lf.delta_update); + + assert_eq!(lf.update_ref_delta, [true, false, true, true]); + assert_eq!(lf.ref_deltas, [1, 0, -1, -1]); + + assert_eq!(lf.update_mode_delta, [false, false]); + + let q = &h.quant; + + assert_eq!(q.base_q_idx, 65); + assert_eq!(q.delta_q_y_dc, 0); + assert_eq!(q.delta_q_uv_dc, 0); + assert_eq!(q.delta_q_uv_ac, 0); + + let s = &h.seg; + + assert!(!s.enabled); + assert!(!s.update_map); + assert_eq!(s.tree_probs, [0, 0, 0, 0, 0, 0, 0]); + assert_eq!(s.pred_probs, [0, 0, 0]); + assert!(!s.temporal_update); + assert!(!s.update_data); + assert!(!s.abs_or_delta_update); + assert_eq!(s.feature_enabled, [[false; SEG_LVL_MAX]; MAX_SEGMENTS]); + assert_eq!(s.feature_data, [[0; SEG_LVL_MAX]; MAX_SEGMENTS]); + + assert_eq!(h.tile_cols_log2, 0); + assert_eq!(h.tile_rows_log2, 0); + assert_eq!(h.header_size_in_bytes, 120); + + assert!(!h.lossless); + } else if frame_n == 1 { + assert_eq!(frames.len(), 2); + + assert_eq!(frames[0].offset, 0); + assert_eq!(frames[0].size, 2390); + assert_eq!(frames[1].offset, 2390); + assert_eq!(frames[1].size, 108); + + let h = &frames[0].header; + + assert!(matches!(h.profile, Profile::Profile0)); + assert!(matches!(h.bit_depth, BitDepth::Depth8)); + + assert!(h.subsampling_x); + assert!(h.subsampling_y); + + assert!(matches!(h.color_space, ColorSpace::Unknown)); + assert!(matches!( + h.color_range, + crate::codec::vp9::parser::ColorRange::StudioSwing + )); + + assert!(!h.show_existing_frame); + assert_eq!(h.frame_to_show_map_idx, 0); + + assert!(matches!(h.frame_type, FrameType::InterFrame)); + assert!(!h.show_frame); + assert!(!h.error_resilient_mode); + + assert_eq!(h.width, 320); + assert_eq!(h.height, 240); + + assert!(!h.render_and_frame_size_different); + + assert_eq!(h.render_width, 320); + assert_eq!(h.render_height, 240); + + assert!(!h.intra_only); + assert_eq!(h.reset_frame_context, 0); + + assert_eq!(h.refresh_frame_flags, 4); + assert_eq!(h.ref_frame_idx, [0, 1, 2]); + assert_eq!(h.ref_frame_sign_bias, [0, 0, 0, 0]); + + assert!(h.allow_high_precision_mv); + assert!(matches!(h.interpolation_filter, InterpolationFilter::EightTap)); + + assert!(h.refresh_frame_context); + assert!(h.frame_parallel_decoding_mode); + assert_eq!(h.frame_context_idx, 1); + + let lf = &h.lf; + assert_eq!(lf.level, 15); + assert_eq!(lf.sharpness, 0); + + assert!(lf.delta_enabled); + assert!(!lf.delta_update); + + assert_eq!(lf.update_ref_delta, [true, false, true, true]); + assert_eq!(lf.ref_deltas, [1, 0, -1, -1]); + + assert_eq!(lf.update_mode_delta, [false, false]); + + let q = &h.quant; + + assert_eq!(q.base_q_idx, 112); + assert_eq!(q.delta_q_y_dc, 0); + assert_eq!(q.delta_q_uv_dc, 0); + assert_eq!(q.delta_q_uv_ac, 0); + + let s = &h.seg; + + assert!(!s.enabled); + assert!(!s.update_map); + assert_eq!(s.tree_probs, [0, 0, 0, 0, 0, 0, 0]); + assert_eq!(s.pred_probs, [0, 0, 0]); + assert!(!s.temporal_update); + assert!(!s.update_data); + assert!(!s.abs_or_delta_update); + assert_eq!(s.feature_enabled, [[false; SEG_LVL_MAX]; MAX_SEGMENTS]); + assert_eq!(s.feature_data, [[0; SEG_LVL_MAX]; MAX_SEGMENTS]); + + assert_eq!(h.tile_cols_log2, 0); + assert_eq!(h.tile_rows_log2, 0); + assert_eq!(h.header_size_in_bytes, 48); + + assert!(!h.lossless); + + let h = &frames[1].header; + + assert!(matches!(h.profile, Profile::Profile0)); + assert!(matches!(h.bit_depth, BitDepth::Depth8)); + + assert!(h.subsampling_x); + assert!(h.subsampling_y); + + assert!(matches!(h.color_space, ColorSpace::Unknown)); + assert!(matches!( + h.color_range, + crate::codec::vp9::parser::ColorRange::StudioSwing + )); + + assert!(!h.show_existing_frame); + assert_eq!(h.frame_to_show_map_idx, 0); + + assert!(matches!(h.frame_type, FrameType::InterFrame)); + assert!(h.show_frame); + assert!(!h.error_resilient_mode); + + assert_eq!(h.width, 320); + assert_eq!(h.height, 240); + + assert!(!h.render_and_frame_size_different); + + assert_eq!(h.render_width, 320); + assert_eq!(h.render_height, 240); + + assert!(!h.intra_only); + assert_eq!(h.reset_frame_context, 0); + + assert_eq!(h.refresh_frame_flags, 1); + assert_eq!(h.ref_frame_idx, [0, 1, 2]); + assert_eq!(h.ref_frame_sign_bias, [0, 0, 0, 1]); + + assert!(!h.allow_high_precision_mv); + assert!(matches!(h.interpolation_filter, InterpolationFilter::EightTap)); + + assert!(h.refresh_frame_context); + assert!(h.frame_parallel_decoding_mode); + assert_eq!(h.frame_context_idx, 0); + + let lf = &h.lf; + assert_eq!(lf.level, 36); + assert_eq!(lf.sharpness, 0); + + assert!(lf.delta_enabled); + assert!(!lf.delta_update); + + assert_eq!(lf.update_ref_delta, [true, false, true, true]); + assert_eq!(lf.ref_deltas, [1, 0, -1, -1]); + + assert_eq!(lf.update_mode_delta, [false, false]); + + let q = &h.quant; + + assert_eq!(q.base_q_idx, 216); + assert_eq!(q.delta_q_y_dc, 0); + assert_eq!(q.delta_q_uv_dc, 0); + assert_eq!(q.delta_q_uv_ac, 0); + + let s = &h.seg; + + assert!(!s.enabled); + assert!(!s.update_map); + assert_eq!(s.tree_probs, [0, 0, 0, 0, 0, 0, 0]); + assert_eq!(s.pred_probs, [0, 0, 0]); + assert!(!s.temporal_update); + assert!(!s.update_data); + assert!(!s.abs_or_delta_update); + assert_eq!(s.feature_enabled, [[false; SEG_LVL_MAX]; MAX_SEGMENTS]); + assert_eq!(s.feature_data, [[0; SEG_LVL_MAX]; MAX_SEGMENTS]); + + assert_eq!(h.tile_cols_log2, 0); + assert_eq!(h.tile_rows_log2, 0); + assert_eq!(h.header_size_in_bytes, 9); + + assert!(!h.lossless); + } + } + } +} diff --git a/vendor/cros-codecs/src/decoder.rs b/vendor/cros-codecs/src/decoder.rs new file mode 100644 index 0000000..5067c0a --- /dev/null +++ b/vendor/cros-codecs/src/decoder.rs @@ -0,0 +1,266 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Encoded stream decoding. +//! +//! A decoder turns an encoded stream into its corresponding decoded frames. This module provides +//! several decoders for various codecs and backends. +//! +//! At the moment, only a [stateless] decoder interface is provided. + +pub mod stateless; + +use std::collections::VecDeque; +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; +use std::sync::Arc; + +use nix::errno::Errno; +use nix::sys::eventfd::EventFd; + +pub use crate::BlockingMode; + +use crate::video_frame::VideoFrame; +use crate::DecodedFormat; +use crate::Resolution; + +/// Trait for a pool of frames in a particular format. +/// +/// This is mostly useful for the decoder where the user is expected to manage how the decoded +/// frames buffers are allocated and when. +pub trait FramePool { + /// Type of descriptor for the memory backing the frames. + type Descriptor; + + /// Returns the coded resolution of the pool. + /// + /// All the frames maintained by this pool are guaranteed to be able to contain the coded + /// resolution. + fn coded_resolution(&self) -> Resolution; + /// Update the coded resolution of the pool. + /// + /// Frames managed by this pool that can not contain the new resolution are dropped. + fn set_coded_resolution(&mut self, resolution: Resolution); + /// Add new frames to the pool, using `descriptors` as backing memory. + fn add_frames(&mut self, descriptors: Vec) -> Result<(), anyhow::Error>; + /// Returns new number of frames currently available in this pool. + fn num_free_frames(&self) -> usize; + /// Returns the total number of managed frames in this pool. + fn num_managed_frames(&self) -> usize; + /// Remove all frames from this pool. + fn clear(&mut self); +} + +/// Information about the current stream. +/// +/// This is static information obtained from the stream itself about its requirements. It does not +/// reflect the current settings of the decoder. +#[derive(Clone, Debug)] +pub struct StreamInfo { + /// Pixel format for the output frames expected by the decoder. + pub format: DecodedFormat, + /// Coded resolution of the stream, i.e. minimum size of the frames to be decoded into. + pub coded_resolution: Resolution, + /// Display resolution of the stream, i.e. the part of the decoded frames we want to display. + pub display_resolution: Resolution, + /// Minimum number of output frames per layer required for decoding to proceed. + /// + /// Codecs keep some frames as references and cannot decode immediately into them again after + /// they are returned. Allocating at least this number of frames guarantees that the decoder + /// won't starve from output frames. + pub min_num_frames: usize, +} + +/// Events that can be retrieved using the `next_event` method of a decoder. +pub enum DecoderEvent { + /// The next frame has been decoded. + FrameReady(H), + /// The format of the stream has changed and action is required. + FormatChanged, +} + +/// The handle type used by the decoder backend. The only requirement from implementors is that +/// they give access to the underlying handle and that they can be (cheaply) cloned. +pub trait DecodedHandle { + type Frame: VideoFrame; + + fn video_frame(&self) -> Arc; + + /// Returns the timestamp of the picture. + fn timestamp(&self) -> u64; + + /// Returns the coded resolution at the time this handle was decoded. + fn coded_resolution(&self) -> Resolution; + + /// Returns the display resolution at the time this handle was decoded. + fn display_resolution(&self) -> Resolution; + + /// Returns `true` if this handle has been completely decoded. + fn is_ready(&self) -> bool; + + /// Wait until this handle has been completely rendered. + fn sync(&self) -> anyhow::Result<()>; +} + +/// Implementation for any boxed [`DecodedHandle`], including trait objects. +impl DecodedHandle for Box +where + H: DecodedHandle + ?Sized, +{ + type Frame = H::Frame; + + fn video_frame(&self) -> Arc { + self.as_ref().video_frame() + } + + fn timestamp(&self) -> u64 { + self.as_ref().timestamp() + } + + fn coded_resolution(&self) -> Resolution { + self.as_ref().coded_resolution() + } + + fn display_resolution(&self) -> Resolution { + self.as_ref().display_resolution() + } + + fn is_ready(&self) -> bool { + self.as_ref().is_ready() + } + + fn sync(&self) -> anyhow::Result<()> { + self.as_ref().sync() + } +} + +/// Trait object for [`DecodedHandle`]s using a specific `VideoFrame`. +pub type DynDecodedHandle = Box>; + +/// A queue where decoding jobs wait until they are completed, at which point they can be +/// retrieved. +struct ReadyFramesQueue { + /// Queue of all the frames waiting to be sent to the client. + queue: VecDeque, + + /// EventFd signaling `EPOLLIN` whenever the queue is not empty. + poll_fd: EventFd, +} + +impl ReadyFramesQueue { + /// Create a nwe `ReadyFramesQueue`. + /// + /// This can only fail if the `EventFd` creation fails ; in this case the corresponding `Errno` + /// is returned. + fn new() -> Result { + let poll_fd = EventFd::new()?; + + Ok(Self { queue: Default::default(), poll_fd }) + } + + /// Push `handle` to the back of the queue. + fn push(&mut self, handle: T) { + self.queue.push_back(handle); + if let Err(e) = self.poll_fd.write(1) { + log::error!("failed to write ready frames queue poll FD: {:#}", e); + } + } + + /// Returns a file descriptor that signals `POLLIN` whenever an event is available on this + /// queue. + pub fn poll_fd(&self) -> BorrowedFd { + self.poll_fd.as_fd() + } +} + +impl Extend for ReadyFramesQueue { + fn extend>(&mut self, iter: I) { + let len_before = self.queue.len(); + self.queue.extend(iter); + if let Err(e) = self.poll_fd.write((self.queue.len() - len_before) as u64) { + log::error!("failed to write ready frames queue poll FD: {:#}", e); + } + } +} + +/// Allows us to manipulate the frames list like an iterator without consuming it and resetting its +/// display order counter. +impl Iterator for ReadyFramesQueue { + type Item = T; + + /// Returns the next frame (if any) waiting to be dequeued. + fn next(&mut self) -> Option { + let next = self.queue.pop_front(); + + if next.is_some() && self.queue.is_empty() { + if let Err(e) = self.poll_fd.read() { + log::error!("failed to read ready frames queue poll FD: {:#}", e); + } + } + + next + } +} + +#[cfg(test)] +mod tests { + use nix::sys::epoll::Epoll; + use nix::sys::epoll::EpollCreateFlags; + use nix::sys::epoll::EpollEvent; + use nix::sys::epoll::EpollFlags; + use nix::sys::epoll::EpollTimeout; + + use super::ReadyFramesQueue; + + #[test] + fn test_ready_frame_queue_poll() { + let mut queue = ReadyFramesQueue::<()>::new().unwrap(); + let epoll = Epoll::new(EpollCreateFlags::empty()).unwrap(); + epoll.add(queue.poll_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1)).unwrap(); + + // Empty queue should not signal. + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 0); + + // Events in the queue should signal. + queue.push(()); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 1); + assert_eq!(events, [EpollEvent::new(EpollFlags::EPOLLIN, 1)]); + + // The queue is empty again and should not signal. + queue.next().unwrap(); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 0); + assert_eq!(events, [EpollEvent::empty()]); + + // Add 3 elements to the queue, it should signal until we remove them all. + queue.extend(std::iter::repeat(()).take(3)); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 1); + assert_eq!(events, [EpollEvent::new(EpollFlags::EPOLLIN, 1)]); + + queue.next().unwrap(); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 1); + assert_eq!(events, [EpollEvent::new(EpollFlags::EPOLLIN, 1)]); + + queue.next().unwrap(); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 1); + assert_eq!(events, [EpollEvent::new(EpollFlags::EPOLLIN, 1)]); + + queue.next().unwrap(); + let mut events = [EpollEvent::empty()]; + let nb_fds = epoll.wait(&mut events, EpollTimeout::ZERO).unwrap(); + assert_eq!(nb_fds, 0); + assert_eq!(events, [EpollEvent::empty()]); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless.rs b/vendor/cros-codecs/src/decoder/stateless.rs new file mode 100644 index 0000000..439ce1b --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless.rs @@ -0,0 +1,495 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Stateless decoders. +//! +//! Stateless here refers to the backend API targeted by these decoders. The decoders themselves do +//! hold the decoding state so the backend doesn't need to. +//! +//! The [`StatelessDecoder`] struct is the basis of all stateless decoders. It is created by +//! combining a codec codec to a [backend](crate::backend), after which bitstream units can be +//! submitted through the [`StatelessDecoder::decode`] method. + +pub mod av1; +pub mod h264; +pub mod h265; +pub mod vp8; +pub mod vp9; + +use std::os::fd::AsFd; +use std::os::fd::AsRawFd; +use std::os::fd::BorrowedFd; +use std::time::Duration; + +use nix::errno::Errno; +use nix::sys::epoll::Epoll; +use nix::sys::epoll::EpollCreateFlags; +use nix::sys::epoll::EpollEvent; +use nix::sys::epoll::EpollFlags; +use nix::sys::eventfd::EventFd; +use thiserror::Error; + +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::decoder::DecoderEvent; +use crate::decoder::DynDecodedHandle; +use crate::decoder::ReadyFramesQueue; +use crate::decoder::StreamInfo; +use crate::Resolution; + +/// Error returned by `new_picture` methods of the backend, usually to indicate which kind of +/// resource is needed before the picture can be successfully created. +#[derive(Error, Debug)] +pub enum NewPictureError { + /// Indicates that the backend needs one output buffer to be returned to the pool before it can + /// proceed. + #[error("need one output buffer to be returned before operation can proceed")] + OutOfOutputBuffers, + /// An unrecoverable backend error has occured. + #[error(transparent)] + BackendError(#[from] anyhow::Error), +} + +pub type NewPictureResult = Result; + +/// Error returned by stateless backend methods. +#[derive(Error, Debug)] +pub enum StatelessBackendError { + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +/// Result type returned by stateless backend methods. +pub type StatelessBackendResult = Result; + +/// Decoder implementations can use this struct to represent their decoding state. +/// +/// `F` is a type containing the parsed stream format, that the decoder will use for format +/// negotiation with the client. +#[derive(Clone, Default)] +enum DecodingState { + /// Decoder will ignore all input until format and resolution information passes by. + #[default] + AwaitingStreamInfo, + /// Decoder is stopped until the client has confirmed the output format. + AwaitingFormat(F), + /// Decoder is currently decoding input. + Decoding, + /// Decoder has been reset after a flush, and can resume with the current parameters after + /// seeing a key frame. + Reset, + // Decoder has recently seen a DRC frame and is flushing and waiting for all frames to be + // output before performing the DRC operation. + FlushingForDRC, +} + +/// Error returned by the [`StatelessVideoDecoder::decode`] method. +#[derive(Debug, Error)] +pub enum DecodeError { + #[error("not enough output buffers available to continue, need {0} more")] + NotEnoughOutputBuffers(usize), + #[error("cannot accept more input until pending events are processed")] + CheckEvents, + #[error("error while parsing frame: {0}")] + ParseFrameError(String), + #[error(transparent)] + DecoderError(#[from] anyhow::Error), + #[error(transparent)] + BackendError(#[from] StatelessBackendError), +} + +/// Convenience conversion for codecs that process a single frame per decode call. +impl From for DecodeError { + fn from(err: NewPictureError) -> Self { + match err { + NewPictureError::OutOfOutputBuffers => DecodeError::NotEnoughOutputBuffers(1), + NewPictureError::BackendError(e) => { + DecodeError::BackendError(StatelessBackendError::Other(e)) + } + } + } +} + +/// Error returned by the [`StatelessVideoDecoder::wait_for_next_event`] method. +#[derive(Debug, Error)] +pub enum WaitNextEventError { + #[error("timed out while waiting for next decoder event")] + TimedOut, +} + +/// Specifies the type of picture that a backend will create for a given codec. +/// +/// The picture type is state that is preserved from the start of a given frame to its submission +/// to the backend. Some codecs don't need it, in this case they can just set `Picture` to `()`. +pub trait StatelessDecoderBackendPicture { + /// Backend-specific type representing a frame being decoded. Useful for decoders that need + /// to render a frame in several steps and to preserve its state in between. + /// + /// Backends that don't use this can simply set it to `()`. + type Picture; +} + +/// Common trait shared by all stateless video decoder backends, providing codec-independent +/// methods. +pub trait StatelessDecoderBackend { + /// The type that the backend returns as a result of a decode operation. + /// This will usually be some backend-specific type with a resource and a + /// resource pool so that said buffer can be reused for another decode + /// operation when it goes out of scope. + type Handle: DecodedHandle; + + /// Returns the current decoding parameters, as parsed from the stream. + fn stream_info(&self) -> Option<&StreamInfo>; + + // Resets the backend decoder to accommodate for a format change event. + fn reset_backend(&mut self) -> anyhow::Result<()>; +} + +/// Stateless video decoder interface. +/// +/// A stateless decoder differs from a stateful one in that its input and output queues are not +/// operating independently: a new decode unit can only be processed if there is already an output +/// resource available to receive its decoded content. +/// +/// Therefore [`decode`] can refuse work if there is no output resource +/// available at the time of calling, in which case the caller is responsible for calling +/// [`decode`] again with the same parameters after processing at least one +/// pending output frame and returning it to the decoder. +/// +/// The `M` generic parameter is the type of the memory descriptor backing the output frames. +/// +/// [`decode`]: StatelessVideoDecoder::decode +pub trait StatelessVideoDecoder { + /// Type of the [`DecodedHandle`]s that decoded frames are returned into. + type Handle: DecodedHandle; + + /// Attempts to decode `bitstream` if the current conditions allow it. + /// + /// This method will return [`DecodeError::CheckEvents`] if processing cannot take place until + /// pending events are handled. This could either be because a change of output format has + /// been detected that the client should acknowledge, or because there are no available output + /// resources and dequeueing and returning pending frames will fix that. After the cause has + /// been addressed, the client is responsible for calling this method again with the same data. + /// + /// The return value is the number of bytes in `bitstream` that have been processed. Usually + /// this will be equal to the length of `bitstream`, but some codecs may only do partial + /// processing if e.g. several units are sent at the same time. It is the responsibility of the + /// caller to check that all submitted input has been processed, and to resubmit the + /// unprocessed part if it hasn't. See the documentation of each codec for their expectations. + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option<::Frame>, + ) -> Result; + + /// Flush the decoder i.e. finish processing all pending decode requests and make sure the + /// resulting frames are ready to be retrieved via [`next_event`]. + /// + /// Note that after flushing, a key frame must be submitted before decoding can resume. + /// + /// [`next_event`]: StatelessVideoDecoder::next_event + fn flush(&mut self) -> Result<(), DecodeError>; + + fn stream_info(&self) -> Option<&StreamInfo>; + + /// Returns the next event, if there is any pending. + fn next_event(&mut self) -> Option>; + + /// Blocks until [`StatelessVideoDecoder::next_event`] is expected to return `Some` or + /// `timeout` has elapsed. + /// + /// Wait for the next event and return it, or return `None` if `timeout` has been reached while + /// waiting. + fn wait_for_next_event(&mut self, timeout: Duration) -> Result<(), WaitNextEventError> { + // Wait until the next event is available. + let mut fd = nix::libc::pollfd { + fd: self.poll_fd().as_raw_fd(), + events: nix::libc::POLLIN, + revents: 0, + }; + // SAFETY: `fd` is a valid reference to a properly-filled `pollfd`. + match unsafe { nix::libc::poll(&mut fd, 1, timeout.as_millis() as i32) } { + 0 => Err(WaitNextEventError::TimedOut), + _ => Ok(()), + } + } + + /// Returns a file descriptor that signals `POLLIN` whenever an event is pending on this + /// decoder. + fn poll_fd(&self) -> BorrowedFd; + + /// Transforms the decoder into a [`StatelessVideoDecoder`] trait object. + /// + /// All decoders going through this method present the same virtual interface when they return. + /// This is useful in order avoid monomorphization of application code that can control + /// decoders using various codecs or backends. + fn into_trait_object(self) -> DynStatelessVideoDecoder<::Frame> + where + Self: Sized + 'static, + Self::Handle: 'static, + { + Box::new(DynStatelessVideoDecoderWrapper(self)) + } +} + +/// Wrapper type for a `StatelessVideoDecoder` that can be turned into a trait object with a common +/// interface. +struct DynStatelessVideoDecoderWrapper(D); + +impl StatelessVideoDecoder for DynStatelessVideoDecoderWrapper +where + D: StatelessVideoDecoder, + ::Handle: 'static, +{ + type Handle = DynDecodedHandle<::Frame>; + + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option<::Frame>, + ) -> Result { + self.0.decode(timestamp, bitstream, alloc_cb) + } + + fn flush(&mut self) -> Result<(), DecodeError> { + self.0.flush() + } + + fn stream_info(&self) -> Option<&StreamInfo> { + self.0.stream_info() + } + + fn next_event(&mut self) -> Option> { + self.0.next_event().map(|e| match e { + DecoderEvent::FrameReady(h) => { + DecoderEvent::FrameReady(Box::new(h) as DynDecodedHandle<_>) + } + DecoderEvent::FormatChanged => DecoderEvent::FormatChanged, + }) + } + + fn poll_fd(&self) -> BorrowedFd { + self.0.poll_fd() + } +} + +pub type DynStatelessVideoDecoder = Box>>; + +pub trait StatelessCodec { + /// Type providing current format information for the codec: resolution, color format, etc. + /// + /// For H.264 this would be the Sps, for VP8 or VP9 the frame header. + type FormatInfo; + /// State that needs to be kept during a decoding operation, typed by backend. + type DecoderState; +} + +/// A struct that serves as a basis to implement a stateless decoder. +/// +/// A stateless decoder is defined by three generic parameters: +/// +/// * A codec, represented by a type that implements [`StatelessCodec`]. This type defines the +/// codec-specific decoder state and other codec properties. +/// * A backend, i.e. an interface to talk to the hardware that accelerates decoding. An example is +/// the VAAPI backend that uses VAAPI for acceleration. The backend will typically itself be typed +/// against a memory decriptor, defining how memory is provided for decoded frames. +/// +/// So for instance, a decoder for the H264 codec, using VAAPI for acceleration with self-managed +/// memory, will have the following type: +/// +/// ```text +/// let decoder: StatelessDecoder>; +/// ``` +/// +/// This struct just manages the high-level decoder state as well as the queue of decoded frames. +/// All the rest is left to codec-specific code. +pub struct StatelessDecoder +where + C: StatelessCodec, + B: StatelessDecoderBackend + StatelessDecoderBackendPicture, +{ + /// The current coded resolution + coded_resolution: Resolution, + + /// Whether the decoder should block on decode operations. + blocking_mode: BlockingMode, + + ready_queue: ReadyFramesQueue, + + decoding_state: DecodingState, + + /// The backend used for hardware acceleration. + backend: B, + + /// Codec-specific state. + codec: C::DecoderState, + + /// Signaled whenever the decoder is in `AwaitingFormat` state. + awaiting_format_event: EventFd, + + /// Union of `awaiting_format_event` and `ready_queue` to signal whenever there is an event + /// (frame ready or format change) pending. + epoll_fd: Epoll, +} + +#[derive(Debug, Error)] +pub enum NewStatelessDecoderError { + #[error("failed to create EventFd for ready frames queue: {0}")] + ReadyFramesQueue(Errno), + #[error("failed to create EventFd for awaiting format event: {0}")] + AwaitingFormatEventFd(Errno), + #[error("failed to create Epoll for decoder: {0}")] + Epoll(Errno), + #[error("failed to add poll FDs to decoder Epoll: {0}")] + EpollAdd(Errno), + #[error("failed to initialize the driver")] + DriverInitialization, +} + +impl StatelessDecoder +where + C: StatelessCodec, + B: StatelessDecoderBackend + StatelessDecoderBackendPicture, + C::DecoderState: Default, +{ + pub fn new(backend: B, blocking_mode: BlockingMode) -> Result { + let ready_queue = + ReadyFramesQueue::new().map_err(NewStatelessDecoderError::ReadyFramesQueue)?; + let awaiting_format_event = + EventFd::new().map_err(NewStatelessDecoderError::AwaitingFormatEventFd)?; + let epoll_fd = + Epoll::new(EpollCreateFlags::empty()).map_err(NewStatelessDecoderError::Epoll)?; + epoll_fd + .add(ready_queue.poll_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1)) + .map_err(NewStatelessDecoderError::EpollAdd)?; + epoll_fd + .add(awaiting_format_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 2)) + .map_err(NewStatelessDecoderError::EpollAdd)?; + + Ok(Self { + backend, + blocking_mode, + coded_resolution: Default::default(), + decoding_state: Default::default(), + ready_queue, + codec: Default::default(), + awaiting_format_event, + epoll_fd, + }) + } + + /// Switch the decoder into `AwaitingFormat` state, making it refuse any input until the + /// `FormatChanged` event is processed. + fn await_format_change(&mut self, format_info: C::FormatInfo) { + self.decoding_state = DecodingState::AwaitingFormat(format_info); + self.awaiting_format_event.write(1).unwrap(); + } + + // If the decoder is in a flushing state, the decoder will wait until the ready_queue is + // empty. Once the ready_queue is empty, the decoder will reset the backend. + fn wait_for_drc_flush(&mut self) -> Result<(), DecodeError> { + if matches!(self.decoding_state, DecodingState::FlushingForDRC) { + if self.ready_queue.queue.is_empty() { + // We can start the DRC operation since the ready queue is empty. + self.backend.reset_backend()?; + self.decoding_state = DecodingState::Reset; + } else { + // Since the ready queue is not empty yet, we can't start the DRC. + // Clear the awaiting format event as we cannot process this yet. + self.awaiting_format_event.read().unwrap(); + return Err(DecodeError::CheckEvents); + } + } + Ok(()) + } + + /// Returns the next pending event, if any, using `on_format_changed` as the format change + /// callback of the [`StatelessDecoderFormatNegotiator`] if there is a resolution change event + /// pending. + fn query_next_event(&mut self, on_format_changed: F) -> Option> + where + Self: StatelessVideoDecoder, + C::FormatInfo: Clone, + F: Fn(&mut Self, &C::FormatInfo) + 'static, + { + // The next event is either the next frame, or, if we are awaiting negotiation, the format + // change event that will allow us to keep going. + self.ready_queue.next().map(DecoderEvent::FrameReady).or_else(|| { + if let DecodingState::AwaitingFormat(format_info) = self.decoding_state.clone() { + on_format_changed(self, &format_info); + self.decoding_state = DecodingState::Reset; + self.awaiting_format_event.read().unwrap(); + Some(DecoderEvent::FormatChanged) + } else { + None + } + }) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use crate::decoder::stateless::StatelessVideoDecoder; + use crate::decoder::DecodedHandle; + + /// Stream that can be used in tests, along with the CRC32 of all of its frames. + pub struct TestStream { + /// Bytestream to decode. + pub stream: &'static [u8], + /// Expected CRC for each frame, one per line. + pub crcs: &'static str, + } + + /// Run the codec-specific `decoding_loop` on a `decoder` with a given `test`, linearly + /// decoding the stream until its end. + /// + /// If `check_crcs` is `true`, then the expected CRCs of the decoded images are compared + /// against the existing result. We may want to set this to false when using a decoder backend + /// that does not produce actual frames. + /// + /// `dump_yuv` will dump all the decoded frames into `/tmp/framexxx.yuv`. Set this to true in + /// order to debug the output of the test. + pub fn test_decode_stream( + decoding_loop: L, + mut decoder: D, + test: &TestStream, + check_crcs: bool, + dump_yuv: bool, + ) where + H: DecodedHandle, + D: StatelessVideoDecoder, + L: Fn(&mut D, &[u8], &mut dyn FnMut(H)) -> anyhow::Result<()>, + { + let mut crcs = test.crcs.lines().enumerate(); + + decoding_loop(&mut decoder, test.stream, &mut |handle| { + let (frame_num, expected_crc) = crcs.next().expect("decoded more frames than expected"); + + if check_crcs || dump_yuv { + handle.sync().unwrap(); + let picture = handle.dyn_picture(); + let mut backend_handle = picture.dyn_mappable_handle().unwrap(); + + let buffer_size = backend_handle.image_size(); + let mut nv12 = vec![0; buffer_size]; + + backend_handle.read(&mut nv12).unwrap(); + + if dump_yuv { + std::fs::write(format!("/tmp/frame{:03}.yuv", frame_num), &nv12).unwrap(); + } + + if check_crcs { + let frame_crc = format!("{:08x}", crc32fast::hash(&nv12)); + assert_eq!(frame_crc, expected_crc, "at frame {}", frame_num); + } + } + }) + .unwrap(); + + assert_eq!(crcs.next(), None, "decoded less frames than expected"); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/av1.rs b/vendor/cros-codecs/src/decoder/stateless/av1.rs new file mode 100644 index 0000000..866ed04 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/av1.rs @@ -0,0 +1,565 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; + +use anyhow::anyhow; + +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::FrameObu; +use crate::codec::av1::parser::FrameType; +use crate::codec::av1::parser::ObuAction; +use crate::codec::av1::parser::ObuType; +use crate::codec::av1::parser::ParsedObu; +use crate::codec::av1::parser::Parser; +use crate::codec::av1::parser::StreamInfo; +use crate::codec::av1::parser::TileGroupObu; +use crate::codec::av1::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DecodingState; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::Resolution; + +#[cfg(test)] +mod dummy; +#[cfg(feature = "v4l2")] +mod v4l2; +#[cfg(feature = "vaapi")] +mod vaapi; + +/// Stateless backend methods specific to AV1. +pub trait StatelessAV1DecoderBackend: + StatelessDecoderBackend + StatelessDecoderBackendPicture +{ + /// Called when a new Sequence Header OBU is parsed. The + /// `highest_spatial_layer` argument refers to the maximum layer selected by + /// the client through `set_operating_point()` and the scalability + /// information present in the stream, if any. + fn change_stream_info(&mut self, stream_info: &StreamInfo) -> StatelessBackendResult<()>; + + /// Called when the decoder determines that a new picture was found. The backend allocates all + /// the resources it needs to process that picture. + fn new_picture( + &mut self, + hdr: &FrameHeaderObu, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult; + + /// Called to set the global parameters of a picture. + fn begin_picture( + &mut self, + picture: &mut Self::Picture, + stream_info: &StreamInfo, + hdr: &FrameHeaderObu, + reference_frames: &[Option; NUM_REF_FRAMES], + ) -> StatelessBackendResult<()>; + + /// Called to dispatch a decode operation to the backend. + #[allow(clippy::too_many_arguments)] + fn decode_tile_group( + &mut self, + picture: &mut Self::Picture, + tile_group: TileGroupObu, + ) -> StatelessBackendResult<()>; + + /// Called when the decoder wants the backend to finish the decoding + /// operations for `picture`. At this point, `decode_tile` has been called + /// for all tiles. + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult; +} + +/// State of the picture being currently decoded. +/// +/// Stored between calls to [`StatelessDecoder::decode_tile_group`] that belong to the same +/// picture. +enum CurrentPicState { + /// A regular frame + RegularFrame { + /// Data for the current picture as extracted from the stream. + header: FrameHeaderObu, + /// Backend-specific data for that picture. + backend_picture: P, + }, + + /// A frame that has 'show_existing_frame' set. + ShowExistingFrame { + /// Data for the current picture as extracted from the stream. + header: FrameHeaderObu, + /// The handle of the reference frame that this frame points to. + handle: H, + }, +} + +pub struct AV1DecoderState { + /// AV1 bitstream parser. + parser: Parser, + + /// The reference frames in use. + reference_frames: [Option; NUM_REF_FRAMES], + + /// Keeps track of the last values seen for negotiation purposes. + stream_info: Option, + + /// The picture currently being decoded. We need to preserve it between + /// calls to `decode` because multiple tiles will be processed in different + /// calls to `decode`. + current_pic: Option>, + + /// Keep track of the number of frames we've processed for logging purposes. + frame_count: u32, + + /// For SVC streams, we only want to output the highest layer possible given + /// the choice of operating point. + highest_spatial_layer: Option, +} + +impl Default for AV1DecoderState +where + H: DecodedHandle, +{ + fn default() -> Self { + Self { + parser: Default::default(), + reference_frames: Default::default(), + stream_info: Default::default(), + current_pic: Default::default(), + frame_count: Default::default(), + highest_spatial_layer: Default::default(), + } + } +} + +/// [`StatelessCodec`] structure to use in order to create a AV1 stateless decoder. +/// +/// # Accepted input +/// +/// the VP9 specification requires the last byte of the chunk to contain the superframe marker. +/// Thus, a decoder using this codec processes exactly one encoded chunk per call to +/// [`StatelessDecoder::decode`], and always returns the size of the passed input if successful. +pub struct Av1; + +impl StatelessCodec for Av1 { + type FormatInfo = StreamInfo; + type DecoderState = AV1DecoderState; +} + +impl StatelessDecoder +where + B: StatelessAV1DecoderBackend, + B::Handle: Clone, +{ + fn decode_frame_header( + &mut self, + frame_header: FrameHeaderObu, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result<(), DecodeError> { + log::debug!("Processing frame {} with timestamp {}", self.codec.frame_count, timestamp); + + if frame_header.show_existing_frame { + let ref_frame = self.codec.reference_frames + [frame_header.frame_to_show_map_idx as usize] + .as_ref() + .ok_or(anyhow!("Broken stream: no reference picture to display"))?; + self.codec.current_pic = Some(CurrentPicState::ShowExistingFrame { + header: frame_header, + handle: ref_frame.clone(), + }); + } else if let Some(stream_info) = &self.codec.stream_info { + let mut backend_picture = + self.backend.new_picture(&frame_header, timestamp, alloc_cb)?; + + self.backend.begin_picture( + &mut backend_picture, + stream_info, + &frame_header, + &self.codec.reference_frames, + )?; + + self.codec.current_pic = Some(CurrentPicState::RegularFrame { + header: frame_header.clone(), + backend_picture, + }); + } else { + log::warn!("invalid stream: frame header received while no valid sequence ongoing"); + } + + Ok(()) + } + + fn decode_tile_group(&mut self, tile_group: TileGroupObu) -> anyhow::Result<()> { + let picture = match self.codec.current_pic.as_mut() { + Some(CurrentPicState::RegularFrame { backend_picture, .. }) => backend_picture, + Some(CurrentPicState::ShowExistingFrame { .. }) => { + return Err(anyhow!("Broken stream: cannot decode a tile group for a frame with show_existing_frame set")); + } + None => { + return Err(anyhow!( + "Broken stream: cannot decode a tile group without first decoding a frame header" + )) + } + }; + + self.backend.decode_tile_group(picture, tile_group)?; + Ok(()) + } + + fn decode_frame( + &mut self, + frame: FrameObu, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result<(), DecodeError> { + let FrameObu { header, tile_group } = frame; + self.decode_frame_header(header, timestamp, alloc_cb)?; + self.decode_tile_group(tile_group)?; + Ok(()) + } + + fn submit_frame(&mut self, timestamp: u64) -> anyhow::Result<()> { + log::debug!("Finishing frame {} with timestamp: {}", self.codec.frame_count, timestamp); + + let picture = self.codec.current_pic.take(); + + let (handle, header) = match picture { + Some(CurrentPicState::RegularFrame { header, backend_picture }) => { + let handle = self.backend.submit_picture(backend_picture)?; + + if self.blocking_mode == BlockingMode::Blocking { + handle.sync()?; + } + (handle, header) + } + Some(CurrentPicState::ShowExistingFrame { header, handle }) => (handle, header), + None => return Err(anyhow!("Broken stream: no picture to submit")), + }; + + let update_refs = if header.show_existing_frame { + header.frame_type == FrameType::KeyFrame + } else { + true + }; + + if update_refs { + let mut refresh_frame_flags = header.refresh_frame_flags; + + #[allow(clippy::needless_range_loop)] + for i in 0..NUM_REF_FRAMES { + if (refresh_frame_flags & 1) == 1 { + log::debug!( + "Replacing reference frame {} to new timestamp {} on frame count: {}", + i, + timestamp, + self.codec.frame_count + ); + self.codec.reference_frames[i] = Some(handle.clone()); + } + + refresh_frame_flags >>= 1; + } + } + + let show_existing_frame = header.show_existing_frame; + if header.show_frame || show_existing_frame { + match self.codec.highest_spatial_layer { + None => self.ready_queue.push(handle), + Some(highest_spatial_layer) => { + if header.obu_header.spatial_id >= highest_spatial_layer { + self.ready_queue.push(handle); + } else { + log::debug!( + "Dropping frame with spatial_id {}", + header.obu_header.spatial_id + ); + } + } + } + } + + self.codec.parser.ref_frame_update(&header).map_err(|err| anyhow!(err))?; + self.codec.frame_count += 1; + Ok(()) + } +} + +impl StatelessVideoDecoder for StatelessDecoder +where + B: StatelessAV1DecoderBackend, + B::Handle: Clone + 'static, +{ + type Handle = B::Handle; + + /// Decode an AV1 stream. + /// + /// `bitstream` should initially be submitted as a whole temporal unit, however a call to this + /// method will only consume a single OBU. The caller must be careful to check the return value + /// and resubmit the remainder if the whole bitstream has not been consumed. + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result { + let obu = match self + .codec + .parser + .read_obu(bitstream) + .map_err(|err| DecodeError::ParseFrameError(err))? + { + ObuAction::Process(obu) => obu, + // This OBU should be dropped. + ObuAction::Drop(length) => return Ok(length as usize), + }; + let obu_length = obu.bytes_used; + + let is_decode_op = matches!( + obu.header.obu_type, + ObuType::Frame | ObuType::FrameHeader | ObuType::TileGroup + ); + + if is_decode_op { + match self.decoding_state { + /* we want to be here */ + DecodingState::Decoding => (), + + /* otherwise... */ + DecodingState::AwaitingStreamInfo => { + /* Skip input until we get information from the stream. */ + return Ok(obu_length); + } + /* Ask the client to confirm the format before we can process this. */ + DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + + DecodingState::Reset => { + let mut parser = self.codec.parser.clone(); + + let is_key_frame = match obu.header.obu_type { + ObuType::Frame | ObuType::FrameHeader => { + let fh = parser + .parse_frame_header_obu(&obu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + fh.frame_type == FrameType::KeyFrame + } + _ => false, + }; + + /* we can only resume from key frames */ + if !is_key_frame { + return Ok(obu_length); + } else { + self.decoding_state = DecodingState::Decoding; + } + } + } + } + + /* We are in `Decoding` state if we reached here */ + + match self.codec.parser.parse_obu(obu).map_err(|err| DecodeError::ParseFrameError(err))? { + ParsedObu::SequenceHeader(sequence) => { + let sequence_differs = match &self.codec.stream_info { + Some(old_stream_info) => *old_stream_info.seq_header != *sequence, + None => true, + }; + + if matches!(self.decoding_state, DecodingState::AwaitingStreamInfo) + || sequence_differs + { + if self.codec.current_pic.is_some() { + return Err(DecodeError::DecoderError(anyhow!( + "broken stream: a picture is being decoded while a new sequence header is encountered" + ))); + } + + /* make sure we sync *before* we clear any state in the backend */ + for f in &mut self.ready_queue.queue { + /* TODO: this fixes av1-1-b8-03-sizeup on Intel + * gen12, but we apparently do not do the same in + * VP9. How is it that we do not get similar crashes there? + * + * TODO: syncing before calling new_sequence() in VP9 may fix some tests + */ + f.sync()?; + } + + log::debug!( + "found new sequence, resolution: {:?}, profile: {:?}, bit depth: {:?}", + Resolution::from(( + sequence.max_frame_width_minus_1 as u32 + 1, + sequence.max_frame_height_minus_1 as u32 + 1 + )), + sequence.seq_profile, + sequence.bit_depth + ); + /* there is nothing to drain, much like vp8 and vp9 */ + self.codec.highest_spatial_layer = self.codec.parser.highest_operating_point(); + + let stream_info = match &self.codec.parser.last_frame_header { + Some(fh) => StreamInfo { + seq_header: sequence.clone(), + render_width: fh.render_width, + render_height: fh.render_height, + }, + None => StreamInfo { + seq_header: sequence.clone(), + render_width: sequence.max_frame_width_minus_1 as u32 + 1, + render_height: sequence.max_frame_height_minus_1 as u32 + 1, + }, + }; + self.backend.change_stream_info(&stream_info)?; + self.await_format_change(stream_info); + } + } + ParsedObu::FrameHeader(frame_header) => { + if self.codec.current_pic.is_some() { + /* submit this frame immediately, as we need to update the + * DPB and the reference info state *before* processing the + * next frame */ + self.submit_frame(timestamp)?; + } + self.decode_frame_header(frame_header, timestamp, alloc_cb)?; + } + ParsedObu::TileGroup(tile_group) => { + self.decode_tile_group(tile_group)?; + } + ParsedObu::Frame(frame) => { + let stream_info = + self.codec.stream_info.as_ref().ok_or(DecodeError::DecoderError(anyhow!( + "broken stream: a picture is being decoded without a sequence header" + )))?; + if stream_info.render_width != frame.header.render_width + || stream_info.render_height != frame.header.render_height + { + let new_stream_info = StreamInfo { + seq_header: stream_info.seq_header.clone(), + render_width: frame.header.render_width, + render_height: frame.header.render_height, + }; + self.backend.change_stream_info(&new_stream_info)?; + } + if self.codec.current_pic.is_some() { + /* submit this frame immediately, as we need to update the + * DPB and the reference info state *before* processing the + * next frame */ + self.submit_frame(timestamp)?; + } + self.decode_frame(frame, timestamp, alloc_cb)?; + /* submit this frame immediately, as we need to update the + * DPB and the reference info state *before* processing the + * next frame */ + self.submit_frame(timestamp)?; + } + ParsedObu::TileList => { + return Err(DecodeError::DecoderError(anyhow!( + "large tile scale mode is not supported" + ))); + } + other => { + log::debug!("skipping OBU of type {:?}", other.obu_type()); + } + } + + /* Submit the last frame if we have reached the end of the temporal unit. */ + if bitstream.len() == obu_length && self.codec.current_pic.is_some() { + self.submit_frame(timestamp)?; + } + + Ok(obu_length) + } + + fn flush(&mut self) -> Result<(), super::DecodeError> { + // Note: all the submitted frames are already in the ready queue. + self.codec.reference_frames = Default::default(); + self.decoding_state = DecodingState::Reset; + + Ok(()) + } + + fn stream_info(&self) -> Option<&crate::decoder::StreamInfo> { + self.backend.stream_info() + } + + fn next_event(&mut self) -> Option> { + self.query_next_event(|decoder, stream_info| { + decoder.codec.stream_info = Some(stream_info.clone()); + }) + } + + fn poll_fd(&self) -> BorrowedFd { + self.epoll_fd.0.as_fd() + } +} + +#[cfg(test)] +pub mod tests { + use crate::bitstream_utils::IvfIterator; + use crate::decoder::stateless::av1::Av1; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. + fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { + let decoder = StatelessDecoder::::new_dummy(blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + IvfIterator::new(s), + f, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + blocking_mode, + ) + }, + decoder, + test, + false, + false, + ); + } + + /// Same as Chromium's test-25fps.av1.ivf + pub const DECODE_TEST_25FPS: TestStream = TestStream { + stream: include_bytes!("../../codec/av1/test_data/test-25fps.ivf.av1"), + crcs: include_str!("../../codec/av1/test_data/test-25fps.ivf.av1.crc"), + }; + + #[test] + fn test_25fps_block() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/av1/dummy.rs b/vendor/cros-codecs/src/decoder/stateless/av1/dummy.rs new file mode 100644 index 0000000..382693d --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/av1/dummy.rs @@ -0,0 +1,69 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backend whose only purpose is to let the decoder +//! run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::dummy::decoder::Backend; +use crate::backend::dummy::decoder::Handle; + +use crate::decoder::stateless::av1::Av1; +use crate::decoder::stateless::av1::StatelessAV1DecoderBackend; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::BlockingMode; + +impl StatelessAV1DecoderBackend for Backend { + fn new_sequence( + &mut self, + _: &std::rc::Rc, + _: Option, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn new_picture( + &mut self, + _: &crate::codec::av1::parser::FrameHeaderObu, + _: u64, + _: Option, + ) -> crate::decoder::stateless::NewPictureResult { + Ok(()) + } + + fn begin_picture( + &mut self, + _: &mut Self::Picture, + _: &crate::codec::av1::parser::SequenceHeaderObu, + _: &crate::codec::av1::parser::FrameHeaderObu, + _: &[Option; crate::codec::av1::parser::NUM_REF_FRAMES], + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn decode_tile_group( + &mut self, + _: &mut Self::Picture, + _: crate::codec::av1::parser::TileGroupObu, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn submit_picture( + &mut self, + _: Self::Picture, + ) -> crate::decoder::stateless::StatelessBackendResult { + Ok(Handle { handle: Rc::new(RefCell::new(Default::default())) }) + } +} + +impl StatelessDecoder { + // Creates a new instance of the decoder using the dummy backend. + pub fn new_dummy(blocking_mode: BlockingMode) -> Result { + Self::new(Backend::new(), blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/av1/v4l2.rs b/vendor/cros-codecs/src/decoder/stateless/av1/v4l2.rs new file mode 100644 index 0000000..c4b75c4 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/av1/v4l2.rs @@ -0,0 +1,169 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::rc::Rc; + +use v4l2r::ioctl; + +use crate::backend::v4l2::decoder::stateless::V4l2Picture; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderBackend; +use crate::backend::v4l2::decoder::V4l2StreamInfo; +use crate::backend::v4l2::decoder::ADDITIONAL_REFERENCE_FRAME_BUFFER; +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::StreamInfo; +use crate::codec::av1::parser::TileGroupObu; +use crate::codec::av1::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::av1::Av1; +use crate::decoder::stateless::av1::StatelessAV1DecoderBackend; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::device::v4l2::stateless::controls::av1::Av1V4l2FilmGrainCtrl; +use crate::device::v4l2::stateless::controls::av1::Av1V4l2FrameCtrl; +use crate::device::v4l2::stateless::controls::av1::Av1V4l2SequenceCtrl; +use crate::device::v4l2::stateless::controls::av1::Av1V4l2TileGroupEntryCtrl; +use crate::device::v4l2::stateless::controls::av1::V4l2CtrlAv1FilmGrainParams; +use crate::device::v4l2::stateless::controls::av1::V4l2CtrlAv1FrameParams; +use crate::device::v4l2::stateless::controls::av1::V4l2CtrlAv1SequenceParams; +use crate::device::v4l2::stateless::controls::av1::V4l2CtrlAv1TileGroupEntryParams; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Rect; +use crate::Resolution; + +impl V4l2StreamInfo for &StreamInfo { + fn min_num_frames(&self) -> usize { + NUM_REF_FRAMES + ADDITIONAL_REFERENCE_FRAME_BUFFER + } + + fn coded_size(&self) -> Resolution { + Resolution::from(( + self.seq_header.max_frame_width_minus_1 as u32 + 1, + self.seq_header.max_frame_height_minus_1 as u32 + 1, + )) + } + + fn visible_rect(&self) -> Rect { + Rect::from(((0, 0), (self.render_width, self.render_height))) + } +} + +impl StatelessDecoderBackendPicture for V4l2StatelessDecoderBackend { + type Picture = Rc>>; +} + +impl StatelessAV1DecoderBackend for V4l2StatelessDecoderBackend { + fn change_stream_info(&mut self, stream_info: &StreamInfo) -> StatelessBackendResult<()> { + self.new_sequence(stream_info, Fourcc::from(b"AV1F")) + } + + fn new_picture( + &mut self, + _hdr: &FrameHeaderObu, + _timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option, + ) -> NewPictureResult { + let timestamp = self.frame_counter; + let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?; + let request_buffer = match self.device.alloc_request(timestamp, frame) { + Ok(buffer) => buffer, + _ => return Err(NewPictureError::OutOfOutputBuffers), + }; + let picture = Rc::new(RefCell::new(V4l2Picture::new(request_buffer.clone()))); + request_buffer + .as_ref() + .borrow_mut() + .set_picture_ref(Rc::>>::downgrade(&picture)); + + self.frame_counter = self.frame_counter + 1; + Ok(picture) + } + + fn begin_picture( + &mut self, + picture: &mut Self::Picture, + stream_info: &StreamInfo, + hdr: &FrameHeaderObu, + _reference_frames: &[Option; NUM_REF_FRAMES], + ) -> StatelessBackendResult<()> { + let mut picture = picture.borrow_mut(); + let request = picture.request(); + let request = request.as_ref().borrow_mut(); + + if hdr.film_grain_params.apply_grain { + let mut film_grain_params = V4l2CtrlAv1FilmGrainParams::new(); + film_grain_params.set_film_grain_params(&hdr); + + let mut film_grain_params_ctrl = Av1V4l2FilmGrainCtrl::from(&film_grain_params); + let which = request.which(); + ioctl::s_ext_ctrls(&self.device, which, &mut film_grain_params_ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + } + + let mut frame_params = V4l2CtrlAv1FrameParams::new(); + frame_params + .set_frame_params(&hdr) + .set_global_motion_params(&hdr.global_motion_params) + .set_loop_restoration_params(&hdr.loop_restoration_params) + .set_cdef_params(&hdr.cdef_params) + .set_loop_filter_params(&hdr.loop_filter_params) + .set_segmentation_params(&hdr.segmentation_params) + .set_quantization_params(&hdr.quantization_params) + .set_tile_info_params(&hdr); + + let mut frame_params_ctrl = Av1V4l2FrameCtrl::from(&frame_params); + let which = request.which(); + ioctl::s_ext_ctrls(&self.device, which, &mut frame_params_ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + + let mut sequence_params = V4l2CtrlAv1SequenceParams::new(); + sequence_params.set_ctrl_sequence(&stream_info.seq_header); + + let mut sequence_params_ctrl = Av1V4l2SequenceCtrl::from(&sequence_params); + let which = request.which(); + ioctl::s_ext_ctrls(&self.device, which, &mut sequence_params_ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + + todo!() + } + + fn decode_tile_group( + &mut self, + picture: &mut Self::Picture, + tile_group: TileGroupObu, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + let mut tile_group_params = V4l2CtrlAv1TileGroupEntryParams::new(); + + for tile in &tile_group.tiles { + tile_group_params.set_tile_group_entry(&tile); + } + + let mut picture = picture.borrow_mut(); + let request = picture.request(); + let request = request.as_ref().borrow_mut(); + + let mut tile_group_params_ctrl = Av1V4l2TileGroupEntryCtrl::from(&tile_group_params); + let which = request.which(); + ioctl::s_ext_ctrls(&self.device, which, &mut tile_group_params_ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + + todo!() + } + + fn submit_picture(&mut self, _picture: Self::Picture) -> StatelessBackendResult { + todo!() + } +} + +impl StatelessDecoder> { + pub fn new_v4l2(blocking_mode: BlockingMode) -> Result { + Self::new(V4l2StatelessDecoderBackend::new()?, blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs new file mode 100644 index 0000000..cc06ca2 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs @@ -0,0 +1,625 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; +use libva::Display; + +use crate::backend::vaapi::decoder::va_surface_id; +use crate::backend::vaapi::decoder::DecodedHandle as VADecodedHandle; +use crate::backend::vaapi::decoder::VaStreamInfo; +use crate::backend::vaapi::decoder::VaapiBackend; +use crate::backend::vaapi::decoder::VaapiPicture; +use crate::codec::av1::parser::BitDepth; +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::Profile; +use crate::codec::av1::parser::StreamInfo; +use crate::codec::av1::parser::TileGroupObu; +use crate::codec::av1::parser::WarpModelType; +use crate::codec::av1::parser::MAX_SEGMENTS; +use crate::codec::av1::parser::MAX_TILE_COLS; +use crate::codec::av1::parser::MAX_TILE_ROWS; +use crate::codec::av1::parser::NUM_REF_FRAMES; +use crate::codec::av1::parser::SEG_LVL_MAX; +use crate::decoder::stateless::av1::Av1; +use crate::decoder::stateless::av1::StatelessAV1DecoderBackend; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::video_frame::VideoFrame; +use crate::Rect; +use crate::Resolution; + +/// The number of surfaces to allocate for this codec. +const NUM_SURFACES: usize = 16; + +impl VaStreamInfo for &StreamInfo { + fn va_profile(&self) -> anyhow::Result { + match self.seq_header.seq_profile { + Profile::Profile0 => Ok(libva::VAProfile::VAProfileAV1Profile0), + Profile::Profile1 => Ok(libva::VAProfile::VAProfileAV1Profile1), + Profile::Profile2 => { + Err(anyhow!("Profile {:?} is not supported by VAAPI", self.seq_header.seq_profile)) + } + } + } + + fn rt_format(&self) -> anyhow::Result { + // See table 6.4.1. + match self.seq_header.seq_profile { + Profile::Profile0 => { + if self.seq_header.bit_depth == BitDepth::Depth8 { + Ok(libva::VA_RT_FORMAT_YUV420) + } else if self.seq_header.bit_depth == BitDepth::Depth10 { + Ok(libva::VA_RT_FORMAT_YUV420_10) + } else { + Err(anyhow!( + "Unsupported bit depth {:?} for profile {:?}", + self.seq_header.bit_depth, + self.seq_header.seq_profile + )) + } + } + Profile::Profile1 => { + if self.seq_header.bit_depth == BitDepth::Depth8 { + Ok(libva::VA_RT_FORMAT_YUV444) + } else if self.seq_header.bit_depth == BitDepth::Depth10 { + Ok(libva::VA_RT_FORMAT_YUV444_10) + } else { + Err(anyhow!( + "Unsupported bit depth {:?} for profile {:?}", + self.seq_header.bit_depth, + self.seq_header.seq_profile + )) + } + } + Profile::Profile2 => { + Err(anyhow!("Profile {:?} is not supported by VAAPI", self.seq_header.seq_profile)) + } + } + } + + fn min_num_surfaces(&self) -> usize { + NUM_SURFACES + } + + fn coded_size(&self) -> Resolution { + Resolution::from(( + self.seq_header.max_frame_width_minus_1 as u32 + 1, + self.seq_header.max_frame_height_minus_1 as u32 + 1, + )) + } + + fn visible_rect(&self) -> Rect { + Rect::from(((0, 0), (self.render_width, self.render_height))) + } +} + +impl From<&FrameHeaderObu> for libva::AV1FilmGrain { + fn from(hdr: &FrameHeaderObu) -> Self { + let fg = &hdr.film_grain_params; + + if fg.apply_grain { + log::warn!("Film grain is not officially supported yet.") + } + + let film_grain_fields = libva::AV1FilmGrainFields::new( + u32::from(fg.apply_grain), + u32::from(fg.chroma_scaling_from_luma), + u32::from(fg.grain_scaling_minus_8), + fg.ar_coeff_lag, + fg.ar_coeff_shift_minus_6 as u32, + fg.grain_scale_shift as u32, + u32::from(fg.overlap_flag), + u32::from(fg.clip_to_restricted_range), + ); + + const NUM_POINT_Y: usize = 14; + let fg_point_y_value = { + let mut fg_point_y_value = [0u8; NUM_POINT_Y]; + fg_point_y_value.copy_from_slice(&fg.point_y_value[0..NUM_POINT_Y]); + fg_point_y_value + }; + let fg_point_y_scaling = { + let mut fg_point_y_scaling = [0u8; NUM_POINT_Y]; + fg_point_y_scaling.copy_from_slice(&fg.point_y_scaling[0..NUM_POINT_Y]); + fg_point_y_scaling + }; + + const NUM_POINT_CB: usize = 10; + let fg_point_cb_value = { + let mut fg_point_cb_value = [0u8; NUM_POINT_CB]; + fg_point_cb_value.copy_from_slice(&fg.point_cb_value[0..NUM_POINT_CB]); + fg_point_cb_value + }; + let fg_point_cb_scaling = { + let mut fg_point_cb_scaling = [0u8; NUM_POINT_CB]; + fg_point_cb_scaling.copy_from_slice(&fg.point_cb_scaling[0..NUM_POINT_CB]); + fg_point_cb_scaling + }; + + const NUM_POINT_CR: usize = 10; + let fg_point_cr_value = { + let mut fg_point_cr_value = [0u8; NUM_POINT_CR]; + fg_point_cr_value.copy_from_slice(&fg.point_cr_value[0..NUM_POINT_CR]); + fg_point_cr_value + }; + let fg_point_cr_scaling = { + let mut fg_point_cr_scaling = [0u8; NUM_POINT_CR]; + fg_point_cr_scaling.copy_from_slice(&fg.point_cr_scaling[0..NUM_POINT_CR]); + fg_point_cr_scaling + }; + + let fg_ar_coeffs_y = { + let mut fg_ar_coeffs_y = [0i8; 24]; + fg_ar_coeffs_y + .iter_mut() + .zip(fg.ar_coeffs_y_plus_128.iter().copied()) + .for_each(|(dest, src)| *dest = ((src as i16) - 128) as i8); + fg_ar_coeffs_y + }; + let fg_ar_coeffs_cb = { + let mut fg_ar_coeffs_cb = [0i8; 25]; + fg_ar_coeffs_cb + .iter_mut() + .zip(fg.ar_coeffs_cb_plus_128.iter().copied()) + .for_each(|(dest, src)| *dest = ((src as i16) - 128) as i8); + fg_ar_coeffs_cb + }; + let fg_ar_coeffs_cr = { + let mut fg_ar_coeffs_cr = [0i8; 25]; + fg_ar_coeffs_cr + .iter_mut() + .zip(fg.ar_coeffs_cr_plus_128.iter().copied()) + .for_each(|(dest, src)| *dest = ((src as i16) - 128) as i8); + fg_ar_coeffs_cr + }; + + libva::AV1FilmGrain::new( + &film_grain_fields, + fg.grain_seed, + fg.num_y_points, + fg_point_y_value, + fg_point_y_scaling, + fg.num_cb_points, + fg_point_cb_value, + fg_point_cb_scaling, + fg.num_cr_points, + fg_point_cr_value, + fg_point_cr_scaling, + fg_ar_coeffs_y, + fg_ar_coeffs_cb, + fg_ar_coeffs_cr, + fg.cb_mult, + fg.cb_luma_mult, + fg.cb_offset, + fg.cr_mult, + fg.cr_luma_mult, + fg.cr_offset, + ) + } +} + +fn build_wm_info(hdr: &FrameHeaderObu) -> [libva::AV1WarpedMotionParams; 7] { + let mut wm = vec![]; + let gm = &hdr.global_motion_params; + for i in 1..=7 { + let wm_type = match gm.gm_type[i] { + /* TODO: these were not exported in cros-libva */ + WarpModelType::Identity => 0, + WarpModelType::Translation => 1, + WarpModelType::RotZoom => 2, + WarpModelType::Affine => 3, + }; + + let params = { + let mut params = [0; 8]; + params[0..6].copy_from_slice(&gm.gm_params[i][0..6]); + params + }; + + wm.push(libva::AV1WarpedMotionParams::new(wm_type, params, u8::from(!gm.warp_valid[i]))); + } + + match wm.try_into() { + Ok(wm) => wm, + Err(_) => unreachable!("The Vec should have the right size"), + } +} + +fn build_pic_param( + hdr: &FrameHeaderObu, + stream_info: &StreamInfo, + current_frame: libva::VASurfaceID, + reference_frames: &[Option>; NUM_REF_FRAMES], +) -> anyhow::Result { + let seq = stream_info.seq_header.clone(); + + let seq_info_fields = libva::AV1SeqFields::new( + u32::from(seq.still_picture), + u32::from(seq.use_128x128_superblock), + u32::from(seq.enable_filter_intra), + u32::from(seq.enable_intra_edge_filter), + u32::from(seq.enable_interintra_compound), + u32::from(seq.enable_masked_compound), + u32::from(seq.enable_dual_filter), + u32::from(seq.enable_order_hint), + u32::from(seq.enable_jnt_comp), + u32::from(seq.enable_cdef), + u32::from(seq.color_config.mono_chrome), + u32::from(seq.color_config.color_range), + u32::from(seq.color_config.subsampling_x), + u32::from(seq.color_config.subsampling_y), + seq.color_config.chroma_sample_position as u32, + u32::from(seq.film_grain_params_present), + ); + + let seg = &hdr.segmentation_params; + let seg_info_fields = libva::AV1SegmentInfoFields::new( + u32::from(seg.segmentation_enabled), + u32::from(seg.segmentation_update_map), + u32::from(seg.segmentation_temporal_update), + u32::from(seg.segmentation_update_data), + ); + + let seg_feature_mask = { + let mut seg_feature_mask = [0u8; MAX_SEGMENTS]; + #[allow(clippy::needless_range_loop)] + for i in 0..MAX_SEGMENTS { + let mut mask = 0; + for j in 0..SEG_LVL_MAX { + if seg.feature_enabled[i][j] { + mask |= 1 << j; + } + } + seg_feature_mask[i] = mask; + } + seg_feature_mask + }; + + let seg_info = + libva::AV1Segmentation::new(&seg_info_fields, seg.feature_data, seg_feature_mask); + + let pic_info_fields = libva::AV1PicInfoFields::new( + hdr.frame_type as u32, + u32::from(hdr.show_frame), + u32::from(hdr.showable_frame), + u32::from(hdr.error_resilient_mode), + u32::from(hdr.disable_cdf_update), + hdr.allow_screen_content_tools, + hdr.force_integer_mv, + u32::from(hdr.allow_intrabc), + u32::from(hdr.use_superres), + u32::from(hdr.allow_high_precision_mv), + u32::from(hdr.is_motion_mode_switchable), + u32::from(hdr.use_ref_frame_mvs), + u32::from(hdr.disable_frame_end_update_cdf), + u32::from(hdr.tile_info.uniform_tile_spacing_flag), + u32::from(hdr.allow_warped_motion), + 0, /* large_scale_tile */ + ); + + let bit_depth_idx = match seq.bit_depth { + BitDepth::Depth8 => 0, + BitDepth::Depth10 => 1, + BitDepth::Depth12 => 2, + }; + + let ref_frame_map: [libva::VASurfaceID; NUM_REF_FRAMES] = + reference_frames.iter().map(va_surface_id).collect::>().try_into().unwrap(); + + let width_in_sbs_minus_1 = { + let mut width_in_sbs_minus_1 = [0; MAX_TILE_COLS - 1]; + #[allow(clippy::needless_range_loop)] + for i in 0..width_in_sbs_minus_1.len() { + width_in_sbs_minus_1[i] = u16::try_from(hdr.tile_info.width_in_sbs_minus_1[i]) + .context("Invalid width_in_sbs_minus_1")?; + } + width_in_sbs_minus_1 + }; + + let height_in_sbs_minus_1 = { + let mut height_in_sbs_minus_1 = [0; MAX_TILE_ROWS - 1]; + #[allow(clippy::needless_range_loop)] + for i in 0..height_in_sbs_minus_1.len() { + height_in_sbs_minus_1[i] = u16::try_from(hdr.tile_info.height_in_sbs_minus_1[i]) + .context("Invalid height_in_sbs_minus_1")?; + } + height_in_sbs_minus_1 + }; + + let lf = &hdr.loop_filter_params; + let filter_level = [lf.loop_filter_level[0], lf.loop_filter_level[1]]; + + let lf_fields = libva::AV1LoopFilterFields::new( + lf.loop_filter_sharpness, + u8::from(lf.loop_filter_delta_enabled), + u8::from(lf.loop_filter_delta_update), + ); + + let quant = &hdr.quantization_params; + let qmatrix_fields = libva::AV1QMatrixFields::new( + u16::from(quant.using_qmatrix), + u16::try_from(quant.qm_y).context("Invalid qm_y")?, + u16::try_from(quant.qm_u).context("Invalid qm_u")?, + u16::try_from(quant.qm_v).context("Invalid qm_v")?, + ); + + let mode_control_fields = libva::AV1ModeControlFields::new( + u32::from(quant.delta_q_present), + quant.delta_q_res, + u32::from(lf.delta_lf_present), + lf.delta_lf_res as u32, + lf.delta_lf_multi as u32, + hdr.tx_mode as u32, + u32::from(hdr.reference_select), + u32::from(hdr.reduced_tx_set), + u32::from(hdr.skip_mode_present), + ); + + let cdef = &hdr.cdef_params; + let (cdef_y_strengths, cdef_uv_strengths) = { + let num_cdef_strenghts = 1 << cdef.cdef_bits; + let mut cdef_y_strengths = [0; 8]; + let mut cdef_uv_strengths = [0; 8]; + + #[allow(clippy::needless_range_loop)] + for i in 0..num_cdef_strenghts { + let mut sec_strength = cdef.cdef_y_sec_strength[i]; + if sec_strength == 4 { + sec_strength -= 1; + } + cdef_y_strengths[i] = + u8::try_from(((cdef.cdef_y_pri_strength[i] & 0xf) << 2) | (sec_strength & 0x3)) + .context("Failed to merge primary and secondary strengths")?; + } + + #[allow(clippy::needless_range_loop)] + for i in 0..num_cdef_strenghts { + let mut sec_strength = cdef.cdef_uv_sec_strength[i]; + if sec_strength == 4 { + sec_strength -= 1; + } + cdef_uv_strengths[i] = + u8::try_from(((cdef.cdef_uv_pri_strength[i] & 0xf) << 2) | (sec_strength & 0x3)) + .context("Failed to merge primary and secondary strengths")?; + } + + (cdef_y_strengths, cdef_uv_strengths) + }; + + let lr = &hdr.loop_restoration_params; + let loop_restoration_fields = libva::AV1LoopRestorationFields::new( + lr.frame_restoration_type[0] as u16, + lr.frame_restoration_type[1] as u16, + lr.frame_restoration_type[2] as u16, + u16::from(lr.lr_unit_shift), + u16::from(lr.lr_uv_shift), + ); + + let wm = build_wm_info(hdr); + + let pic_param = libva::PictureParameterBufferAV1::new( + u8::try_from(seq.seq_profile as u32).context("Invalid profile")?, + u8::try_from(seq.order_hint_bits_minus_1).context("Invalid order hint bits")?, + bit_depth_idx, + u8::try_from(seq.color_config.matrix_coefficients as u32) + .context("Invalid matrix_coefficients")?, + &seq_info_fields, + current_frame, + libva::VA_INVALID_SURFACE, /* film grain is unsupported for now */ + vec![], /* anchor_frames_list */ + u16::try_from(hdr.upscaled_width - 1).context("Invalid frame width")?, + u16::try_from(hdr.frame_height - 1).context("Invalid frame height")?, + 0, /* output_frame_width_in_tiles_minus_1 */ + 0, /* output_frame_height_in_tiles_minus_1 */ + ref_frame_map, + hdr.ref_frame_idx, + u8::try_from(hdr.primary_ref_frame).context("Invalid primary_ref_frame")?, + u8::try_from(hdr.order_hint).context("Invalid order_hint")?, + &seg_info, + &libva::AV1FilmGrain::from(hdr), + u8::try_from(hdr.tile_info.tile_cols).context("Invalid tile_cols")?, + u8::try_from(hdr.tile_info.tile_rows).context("Invalid tile_rows")?, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + 0, /* large-scale tile not supported */ + u16::try_from(hdr.tile_info.context_update_tile_id) + .context("Invalid context_update_tile_id")?, + &pic_info_fields, + u8::try_from(hdr.superres_denom).context("Invalid superres_denom")?, + u8::try_from(hdr.interpolation_filter as u32).context("Invalid interpolation_filter")?, + filter_level, + lf.loop_filter_level[2], + lf.loop_filter_level[3], + &lf_fields, + lf.loop_filter_ref_deltas, + lf.loop_filter_mode_deltas, + u8::try_from(quant.base_q_idx).context("Invalid base_q_idx")?, + i8::try_from(quant.delta_q_y_dc).context("Invalid delta_q_y_dc")?, + i8::try_from(quant.delta_q_u_dc).context("Invalid delta_q_u_dc")?, + i8::try_from(quant.delta_q_u_ac).context("Invalid delta_q_u_ac")?, + i8::try_from(quant.delta_q_v_dc).context("Invalid delta_q_v_dc")?, + i8::try_from(quant.delta_q_v_ac).context("Invalid delta_q_v_ac")?, + &qmatrix_fields, + &mode_control_fields, + u8::try_from(hdr.cdef_params.cdef_damping - 3).context("Invalid cdef_damping")?, + u8::try_from(hdr.cdef_params.cdef_bits).context("Invalid cdef_bits")?, + cdef_y_strengths, + cdef_uv_strengths, + &loop_restoration_fields, + &wm, + ); + + Ok(libva::BufferType::PictureParameter(libva::PictureParameter::AV1(pic_param))) +} + +fn build_slice_params_for_tg(tg: &TileGroupObu) -> anyhow::Result { + let mut slice_params = libva::SliceParameterBufferAV1::new(); + + for tile in &tg.tiles { + /* all tiles must be submitted in the same slice parameter array */ + slice_params.add_slice_parameter( + tile.tile_size, + tile.tile_offset, + 0, + u16::try_from(tile.tile_row).context("Invalid tile_row")?, + u16::try_from(tile.tile_col).context("Invalid tile_col")?, + u16::try_from(tg.tg_start).context("Invalid tg_start")?, + u16::try_from(tg.tg_end).context("Invalid tg_end")?, + 0, + 0, + ); + } + + Ok(libva::BufferType::SliceParameter(libva::SliceParameter::AV1(slice_params))) +} + +fn build_slice_data_for_tg(tg: TileGroupObu) -> libva::BufferType { + let TileGroupObu { obu, .. } = tg; + libva::BufferType::SliceData(Vec::from(obu.as_ref())) +} + +impl StatelessDecoderBackendPicture for VaapiBackend { + type Picture = VaapiPicture; +} + +impl StatelessAV1DecoderBackend for VaapiBackend { + fn change_stream_info(&mut self, stream_info: &StreamInfo) -> StatelessBackendResult<()> { + self.new_sequence(stream_info) + } + + fn new_picture( + &mut self, + _hdr: &FrameHeaderObu, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option, + ) -> NewPictureResult { + Ok(VaapiPicture::new( + timestamp, + Rc::clone(&self.context), + alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, + )) + } + + fn begin_picture( + &mut self, + picture: &mut Self::Picture, + stream_info: &StreamInfo, + hdr: &FrameHeaderObu, + reference_frames: &[Option; NUM_REF_FRAMES], + ) -> StatelessBackendResult<()> { + let pic_param = build_pic_param(hdr, stream_info, picture.surface().id(), reference_frames) + .context("Failed to build picture parameter")?; + let pic_param = self + .context + .create_buffer(pic_param) + .context("Failed to create picture parameter buffer")?; + picture.add_buffer(pic_param); + + Ok(()) + } + + fn decode_tile_group( + &mut self, + picture: &mut Self::Picture, + tile_group: TileGroupObu, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + let slice_params = build_slice_params_for_tg(&tile_group)?; + let slice_data = build_slice_data_for_tg(tile_group); + + let context = &self.context; + + let buffer = context + .create_buffer(slice_params) + .context("Failed to create slice parameter buffer")?; + + picture.add_buffer(buffer); + + let buffer = + context.create_buffer(slice_data).context("Failed to create slice data buffer")?; + + picture.add_buffer(buffer); + + Ok(()) + } + + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult { + self.process_picture::(picture) + } +} + +impl StatelessDecoder> { + // Creates a new instance of the decoder using the VAAPI backend. + pub fn new_vaapi( + display: Rc, + blocking_mode: BlockingMode, + ) -> Result { + Self::new(VaapiBackend::new(display, true), blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::Display; + + use crate::bitstream_utils::IvfIterator; + use crate::decoder::stateless::av1::Av1; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the vaapi decoder, in both blocking and non-blocking modes. + fn test_decoder_vaapi( + test: &TestStream, + output_format: DecodedFormat, + blocking_mode: BlockingMode, + ) { + let display = Display::open().unwrap(); + let decoder = StatelessDecoder::::new_vaapi::<()>(display, blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + IvfIterator::new(s), + f, + &mut simple_playback_loop_owned_frames, + output_format, + blocking_mode, + ) + }, + decoder, + test, + true, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_av1_blocking() { + use crate::decoder::stateless::av1::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::Blocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_av1_non_blocking() { + use crate::decoder::stateless::av1::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::NonBlocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h264.rs b/vendor/cros-codecs/src/decoder/stateless/h264.rs new file mode 100644 index 0000000..baa3fbf --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h264.rs @@ -0,0 +1,1501 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(any(test, fuzzing))] +mod dummy; +#[cfg(feature = "v4l2")] +mod v4l2; +#[cfg(feature = "vaapi")] +mod vaapi; + +use std::collections::btree_map::Entry; +use std::io::Cursor; +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; +use log::debug; +use thiserror::Error; + +use crate::codec::h264::dpb::Dpb; +use crate::codec::h264::dpb::DpbEntry; +use crate::codec::h264::dpb::DpbPicRefList; +use crate::codec::h264::dpb::MmcoError; +use crate::codec::h264::dpb::ReferencePicLists; +use crate::codec::h264::parser::MaxLongTermFrameIdx; +use crate::codec::h264::parser::Nalu; +use crate::codec::h264::parser::NaluType; +use crate::codec::h264::parser::Parser; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::RefPicListModification; +use crate::codec::h264::parser::Slice; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::SliceType; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::Field; +use crate::codec::h264::picture::FieldRank; +use crate::codec::h264::picture::IsIdr; +use crate::codec::h264::picture::PictureData; +use crate::codec::h264::picture::RcPictureData; +use crate::codec::h264::picture::Reference; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DecodingState; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::decoder::DecoderEvent; +use crate::decoder::StreamInfo; +use crate::Resolution; + +pub fn get_raster_from_zigzag_8x8(src: [u8; 64], dst: &mut [u8; 64]) { + const ZIGZAG_8X8: [usize; 64] = [ + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, + ]; + + for i in 0..64 { + dst[ZIGZAG_8X8[i]] = src[i]; + } +} + +pub fn get_raster_from_zigzag_4x4(src: [u8; 16], dst: &mut [u8; 16]) { + const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + + for i in 0..16 { + dst[ZIGZAG_4X4[i]] = src[i]; + } +} + +/// Stateless backend methods specific to H.264. +pub trait StatelessH264DecoderBackend: + StatelessDecoderBackend + StatelessDecoderBackendPicture +{ + /// Called when a new SPS is parsed. + fn new_sequence(&mut self, sps: &Rc) -> StatelessBackendResult<()>; + + /// Called when the decoder determines that a frame or field was found. + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult; + + /// Called when the decoder determines that a second field was found. + /// Indicates that the underlying BackendHandle is to be shared between the + /// two pictures. This is so both fields decode to the same underlying + /// resource and can thus be presented together as a single frame. + fn new_field_picture( + &mut self, + timestamp: u64, + first_field: &Self::Handle, + ) -> NewPictureResult; + + /// Called by the decoder when starting a new frame or field. + fn start_picture( + &mut self, + picture: &mut Self::Picture, + picture_data: &PictureData, + sps: &Sps, + pps: &Pps, + dpb: &Dpb, + hdr: &SliceHeader, + ) -> StatelessBackendResult<()>; + + /// Called to dispatch a decode operation to the backend. + #[allow(clippy::too_many_arguments)] + fn decode_slice( + &mut self, + picture: &mut Self::Picture, + slice: &Slice, + sps: &Sps, + pps: &Pps, + ref_pic_list0: &[&DpbEntry], + ref_pic_list1: &[&DpbEntry], + ) -> StatelessBackendResult<()>; + + /// Called when the decoder wants the backend to finish the decoding + /// operations for `picture`. At this point, `decode_slice` has been called + /// for all slices. + /// + /// This call will assign the ownership of the BackendHandle to the Picture + /// and then assign the ownership of the Picture to the Handle. + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult; +} + +/// Keeps track of the last values seen for negotiation purposes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct NegotiationInfo { + /// The current coded resolution + coded_resolution: Resolution, + /// Same meaning as the specification. + profile_idc: u8, + /// Same meaning as the specification. + bit_depth_luma_minus8: u8, + /// Same meaning as the specification. + bit_depth_chroma_minus8: u8, + /// Same meaning as the specification. + chroma_format_idc: u8, + /// The maximum size of the dpb in frames. + max_dpb_frames: usize, + /// Whether this is an interlaced stream + interlaced: bool, +} + +impl From<&Sps> for NegotiationInfo { + fn from(sps: &Sps) -> Self { + NegotiationInfo { + coded_resolution: Resolution::from((sps.width(), sps.height())), + profile_idc: sps.profile_idc, + bit_depth_luma_minus8: sps.bit_depth_luma_minus8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8, + chroma_format_idc: sps.chroma_format_idc, + max_dpb_frames: sps.max_dpb_frames(), + interlaced: !sps.frame_mbs_only_flag, + } + } +} + +#[derive(Copy, Clone, Debug)] +enum RefPicList { + RefPicList0, + RefPicList1, +} + +pub struct PrevReferencePicInfo { + frame_num: u32, + has_mmco_5: bool, + top_field_order_cnt: i32, + pic_order_cnt_msb: i32, + pic_order_cnt_lsb: i32, + field: Field, +} + +impl Default for PrevReferencePicInfo { + fn default() -> Self { + Self { + frame_num: Default::default(), + has_mmco_5: Default::default(), + top_field_order_cnt: Default::default(), + pic_order_cnt_msb: Default::default(), + pic_order_cnt_lsb: Default::default(), + field: Field::Frame, + } + } +} + +impl PrevReferencePicInfo { + /// Store some variables related to the previous reference picture. These + /// will be used in the decoding of future pictures. + fn fill(&mut self, pic: &PictureData) { + self.has_mmco_5 = pic.has_mmco_5; + self.top_field_order_cnt = pic.top_field_order_cnt; + self.pic_order_cnt_msb = pic.pic_order_cnt_msb; + self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb; + self.field = pic.field; + self.frame_num = pic.frame_num; + } +} + +#[derive(Default)] +pub struct PrevPicInfo { + frame_num: u32, + frame_num_offset: u32, + has_mmco_5: bool, +} + +impl PrevPicInfo { + /// Store some variables related to the previous picture. These will be used + /// in the decoding of future pictures. + fn fill(&mut self, pic: &PictureData) { + self.frame_num = pic.frame_num; + self.has_mmco_5 = pic.has_mmco_5; + self.frame_num_offset = pic.frame_num_offset; + } +} + +/// Corresponds to RefPicList0 and RefPicList1 in the specification. Computed for every slice, +/// points to the pictures in the DPB. +struct RefPicLists<'a, T> { + ref_pic_list0: DpbPicRefList<'a, T>, + ref_pic_list1: DpbPicRefList<'a, T>, +} + +/// Used to track that first_mb_in_slice increases monotonically. +enum CurrentMacroblockTracking { + SeparateColorPlane(std::collections::BTreeMap), + NonSeparateColorPlane(u32), +} + +/// State of the picture being currently decoded. +/// +/// Stored between calls to [`StatelessDecoder::handle_slice`] that belong to the same picture. +struct CurrentPicState

{ + /// Data for the current picture as extracted from the stream. + pic: PictureData, + /// PPS at the time of the current picture. + pps: Rc, + /// Backend-specific data for that picture. + backend_pic: P, + /// List of reference pictures, used once per slice. + ref_pic_lists: ReferencePicLists, + /// The current macroblock we are processing + current_macroblock: CurrentMacroblockTracking, +} + +/// State of the H.264 decoder. +/// +/// `B` is the backend used for this decoder. +pub struct H264DecoderState { + /// H.264 bitstream parser. + parser: Parser, + /// Keeps track of the last stream parameters seen for negotiation purposes. + negotiation_info: NegotiationInfo, + + /// The decoded picture buffer. + dpb: Dpb, + + /// Cached variables from the previous reference picture. + prev_ref_pic_info: PrevReferencePicInfo, + /// Cached variables from the previous picture. + prev_pic_info: PrevPicInfo, + /// Maximum index of the long-term frame. + max_long_term_frame_idx: MaxLongTermFrameIdx, + + /// The picture currently being decoded. We need to preserve it between calls to `decode` + /// because multiple slices will be processed in different calls to `decode`. + current_pic: Option>, +} + +impl Default for H264DecoderState +where + H: DecodedHandle, +{ + fn default() -> Self { + H264DecoderState { + parser: Default::default(), + negotiation_info: Default::default(), + dpb: Default::default(), + prev_ref_pic_info: Default::default(), + prev_pic_info: Default::default(), + max_long_term_frame_idx: Default::default(), + current_pic: None, + } + } +} + +/// [`StatelessCodec`] structure to use in order to create a H.264 stateless decoder. +/// +/// # Accepted input +/// +/// A decoder using this codec processes exactly one NAL unit of input per call to +/// [`StatelessDecoder::decode`], and returns the number of bytes until the end of this NAL unit. +/// This makes it possible to call [`Decode`](StatelessDecoder::decode) repeatedly on some unsplit +/// Annex B stream and shrinking it by the number of bytes processed after each call, until the +/// stream ends up being empty. +pub struct H264; + +impl StatelessCodec for H264 { + type FormatInfo = Rc; + type DecoderState = H264DecoderState; +} + +#[derive(Debug, Error)] +enum FindFirstFieldError { + #[error("expected complementary field {0:?}, got {1:?}")] + ExpectedComplementaryField(Field, Field), + #[error("the previous field's frame_num value {0} differs from the current one's {1}")] + FrameNumDiffers(u32, u32), +} + +impl H264DecoderState +where + H: DecodedHandle + Clone, +{ + fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> { + match pic.pic_order_cnt_type { + // Spec 8.2.1.1 + 0 => { + let prev_pic_order_cnt_msb; + let prev_pic_order_cnt_lsb; + + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + prev_pic_order_cnt_lsb = 0; + prev_pic_order_cnt_msb = 0; + } else if self.prev_ref_pic_info.has_mmco_5 { + if !matches!(self.prev_ref_pic_info.field, Field::Bottom) { + prev_pic_order_cnt_msb = 0; + prev_pic_order_cnt_lsb = self.prev_ref_pic_info.top_field_order_cnt; + } else { + prev_pic_order_cnt_msb = 0; + prev_pic_order_cnt_lsb = 0; + } + } else { + prev_pic_order_cnt_msb = self.prev_ref_pic_info.pic_order_cnt_msb; + prev_pic_order_cnt_lsb = self.prev_ref_pic_info.pic_order_cnt_lsb; + } + + let max_pic_order_cnt_lsb = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); + + pic.pic_order_cnt_msb = if (pic.pic_order_cnt_lsb + < self.prev_ref_pic_info.pic_order_cnt_lsb) + && (prev_pic_order_cnt_lsb - pic.pic_order_cnt_lsb >= max_pic_order_cnt_lsb / 2) + { + prev_pic_order_cnt_msb + max_pic_order_cnt_lsb + } else if (pic.pic_order_cnt_lsb > prev_pic_order_cnt_lsb) + && (pic.pic_order_cnt_lsb - prev_pic_order_cnt_lsb > max_pic_order_cnt_lsb / 2) + { + prev_pic_order_cnt_msb - max_pic_order_cnt_lsb + } else { + prev_pic_order_cnt_msb + }; + + if !matches!(pic.field, Field::Bottom) { + pic.top_field_order_cnt = pic.pic_order_cnt_msb + pic.pic_order_cnt_lsb; + } + + if !matches!(pic.field, Field::Top) { + if matches!(pic.field, Field::Frame) { + pic.bottom_field_order_cnt = + pic.top_field_order_cnt + pic.delta_pic_order_cnt_bottom; + } else { + pic.bottom_field_order_cnt = pic.pic_order_cnt_msb + pic.pic_order_cnt_lsb; + } + } + } + + 1 => { + if self.prev_pic_info.has_mmco_5 { + self.prev_pic_info.frame_num_offset = 0; + } + + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + pic.frame_num_offset = 0; + } else if self.prev_pic_info.frame_num > pic.frame_num { + pic.frame_num_offset = + self.prev_pic_info.frame_num_offset + sps.max_frame_num(); + } else { + pic.frame_num_offset = self.prev_pic_info.frame_num_offset; + } + + let mut abs_frame_num = if sps.num_ref_frames_in_pic_order_cnt_cycle != 0 { + pic.frame_num_offset + pic.frame_num + } else { + 0 + }; + + if pic.nal_ref_idc == 0 && abs_frame_num > 0 { + abs_frame_num -= 1; + } + + let mut expected_pic_order_cnt = 0; + + if abs_frame_num > 0 { + if sps.num_ref_frames_in_pic_order_cnt_cycle == 0 { + return Err(anyhow!("Invalid num_ref_frames_in_pic_order_cnt_cycle")); + } + + let pic_order_cnt_cycle_cnt = + (abs_frame_num - 1) / sps.num_ref_frames_in_pic_order_cnt_cycle as u32; + let frame_num_in_pic_order_cnt_cycle = + (abs_frame_num - 1) % sps.num_ref_frames_in_pic_order_cnt_cycle as u32; + expected_pic_order_cnt = + pic_order_cnt_cycle_cnt as i32 * sps.expected_delta_per_pic_order_cnt_cycle; + + assert!(frame_num_in_pic_order_cnt_cycle < 255); + + for i in 0..sps.num_ref_frames_in_pic_order_cnt_cycle { + expected_pic_order_cnt += sps.offset_for_ref_frame[i as usize]; + } + } + + if pic.nal_ref_idc == 0 { + expected_pic_order_cnt += sps.offset_for_non_ref_pic; + } + + if matches!(pic.field, Field::Frame) { + pic.top_field_order_cnt = expected_pic_order_cnt + pic.delta_pic_order_cnt0; + + pic.bottom_field_order_cnt = pic.top_field_order_cnt + + sps.offset_for_top_to_bottom_field + + pic.delta_pic_order_cnt1; + } else if !matches!(pic.field, Field::Bottom) { + pic.top_field_order_cnt = expected_pic_order_cnt + pic.delta_pic_order_cnt0; + } else { + pic.bottom_field_order_cnt = expected_pic_order_cnt + + sps.offset_for_top_to_bottom_field + + pic.delta_pic_order_cnt0; + } + } + + 2 => { + // Spec 8.2.1.3 + if self.prev_pic_info.has_mmco_5 { + self.prev_pic_info.frame_num_offset = 0; + } + + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + pic.frame_num_offset = 0; + } else if self.prev_pic_info.frame_num > pic.frame_num { + pic.frame_num_offset = + self.prev_pic_info.frame_num_offset + sps.max_frame_num(); + } else { + pic.frame_num_offset = self.prev_pic_info.frame_num_offset; + } + + let pic_order_cnt = if matches!(pic.is_idr, IsIdr::Yes { .. }) { + 0 + } else if pic.nal_ref_idc == 0 { + 2 * (pic.frame_num_offset + pic.frame_num) as i32 - 1 + } else { + 2 * (pic.frame_num_offset + pic.frame_num) as i32 + }; + + if matches!(pic.field, Field::Frame | Field::Top) { + pic.top_field_order_cnt = pic_order_cnt; + } + if matches!(pic.field, Field::Frame | Field::Bottom) { + pic.bottom_field_order_cnt = pic_order_cnt; + } + } + + _ => return Err(anyhow!("Invalid pic_order_cnt_type: {}", sps.pic_order_cnt_type)), + } + + match pic.field { + Field::Frame => { + pic.pic_order_cnt = + std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt); + } + Field::Top => { + pic.pic_order_cnt = pic.top_field_order_cnt; + } + Field::Bottom => { + pic.pic_order_cnt = pic.bottom_field_order_cnt; + } + } + + Ok(()) + } + + /// Returns an iterator of the handles of the frames that need to be bumped into the ready + /// queue. + fn bump_as_needed(&mut self, current_pic: &PictureData) -> impl Iterator { + self.dpb.bump_as_needed(current_pic).into_iter().flatten() + } + + /// Returns an iterator of the handles of all the frames still present in the DPB. + fn drain(&mut self) -> impl Iterator { + let pics = self.dpb.drain(); + + pics.into_iter().flatten() + } + + /// Find the first field for the picture started by `slice`, if any. + fn find_first_field( + &self, + hdr: &SliceHeader, + ) -> Result, FindFirstFieldError> { + let mut prev_field = None; + + if self.dpb.interlaced() { + if let Some(last_dpb_entry) = self.dpb.entries().last() { + // Use the last entry in the DPB + let last_pic = last_dpb_entry.pic.borrow(); + + // If the picture is interlaced but doesn't have its other field set yet, + // then it must be the first field. + if !matches!(last_pic.field, Field::Frame) + && matches!(last_pic.field_rank(), FieldRank::Single) + { + if let Some(handle) = &last_dpb_entry.reference { + // Still waiting for the second field + prev_field = Some((last_dpb_entry.pic.clone(), handle.clone())); + } + } + } + } + + let prev_field = match prev_field { + None => return Ok(None), + Some(prev_field) => prev_field, + }; + + let prev_field_pic = prev_field.0.borrow(); + + if prev_field_pic.frame_num != u32::from(hdr.frame_num) { + return Err(FindFirstFieldError::FrameNumDiffers( + prev_field_pic.frame_num, + hdr.frame_num as u32, + )); + } + + let cur_field = if hdr.bottom_field_flag { Field::Bottom } else { Field::Top }; + + if !hdr.field_pic_flag || cur_field == prev_field_pic.field { + let field = prev_field_pic.field; + + return Err(FindFirstFieldError::ExpectedComplementaryField(field.opposite(), field)); + } + + drop(prev_field_pic); + Ok(Some(prev_field)) + } + + // 8.2.4.3.1 Modification process of reference picture lists for short-term + // reference pictures + #[allow(clippy::too_many_arguments)] + fn short_term_pic_list_modification<'a>( + cur_pic: &PictureData, + dpb: &'a Dpb, + ref_pic_list_x: &mut DpbPicRefList<'a, H>, + num_ref_idx_lx_active_minus1: u8, + max_pic_num: i32, + rplm: &RefPicListModification, + pic_num_lx_pred: &mut i32, + ref_idx_lx: &mut usize, + ) -> anyhow::Result<()> { + let pic_num_lx_no_wrap; + let abs_diff_pic_num = rplm.abs_diff_pic_num_minus1 as i32 + 1; + let modification_of_pic_nums_idc = rplm.modification_of_pic_nums_idc; + + if modification_of_pic_nums_idc == 0 { + if *pic_num_lx_pred - abs_diff_pic_num < 0 { + pic_num_lx_no_wrap = *pic_num_lx_pred - abs_diff_pic_num + max_pic_num; + } else { + pic_num_lx_no_wrap = *pic_num_lx_pred - abs_diff_pic_num; + } + } else if modification_of_pic_nums_idc == 1 { + if *pic_num_lx_pred + abs_diff_pic_num >= max_pic_num { + pic_num_lx_no_wrap = *pic_num_lx_pred + abs_diff_pic_num - max_pic_num; + } else { + pic_num_lx_no_wrap = *pic_num_lx_pred + abs_diff_pic_num; + } + } else { + anyhow::bail!( + "unexpected value for modification_of_pic_nums_idc {:?}", + rplm.modification_of_pic_nums_idc + ); + } + + *pic_num_lx_pred = pic_num_lx_no_wrap; + + let pic_num_lx = if pic_num_lx_no_wrap > cur_pic.pic_num { + pic_num_lx_no_wrap - max_pic_num + } else { + pic_num_lx_no_wrap + }; + + let handle = dpb + .find_short_term_with_pic_num(pic_num_lx) + .with_context(|| format!("No ShortTerm reference found with pic_num {}", pic_num_lx))?; + + if *ref_idx_lx >= ref_pic_list_x.len() { + anyhow::bail!("invalid ref_idx_lx index"); + } + ref_pic_list_x.insert(*ref_idx_lx, handle); + *ref_idx_lx += 1; + + let mut nidx = *ref_idx_lx; + + for cidx in *ref_idx_lx..=usize::from(num_ref_idx_lx_active_minus1) + 1 { + if cidx == ref_pic_list_x.len() { + break; + } + + let target = &ref_pic_list_x[cidx].pic; + + if target.borrow().pic_num_f(max_pic_num) != pic_num_lx { + ref_pic_list_x[nidx] = ref_pic_list_x[cidx]; + nidx += 1; + } + } + + while ref_pic_list_x.len() > (usize::from(num_ref_idx_lx_active_minus1) + 1) { + ref_pic_list_x.pop(); + } + + Ok(()) + } + + fn long_term_pic_list_modification<'a>( + dpb: &'a Dpb, + ref_pic_list_x: &mut DpbPicRefList<'a, H>, + num_ref_idx_lx_active_minus1: u8, + max_long_term_frame_idx: MaxLongTermFrameIdx, + rplm: &RefPicListModification, + ref_idx_lx: &mut usize, + ) -> anyhow::Result<()> { + let long_term_pic_num = rplm.long_term_pic_num; + + let handle = + dpb.find_long_term_with_long_term_pic_num(long_term_pic_num).with_context(|| { + format!("No LongTerm reference found with long_term_pic_num {}", long_term_pic_num) + })?; + + if *ref_idx_lx >= ref_pic_list_x.len() { + anyhow::bail!("invalid ref_idx_lx index"); + } + ref_pic_list_x.insert(*ref_idx_lx, handle); + *ref_idx_lx += 1; + + let mut nidx = *ref_idx_lx; + + for cidx in *ref_idx_lx..=usize::from(num_ref_idx_lx_active_minus1) + 1 { + if cidx == ref_pic_list_x.len() { + break; + } + + let target = &ref_pic_list_x[cidx].pic; + if target.borrow().long_term_pic_num_f(max_long_term_frame_idx) != long_term_pic_num { + ref_pic_list_x[nidx] = ref_pic_list_x[cidx]; + nidx += 1; + } + } + + while ref_pic_list_x.len() > (usize::from(num_ref_idx_lx_active_minus1) + 1) { + ref_pic_list_x.pop(); + } + + Ok(()) + } + + fn modify_ref_pic_list( + &self, + cur_pic: &PictureData, + hdr: &SliceHeader, + ref_pic_list_type: RefPicList, + ref_pic_list_indices: &[usize], + ) -> anyhow::Result> { + let (ref_pic_list_modification_flag_lx, num_ref_idx_lx_active_minus1, rplm) = + match ref_pic_list_type { + RefPicList::RefPicList0 => ( + hdr.ref_pic_list_modification_flag_l0, + hdr.num_ref_idx_l0_active_minus1, + &hdr.ref_pic_list_modification_l0, + ), + RefPicList::RefPicList1 => ( + hdr.ref_pic_list_modification_flag_l1, + hdr.num_ref_idx_l1_active_minus1, + &hdr.ref_pic_list_modification_l1, + ), + }; + + let mut ref_pic_list: Vec<_> = ref_pic_list_indices + .iter() + .map(|&i| &self.dpb.entries()[i]) + .take(usize::from(num_ref_idx_lx_active_minus1) + 1) + .collect(); + + if !ref_pic_list_modification_flag_lx { + return Ok(ref_pic_list); + } + + let mut pic_num_lx_pred = cur_pic.pic_num; + let mut ref_idx_lx = 0; + + for modification in rplm { + let idc = modification.modification_of_pic_nums_idc; + + match idc { + 0 | 1 => { + Self::short_term_pic_list_modification( + cur_pic, + &self.dpb, + &mut ref_pic_list, + num_ref_idx_lx_active_minus1, + hdr.max_pic_num as i32, + modification, + &mut pic_num_lx_pred, + &mut ref_idx_lx, + )?; + } + 2 => Self::long_term_pic_list_modification( + &self.dpb, + &mut ref_pic_list, + num_ref_idx_lx_active_minus1, + self.max_long_term_frame_idx, + modification, + &mut ref_idx_lx, + )?, + 3 => break, + _ => anyhow::bail!("unexpected modification_of_pic_nums_idc {:?}", idc), + } + } + + Ok(ref_pic_list) + } + + /// Generate RefPicList0 and RefPicList1 in the specification. Computed for every slice, points + /// to the pictures in the DPB. + fn create_ref_pic_lists( + &mut self, + cur_pic: &PictureData, + hdr: &SliceHeader, + ref_pic_lists: &ReferencePicLists, + ) -> anyhow::Result> { + let ref_pic_list0 = match hdr.slice_type { + SliceType::P | SliceType::Sp => self.modify_ref_pic_list( + cur_pic, + hdr, + RefPicList::RefPicList0, + &ref_pic_lists.ref_pic_list_p0, + )?, + SliceType::B => self.modify_ref_pic_list( + cur_pic, + hdr, + RefPicList::RefPicList0, + &ref_pic_lists.ref_pic_list_b0, + )?, + _ => Vec::new(), + }; + + let ref_pic_list1 = match hdr.slice_type { + SliceType::B => self.modify_ref_pic_list( + cur_pic, + hdr, + RefPicList::RefPicList1, + &ref_pic_lists.ref_pic_list_b1, + )?, + _ => Vec::new(), + }; + + Ok(RefPicLists { ref_pic_list0, ref_pic_list1 }) + } + + fn handle_memory_management_ops(&mut self, pic: &mut PictureData) -> Result<(), MmcoError> { + let markings = pic.ref_pic_marking.clone(); + + for marking in &markings.inner { + match marking.memory_management_control_operation { + 0 => break, + 1 => self.dpb.mmco_op_1(pic, marking)?, + 2 => self.dpb.mmco_op_2(pic, marking)?, + 3 => self.dpb.mmco_op_3(pic, marking)?, + 4 => self.max_long_term_frame_idx = self.dpb.mmco_op_4(marking), + 5 => self.max_long_term_frame_idx = self.dpb.mmco_op_5(pic), + 6 => self.dpb.mmco_op_6(pic, marking), + other => return Err(MmcoError::UnknownMmco(other)), + } + } + + Ok(()) + } + + fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> { + /* 8.2.5.1 */ + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + self.dpb.mark_all_as_unused_for_ref(); + + if pic.ref_pic_marking.long_term_reference_flag { + pic.set_reference(Reference::LongTerm, false); + pic.long_term_frame_idx = 0; + self.max_long_term_frame_idx = MaxLongTermFrameIdx::Idx(0); + } else { + pic.set_reference(Reference::ShortTerm, false); + self.max_long_term_frame_idx = MaxLongTermFrameIdx::NoLongTermFrameIndices; + } + + return Ok(()); + } + + if pic.ref_pic_marking.adaptive_ref_pic_marking_mode_flag { + self.handle_memory_management_ops(pic)?; + } else { + self.dpb.sliding_window_marking(pic, sps); + } + + Ok(()) + } + + // Apply the parameters of `sps` to the decoding state. + fn apply_sps(&mut self, sps: &Sps) { + self.negotiation_info = NegotiationInfo::from(sps); + + let max_dpb_frames = sps.max_dpb_frames(); + let interlaced = !sps.frame_mbs_only_flag; + let max_num_order_frames = sps.max_num_order_frames() as usize; + let max_num_reorder_frames = + if max_num_order_frames > max_dpb_frames { 0 } else { max_num_order_frames }; + + self.dpb.set_limits(max_dpb_frames, max_num_reorder_frames); + self.dpb.set_interlaced(interlaced); + } +} + +impl StatelessDecoder +where + B: StatelessH264DecoderBackend, + B::Handle: Clone, +{ + fn negotiation_possible(sps: &Sps, old_negotiation_info: &NegotiationInfo) -> bool { + let negotiation_info = NegotiationInfo::from(sps); + *old_negotiation_info != negotiation_info + } + + fn renegotiate_if_needed(&mut self, sps: &Rc) -> anyhow::Result<()> { + if Self::negotiation_possible(sps, &self.codec.negotiation_info) { + // Make sure all the frames we decoded so far are in the ready queue. + self.drain()?; + self.backend.new_sequence(sps)?; + self.await_format_change(sps.clone()); + } + + Ok(()) + } + + // Apply the parameters of `sps` to the decoder. + fn apply_sps(&mut self, sps: &Sps) { + self.codec.apply_sps(sps); + + self.coded_resolution = Resolution::from((sps.width(), sps.height())); + } + + fn drain(&mut self) -> anyhow::Result<()> { + // Finish the current picture if there is one pending. + if let Some(cur_pic) = self.codec.current_pic.take() { + self.finish_picture(cur_pic)?; + } + + self.ready_queue.extend(self.codec.drain()); + + Ok(()) + } + + /// Adds picture to the ready queue if it could not be added to the DPB. + fn add_to_ready_queue(&mut self, pic: PictureData, handle: B::Handle) { + if matches!(pic.field, Field::Frame) { + self.ready_queue.push(handle); + } else if let FieldRank::Second(..) = pic.field_rank() { + self.ready_queue.push(handle) + } + } + + fn finish_picture(&mut self, pic: CurrentPicState) -> anyhow::Result<()> { + debug!("Finishing picture POC {:?}", pic.pic.pic_order_cnt); + + // Submit the picture to the backend. + let handle = self.submit_picture(pic.backend_pic)?; + let pps = pic.pps; + let mut pic = pic.pic; + + if matches!(pic.reference(), Reference::ShortTerm | Reference::LongTerm) { + self.codec.reference_pic_marking(&mut pic, &pps.sps)?; + self.codec.prev_ref_pic_info.fill(&pic); + } + + self.codec.prev_pic_info.fill(&pic); + + if pic.has_mmco_5 { + // C.4.5.3 "Bumping process" + // The bumping process is invoked in the following cases: + // Clause 3: + // The current picture has memory_management_control_operation equal + // to 5, as specified in clause C.4.4. + self.drain()?; + } + + // Bump the DPB as per C.4.5.3 to cover clauses 1, 4, 5 and 6. + self.ready_queue.extend(self.codec.bump_as_needed(&pic)); + + // C.4.5.1, C.4.5.2 + // If the current decoded picture is the second field of a complementary + // reference field pair, add to DPB. + // C.4.5.1 + // For a reference decoded picture, the "bumping" process is invoked + // repeatedly until there is an empty frame buffer, by which point it is + // added to the DPB. Notice that Dpb::needs_bumping already accounts for + // this. + // C.4.5.2 + // For a non-reference decoded picture, if there is empty frame buffer + // after bumping the smaller POC, add to DPB. Otherwise, add it to the + // ready queue. + if pic.is_second_field_of_complementary_ref_pair() + || pic.is_ref() + || self.codec.dpb.has_empty_frame_buffer() + { + if self.codec.dpb.interlaced() && matches!(pic.field, Field::Frame) { + // Split the Frame into two complementary fields so reference + // marking is easier. This is inspired by the GStreamer implementation. + let (first_field, second_field) = PictureData::split_frame(pic); + + self.codec.dpb.store_picture(first_field, Some(handle.clone()))?; + self.codec.dpb.store_picture(second_field, Some(handle))?; + } else { + self.codec.dpb.store_picture(pic.into_rc(), Some(handle))?; + } + } else { + self.add_to_ready_queue(pic, handle); + } + + Ok(()) + } + + fn handle_frame_num_gap( + &mut self, + sps: &Sps, + frame_num: u32, + timestamp: u64, + ) -> anyhow::Result<()> { + if self.codec.dpb.is_empty() { + return Ok(()); + } + + debug!("frame_num gap detected."); + + if !sps.gaps_in_frame_num_value_allowed_flag { + return Err(anyhow!( + "Invalid frame_num: {}. Assuming unintentional loss of pictures", + frame_num + )); + } + + let mut unused_short_term_frame_num = + (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num(); + while unused_short_term_frame_num != frame_num { + let max_frame_num = sps.max_frame_num(); + + let mut pic = PictureData::new_non_existing(unused_short_term_frame_num, timestamp); + self.codec.compute_pic_order_count(&mut pic, sps)?; + + self.codec.dpb.update_pic_nums(unused_short_term_frame_num, max_frame_num, &pic); + + self.codec.dpb.sliding_window_marking(&mut pic, sps); + + self.ready_queue.extend(self.codec.bump_as_needed(&pic)); + + if self.codec.dpb.interlaced() { + let (first_field, second_field) = PictureData::split_frame(pic); + + self.codec.dpb.store_picture(first_field, None)?; + self.codec.dpb.store_picture(second_field, None)?; + } else { + self.codec.dpb.store_picture(pic.into_rc(), None)?; + } + + unused_short_term_frame_num += 1; + unused_short_term_frame_num %= max_frame_num; + } + + Ok(()) + } + + /// Init the current picture being decoded. + fn init_current_pic( + &mut self, + slice: &Slice, + sps: &Sps, + first_field: Option<&RcPictureData>, + timestamp: u64, + ) -> anyhow::Result { + let mut pic = PictureData::new_from_slice(slice, sps, timestamp, first_field); + self.codec.compute_pic_order_count(&mut pic, sps)?; + + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + // C.4.5.3 "Bumping process" + // The bumping process is invoked in the following cases: + // Clause 2: + // The current picture is an IDR picture and + // no_output_of_prior_pics_flag is not equal to 1 and is not + // inferred to be equal to 1, as specified in clause C.4.4. + if !pic.ref_pic_marking.no_output_of_prior_pics_flag { + self.drain()?; + } else { + // C.4.4 When no_output_of_prior_pics_flag is equal to 1 or is + // inferred to be equal to 1, all frame buffers in the DPB are + // emptied without output of the pictures they contain, and DPB + // fullness is set to 0. + self.codec.dpb.clear(); + } + } + + self.codec.dpb.update_pic_nums( + u32::from(slice.header.frame_num), + sps.max_frame_num(), + &pic, + ); + + Ok(pic) + } + + /// Called once per picture to start it. + fn begin_picture( + &mut self, + timestamp: u64, + slice: &Slice, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result, DecodeError> { + let hdr = &slice.header; + let pps = Rc::clone( + self.codec + .parser + .get_pps(hdr.pic_parameter_set_id) + .context("Invalid PPS in handle_picture")?, + ); + + // A picture's SPS may require negociation. + self.renegotiate_if_needed(&pps.sps)?; + if let DecodingState::AwaitingFormat(_) = &self.decoding_state { + return Err(DecodeError::CheckEvents); + } + + // Start by securing the backend picture before modifying our state. + let first_field = + self.codec.find_first_field(&slice.header).context("while looking for first field")?; + let mut backend_pic = if let Some(first_field) = &first_field { + self.backend.new_field_picture(timestamp, &first_field.1) + } else { + self.backend.new_picture(timestamp, alloc_cb) + }?; + + let nalu_hdr = &slice.nalu.header; + + if nalu_hdr.idr_pic_flag { + self.codec.prev_ref_pic_info.frame_num = 0; + } + + let frame_num = u32::from(hdr.frame_num); + + let current_macroblock = match pps.sps.separate_colour_plane_flag { + true => CurrentMacroblockTracking::SeparateColorPlane(Default::default()), + false => CurrentMacroblockTracking::NonSeparateColorPlane(0), + }; + + if frame_num != self.codec.prev_ref_pic_info.frame_num + && frame_num != (self.codec.prev_ref_pic_info.frame_num + 1) % pps.sps.max_frame_num() + { + self.handle_frame_num_gap(&pps.sps, frame_num, timestamp)?; + } + + let pic = + self.init_current_pic(slice, &pps.sps, first_field.as_ref().map(|f| &f.0), timestamp)?; + let ref_pic_lists = self.codec.dpb.build_ref_pic_lists(&pic); + + debug!("Decode picture POC {:?}", pic.pic_order_cnt); + + self.backend.start_picture( + &mut backend_pic, + &pic, + pps.sps.as_ref(), + pps.as_ref(), + &self.codec.dpb, + &slice.header, + )?; + + Ok(CurrentPicState { pic, pps, backend_pic, ref_pic_lists, current_macroblock }) + } + + // Check whether first_mb_in_slice increases monotonically for the current + // picture as required by the specification. + fn check_first_mb_in_slice( + &mut self, + current_macroblock: &mut CurrentMacroblockTracking, + slice: &Slice, + ) { + match current_macroblock { + CurrentMacroblockTracking::SeparateColorPlane(current_macroblock) => { + match current_macroblock.entry(slice.header.colour_plane_id) { + Entry::Vacant(current_macroblock) => { + current_macroblock.insert(slice.header.first_mb_in_slice); + } + Entry::Occupied(mut current_macroblock) => { + let current_macroblock = current_macroblock.get_mut(); + if slice.header.first_mb_in_slice >= *current_macroblock { + log::trace!("first_mb_in_slice does not increase monotically, expect corrupted output"); + } + *current_macroblock = slice.header.first_mb_in_slice; + } + } + } + CurrentMacroblockTracking::NonSeparateColorPlane(current_macroblock) => { + if slice.header.first_mb_in_slice >= *current_macroblock { + log::trace!( + "first_mb_in_slice does not increase monotically, expect corrupted output" + ); + } + *current_macroblock = slice.header.first_mb_in_slice; + } + } + } + + /// Handle a slice. Called once per slice NALU. + fn handle_slice( + &mut self, + cur_pic: &mut CurrentPicState, + slice: &Slice, + ) -> anyhow::Result<()> { + self.check_first_mb_in_slice(&mut cur_pic.current_macroblock, slice); + + // A slice can technically refer to another PPS. + let pps = + self.codec.parser.get_pps(slice.header.pic_parameter_set_id).context("Invalid PPS")?; + cur_pic.pps = Rc::clone(pps); + + // Make sure that no negotiation is possible mid-picture. How could it? + // We'd lose the context with the previous slices on it. + if Self::negotiation_possible(&cur_pic.pps.sps, &self.codec.negotiation_info) { + anyhow::bail!("invalid stream: inter-frame renegotiation requested"); + } + + let RefPicLists { ref_pic_list0, ref_pic_list1 } = + self.codec.create_ref_pic_lists(&cur_pic.pic, &slice.header, &cur_pic.ref_pic_lists)?; + + self.backend.decode_slice( + &mut cur_pic.backend_pic, + slice, + cur_pic.pps.sps.as_ref(), + cur_pic.pps.as_ref(), + &ref_pic_list0, + &ref_pic_list1, + )?; + + Ok(()) + } + + /// Submits the picture to the accelerator. + fn submit_picture(&mut self, backend_pic: B::Picture) -> Result { + let handle = self.backend.submit_picture(backend_pic)?; + + if self.blocking_mode == BlockingMode::Blocking { + handle.sync()?; + } + + Ok(handle) + } + + fn process_nalu( + &mut self, + timestamp: u64, + nalu: Nalu, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result<(), DecodeError> { + match nalu.header.type_ { + NaluType::Sps => { + self.codec + .parser + .parse_sps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + } + NaluType::Pps => { + self.codec + .parser + .parse_pps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + } + NaluType::Slice + | NaluType::SliceDpa + | NaluType::SliceDpb + | NaluType::SliceDpc + | NaluType::SliceIdr + | NaluType::SliceExt => { + let slice = self + .codec + .parser + .parse_slice_header(nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + let mut cur_pic = match self.codec.current_pic.take() { + // No current picture, start a new one. + None => self.begin_picture(timestamp, &slice, alloc_cb)?, + // We have a current picture but are starting a new field, or first_mb_in_slice + // indicates that a new picture is starting: finish the current picture and + // start a new one. + Some(cur_pic) + if (self.codec.dpb.interlaced() + && matches!(cur_pic.pic.field, Field::Frame) + && !cur_pic.pic.is_second_field() + && cur_pic.pic.field != slice.header.field()) + || (slice.header.first_mb_in_slice == 0) => + { + self.finish_picture(cur_pic)?; + self.begin_picture(timestamp, &slice, alloc_cb)? + } + // This slice is part of the current picture. + Some(cur_pic) => cur_pic, + }; + + self.handle_slice(&mut cur_pic, &slice)?; + self.codec.current_pic = Some(cur_pic); + } + other => { + debug!("Unsupported NAL unit type {:?}", other,); + } + } + + Ok(()) + } +} + +impl StatelessVideoDecoder for StatelessDecoder +where + B: StatelessH264DecoderBackend, + B::Handle: Clone + 'static, +{ + type Handle = B::Handle; + + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result { + self.wait_for_drc_flush()?; + + let mut cursor = Cursor::new(bitstream); + let nalu = Nalu::next(&mut cursor).map_err(|err| DecodeError::ParseFrameError(err))?; + + if nalu.header.type_ == NaluType::Sps { + let sps = self + .codec + .parser + .parse_sps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))? + .clone(); + + if Self::negotiation_possible(&sps, &self.codec.negotiation_info) + && matches!(self.decoding_state, DecodingState::Decoding) + { + // DRC occurs when an SPS packet is received that indicates an IDR, + // the format is different, and the decoder is already decoding frames. + self.flush()?; + self.decoding_state = DecodingState::FlushingForDRC; + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + + if matches!(self.decoding_state, DecodingState::AwaitingStreamInfo) { + // If more SPS come along we will renegotiate in begin_picture(). + self.renegotiate_if_needed(&sps)?; + } else if matches!(self.decoding_state, DecodingState::Reset) { + // We can resume decoding since the decoding parameters have not changed. + self.decoding_state = DecodingState::Decoding; + } + } else if matches!(self.decoding_state, DecodingState::Reset) { + let mut cursor = Cursor::new(bitstream); + + while let Ok(nalu) = Nalu::next(&mut cursor) { + // In the Reset state we can resume decoding from any key frame. + if matches!(nalu.header.type_, NaluType::SliceIdr) { + self.decoding_state = DecodingState::Decoding; + break; + } + } + } + + let nalu_len = nalu.offset + nalu.size; + + match &mut self.decoding_state { + // Process parameter sets, but skip input until we get information + // from the stream. + DecodingState::AwaitingStreamInfo | DecodingState::Reset => { + if matches!(nalu.header.type_, NaluType::Pps) { + self.process_nalu(timestamp, nalu, alloc_cb)?; + } + } + // Ask the client to confirm the format before we can process this. + DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { + return Err(DecodeError::CheckEvents) + } + DecodingState::Decoding => { + self.process_nalu(timestamp, nalu, alloc_cb)?; + } + } + + Ok(nalu_len) + } + + fn flush(&mut self) -> Result<(), DecodeError> { + self.drain()?; + self.decoding_state = DecodingState::Reset; + + Ok(()) + } + + fn next_event(&mut self) -> Option> { + self.query_next_event(|decoder, sps| { + // Apply the SPS settings to the decoder so we don't enter the AwaitingFormat state + // on the next decode() call. + decoder.apply_sps(sps); + }) + } + + fn stream_info(&self) -> Option<&StreamInfo> { + self.backend.stream_info() + } + + fn poll_fd(&self) -> BorrowedFd { + self.epoll_fd.0.as_fd() + } +} + +#[cfg(test)] +pub mod tests { + use crate::bitstream_utils::NalIterator; + use crate::codec::h264::parser::Nalu; + use crate::decoder::stateless::h264::H264; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. + fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { + let decoder = StatelessDecoder::::new_dummy(blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + NalIterator::::new(s), + f, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + blocking_mode, + ) + }, + decoder, + test, + false, + false, + ); + } + + /// A 64x64 progressive byte-stream encoded I-frame to make it easier to + /// spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// + /// gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,format=I420,width=64,height=64 ! x264enc ! video/x-h264,profile=constrained-baseline,stream-format=byte-stream ! filesink location="64x64-I.h264" + pub const DECODE_64X64_PROGRESSIVE_I: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/64x64-I.h264"), + crcs: include_str!("../../codec/h264/test_data/64x64-I.h264.crc"), + }; + + #[test] + fn test_64x64_progressive_i_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::NonBlocking); + } + + /// A 64x64 progressive byte-stream encoded I-frame and P-frame to make + /// it easier to spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// gst-launch-1.0 videotestsrc num-buffers=2 ! video/x-raw,format=I420,width=64,height=64 ! x264enc b-adapt=false ! video/x-h264,profile=constrained-baseline,stream-format=byte-stream ! filesink location="64x64-I-P.h264" + pub const DECODE_64X64_PROGRESSIVE_I_P: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/64x64-I-P.h264"), + crcs: include_str!("../../codec/h264/test_data/64x64-I-P.h264.crc"), + }; + + #[test] + fn test_64x64_progressive_i_p_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_p_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::NonBlocking); + } + + /// A 64x64 progressive byte-stream encoded I-P-B-P sequence to make it + /// easier to it easier to spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// gst-launch-1.0 videotestsrc num-buffers=3 ! video/x-raw,format=I420,width=64,height=64 ! x264enc b-adapt=false bframes=1 ! video/x-h264,profile=constrained-baseline,stream-format=byte-stream ! filesink location="64x64-I-P-B-P.h264" + pub const DECODE_64X64_PROGRESSIVE_I_P_B_P: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/64x64-I-P-B-P.h264"), + crcs: include_str!("../../codec/h264/test_data/64x64-I-P-B-P.h264.crc"), + }; + + #[test] + fn test_64x64_progressive_i_p_b_p_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_p_b_p_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::NonBlocking); + } + + /// A 64x64 progressive byte-stream encoded I-P-B-P sequence to make it + /// easier to it easier to spot errors on the libva trace. + /// Also tests whether the decoder supports the high profile. + /// + /// Encoded with the following GStreamer pipeline: + /// gst-launch-1.0 videotestsrc num-buffers=3 ! video/x-raw,format=I420,width=64,height=64 ! x264enc b-adapt=false bframes=1 ! video/x-h264,profile=high,stream-format=byte-stream ! filesink location="64x64-I-P-B-P-high.h264" + pub const DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/64x64-I-P-B-P-high.h264"), + crcs: include_str!("../../codec/h264/test_data/64x64-I-P-B-P-high.h264.crc"), + }; + + #[test] + fn test_64x64_progressive_i_p_b_p_high_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_p_b_p_high_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH, BlockingMode::NonBlocking); + } + + /// Same as Chromium's test-25fps.h264 + pub const DECODE_TEST_25FPS: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/test-25fps.h264"), + crcs: include_str!("../../codec/h264/test_data/test-25fps.h264.crc"), + }; + + #[test] + fn test_25fps_block() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); + } + + // Adapted from Chromium's test-25fps.h264. Same file, but encoded as + // interlaced instead using the following ffmpeg command: + // ffmpeg -i + // src/third_party/blink/web_tests/media/content/test-25fps.mp4 + // -flags +ilme+ildct -vbsf h264_mp4toannexb -an test-25fps.h264 + // + // This test makes sure that the interlaced logic in the decoder + // actually works, specially that "frame splitting" works, as the fields + // here were encoded as frames. + pub const DECODE_TEST_25FPS_INTERLACED: TestStream = TestStream { + stream: include_bytes!("../../codec/h264/test_data/test-25fps-interlaced.h264"), + crcs: include_str!("../../codec/h264/test_data/test-25fps-interlaced.h264.crc"), + }; + + #[test] + fn test_25fps_interlaced_block() { + test_decoder_dummy(&DECODE_TEST_25FPS_INTERLACED, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_interlaced_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS_INTERLACED, BlockingMode::NonBlocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h264/dummy.rs b/vendor/cros-codecs/src/decoder/stateless/h264/dummy.rs new file mode 100644 index 0000000..95003ba --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h264/dummy.rs @@ -0,0 +1,75 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backend whose only purpose is to let the decoder +//! run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::dummy::decoder::Backend; +use crate::backend::dummy::decoder::Handle; +use crate::codec::h264::dpb::Dpb; +use crate::codec::h264::dpb::DpbEntry; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::Slice; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::PictureData; +use crate::decoder::stateless::h264::StatelessH264DecoderBackend; +use crate::decoder::stateless::h264::H264; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::BlockingMode; + +impl StatelessH264DecoderBackend for Backend { + fn new_sequence(&mut self, _: &Rc) -> StatelessBackendResult<()> { + Ok(()) + } + + fn start_picture( + &mut self, + _: &mut Self::Picture, + _: &PictureData, + _: &Sps, + _: &Pps, + _: &Dpb, + _: &SliceHeader, + ) -> StatelessBackendResult<()> { + Ok(()) + } + + fn new_field_picture(&mut self, _: u64, _: &Self::Handle) -> NewPictureResult<()> { + Ok(()) + } + + fn decode_slice( + &mut self, + _: &mut Self::Picture, + _: &Slice, + _: &Sps, + _: &Pps, + _: &[&DpbEntry], + _: &[&DpbEntry], + ) -> StatelessBackendResult<()> { + Ok(()) + } + + fn submit_picture(&mut self, _: Self::Picture) -> StatelessBackendResult { + Ok(Handle { handle: Rc::new(RefCell::new(Default::default())) }) + } + + fn new_picture(&mut self, _: u64) -> NewPictureResult<()> { + Ok(()) + } +} + +impl StatelessDecoder { + // Creates a new instance of the decoder using the dummy backend. + pub fn new_dummy(blocking_mode: BlockingMode) -> Result { + Self::new(Backend::new(), blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h264/v4l2.rs b/vendor/cros-codecs/src/decoder/stateless/h264/v4l2.rs new file mode 100644 index 0000000..6c6e146 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h264/v4l2.rs @@ -0,0 +1,180 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::rc::Rc; + +use v4l2r::bindings::v4l2_ctrl_h264_pps; +use v4l2r::bindings::v4l2_ctrl_h264_scaling_matrix; +use v4l2r::bindings::v4l2_ctrl_h264_sps; +use v4l2r::controls::codec::H264Pps; +use v4l2r::controls::codec::H264ScalingMatrix; +use v4l2r::controls::codec::H264Sps; +use v4l2r::controls::SafeExtControl; + +use crate::backend::v4l2::decoder::stateless::V4l2Picture; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderBackend; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderHandle; +use crate::backend::v4l2::decoder::V4l2StreamInfo; +use crate::backend::v4l2::decoder::ADDITIONAL_REFERENCE_FRAME_BUFFER; +use crate::codec::h264::dpb::Dpb; +use crate::codec::h264::dpb::DpbEntry; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::Slice; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::PictureData; +use crate::decoder::stateless::h264::StatelessH264DecoderBackend; +use crate::decoder::stateless::h264::H264; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::device::v4l2::stateless::controls::h264::V4l2CtrlH264DecodeMode; +use crate::device::v4l2::stateless::controls::h264::V4l2CtrlH264DecodeParams; +use crate::device::v4l2::stateless::controls::h264::V4l2CtrlH264DpbEntry; +use crate::device::v4l2::stateless::controls::h264::V4l2CtrlH264StartCode; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Rect; +use crate::Resolution; + +impl V4l2StreamInfo for &Rc { + fn min_num_frames(&self) -> usize { + self.max_dpb_frames() + ADDITIONAL_REFERENCE_FRAME_BUFFER + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width(), self.height())) + } + + fn visible_rect(&self) -> Rect { + let rect = self.visible_rectangle(); + + Rect { x: rect.min.x, y: rect.min.y, width: rect.max.x, height: rect.max.y } + } +} + +impl StatelessDecoderBackendPicture for V4l2StatelessDecoderBackend { + type Picture = Rc>>; +} + +impl StatelessH264DecoderBackend for V4l2StatelessDecoderBackend { + fn new_sequence(&mut self, sps: &Rc) -> StatelessBackendResult<()> { + self.new_sequence(sps, Fourcc::from(b"S264")) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?; + let request_buffer = match self.device.alloc_request(timestamp, frame) { + Ok(buffer) => buffer, + _ => return Err(NewPictureError::OutOfOutputBuffers), + }; + + let picture = Rc::new(RefCell::new(V4l2Picture::new(request_buffer.clone()))); + request_buffer + .as_ref() + .borrow_mut() + .set_picture_ref(Rc::>>::downgrade(&picture)); + Ok(picture) + } + + fn new_field_picture(&mut self, _: u64, _: &Self::Handle) -> NewPictureResult { + todo!() + } + + fn start_picture( + &mut self, + picture: &mut Self::Picture, + picture_data: &PictureData, + sps: &Sps, + pps: &Pps, + dpb: &Dpb, + slice_header: &SliceHeader, + ) -> StatelessBackendResult<()> { + let mut dpb_entries = Vec::::new(); + let mut ref_pictures = Vec::>>>::new(); + for entry in dpb.entries() { + let ref_picture = match &entry.reference { + Some(handle) => handle.picture.clone(), + None => todo!(), + }; + dpb_entries.push(V4l2CtrlH264DpbEntry { + timestamp: ref_picture.borrow().timestamp(), + pic: entry.pic.clone(), + }); + ref_pictures.push(ref_picture); + } + + let mut h264_decode_params = V4l2CtrlH264DecodeParams::new(); + let h264_sps = SafeExtControl::::from(v4l2_ctrl_h264_sps::from(sps)); + let h264_pps = SafeExtControl::::from(v4l2_ctrl_h264_pps::from(pps)); + let h264_scaling_matrix = + SafeExtControl::::from(v4l2_ctrl_h264_scaling_matrix::from(pps)); + + h264_decode_params + .set_picture_data(picture_data) + .set_dpb_entries(dpb_entries) + .set_slice_header(slice_header); + let mut picture = picture.borrow_mut(); + + let request = picture.request(); + let mut request = request.as_ref().borrow_mut(); + request + .ioctl(h264_sps)? + .ioctl(h264_pps)? + .ioctl(h264_scaling_matrix)? + .ioctl(&h264_decode_params)? + .ioctl(V4l2CtrlH264DecodeMode::FrameBased)? + .ioctl(V4l2CtrlH264StartCode::AnnexB)?; + picture.set_ref_pictures(ref_pictures); + Ok(()) + } + + fn decode_slice( + &mut self, + picture: &mut Self::Picture, + slice: &Slice, + _: &Sps, + _: &Pps, + _: &[&DpbEntry], + _: &[&DpbEntry], + ) -> StatelessBackendResult<()> { + const START_CODE: [u8; 3] = [0, 0, 1]; + + let request = picture.borrow_mut().request(); + let mut request = request.as_ref().borrow_mut(); + + request.write(&START_CODE); + request.write(slice.nalu.as_ref()); + Ok(()) + } + + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult { + let request = picture.borrow_mut().request(); + let mut request = request.as_ref().borrow_mut(); + request.submit()?; + Ok(V4l2StatelessDecoderHandle { + picture: picture.clone(), + stream_info: self.stream_info.clone(), + }) + } +} + +impl StatelessDecoder> { + pub fn new_v4l2(blocking_mode: BlockingMode) -> Result { + Self::new(V4l2StatelessDecoderBackend::new()?, blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h264/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/h264/vaapi.rs new file mode 100644 index 0000000..8dab7da --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h264/vaapi.rs @@ -0,0 +1,733 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context as AnyhowContext; +use libva::{ + BufferType, Display, IQMatrix, IQMatrixBufferH264, PictureParameter, + PictureParameterBufferH264, SliceParameter, +}; + +use crate::backend::vaapi::decoder::va_surface_id; +use crate::backend::vaapi::decoder::DecodedHandle as VADecodedHandle; +use crate::backend::vaapi::decoder::VaStreamInfo; +use crate::backend::vaapi::decoder::VaapiBackend; +use crate::backend::vaapi::decoder::VaapiPicture; +use crate::codec::h264::dpb::Dpb; +use crate::codec::h264::dpb::DpbEntry; +use crate::codec::h264::parser::Level; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::Profile; +use crate::codec::h264::parser::Slice; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::Field; +use crate::codec::h264::picture::PictureData; +use crate::codec::h264::picture::Reference; +use crate::decoder::stateless::h264::StatelessH264DecoderBackend; +use crate::decoder::stateless::h264::H264; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::video_frame::VideoFrame; +use crate::Rect; +use crate::Resolution; + +impl VaStreamInfo for &Rc { + fn va_profile(&self) -> anyhow::Result { + let profile_idc = self.profile_idc; + let profile = Profile::try_from(profile_idc) + .map_err(|err| anyhow!(err)) + .with_context(|| format!("Invalid profile_idc {:?}", profile_idc))?; + + match profile { + Profile::Baseline => { + if self.constraint_set0_flag { + Ok(libva::VAProfile::VAProfileH264ConstrainedBaseline) + } else { + Err(anyhow!( + "Unsupported stream: profile_idc=66, but constraint_set0_flag is unset" + )) + } + } + Profile::Main => Ok(libva::VAProfile::VAProfileH264Main), + Profile::Extended => { + if self.constraint_set1_flag { + Ok(libva::VAProfile::VAProfileH264Main) + } else { + Err(anyhow!( + "Unsupported stream: profile_idc=88, but constraint_set1_flag is unset" + )) + } + } + Profile::High | Profile::High422P | Profile::High10 => { + Ok(libva::VAProfile::VAProfileH264High) + } + } + } + + fn rt_format(&self) -> anyhow::Result { + let bit_depth_luma = self.bit_depth_chroma_minus8 + 8; + let chroma_format_idc = self.chroma_format_idc; + + match (bit_depth_luma, chroma_format_idc) { + (8, 0) | (8, 1) => Ok(libva::VA_RT_FORMAT_YUV420), + (8, 2) => Ok(libva::VA_RT_FORMAT_YUV422), + (8, 3) => Ok(libva::VA_RT_FORMAT_YUV444), + (10, 0) | (10, 1) => Ok(libva::VA_RT_FORMAT_YUV420_10), + (10, 2) => Ok(libva::VA_RT_FORMAT_YUV422_10), + (10, 3) => Ok(libva::VA_RT_FORMAT_YUV444_10), + (12, 0) | (12, 1) => Ok(libva::VA_RT_FORMAT_YUV420_12), + (12, 2) => Ok(libva::VA_RT_FORMAT_YUV422_12), + (12, 3) => Ok(libva::VA_RT_FORMAT_YUV444_12), + _ => Err(anyhow!( + "unsupported bit depth/chroma format pair {}, {}", + bit_depth_luma, + chroma_format_idc + )), + } + } + + fn min_num_surfaces(&self) -> usize { + self.max_dpb_frames() + 4 + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width(), self.height())) + } + + fn visible_rect(&self) -> Rect { + let rect = self.visible_rectangle(); + + Rect { x: rect.min.x, y: rect.min.y, width: rect.max.x, height: rect.max.y } + } +} + +/// Fills the internal `va_pic` picture parameter with data from `h264_pic` +fn fill_va_h264_pic( + h264_pic: &PictureData, + surface_id: libva::VASurfaceID, + merge_other_field: bool, +) -> libva::PictureH264 { + let mut flags = 0; + let frame_idx = if matches!(h264_pic.reference(), Reference::LongTerm) { + flags |= libva::VA_PICTURE_H264_LONG_TERM_REFERENCE; + h264_pic.long_term_frame_idx + } else { + if matches!(h264_pic.reference(), Reference::ShortTerm { .. }) { + flags |= libva::VA_PICTURE_H264_SHORT_TERM_REFERENCE; + } + + h264_pic.frame_num + }; + + let top_field_order_cnt; + let bottom_field_order_cnt; + + match h264_pic.field { + Field::Frame => { + top_field_order_cnt = h264_pic.top_field_order_cnt; + bottom_field_order_cnt = h264_pic.bottom_field_order_cnt; + } + Field::Top => { + match (merge_other_field, h264_pic.other_field()) { + (true, Some(other_field)) => { + bottom_field_order_cnt = other_field.borrow().bottom_field_order_cnt + } + (_, _) => { + flags |= libva::VA_PICTURE_H264_TOP_FIELD; + bottom_field_order_cnt = 0; + } + } + + top_field_order_cnt = h264_pic.top_field_order_cnt; + } + Field::Bottom => { + match (merge_other_field, h264_pic.other_field()) { + (true, Some(other_field)) => { + top_field_order_cnt = other_field.borrow().top_field_order_cnt + } + (_, _) => { + flags |= libva::VA_PICTURE_H264_BOTTOM_FIELD; + top_field_order_cnt = 0; + } + } + + bottom_field_order_cnt = h264_pic.bottom_field_order_cnt; + } + } + + libva::PictureH264::new( + surface_id, + frame_idx, + flags, + top_field_order_cnt, + bottom_field_order_cnt, + ) +} + +/// Builds an invalid VaPictureH264. These pictures are used to fill empty +/// array slots there is no data to fill them with. +fn build_invalid_va_h264_pic() -> libva::PictureH264 { + libva::PictureH264::new(libva::VA_INVALID_ID, 0, libva::VA_PICTURE_H264_INVALID, 0, 0) +} + +fn build_iq_matrix(pps: &Pps) -> BufferType { + let mut scaling_list4x4 = [[0; 16]; 6]; + let mut scaling_list8x8 = [[0; 64]; 2]; + + (0..6).for_each(|i| { + super::get_raster_from_zigzag_4x4(pps.scaling_lists_4x4[i], &mut scaling_list4x4[i]); + }); + + (0..2).for_each(|i| { + super::get_raster_from_zigzag_8x8(pps.scaling_lists_8x8[i], &mut scaling_list8x8[i]); + }); + + BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(scaling_list4x4, scaling_list8x8))) +} + +fn build_pic_param( + hdr: &SliceHeader, + current_picture: &PictureData, + current_surface_id: libva::VASurfaceID, + dpb: &Dpb>, + sps: &Sps, + pps: &Pps, +) -> anyhow::Result { + let curr_pic = fill_va_h264_pic(current_picture, current_surface_id, false); + + let mut refs: Vec<_> = dpb + .short_term_refs_iter() + .filter(|handle| { + let pic = handle.pic.borrow(); + !pic.nonexisting && !pic.is_second_field() + }) + .cloned() + .collect(); + + let mut va_refs = vec![]; + + for handle in &refs { + let surface_id = va_surface_id(&handle.reference); + let ref_pic = handle.pic.borrow(); + let pic = fill_va_h264_pic(&ref_pic, surface_id, true); + va_refs.push(pic); + } + + refs.clear(); + + let mut refs: Vec<_> = dpb + .long_term_refs_iter() + .filter(|handle| { + let pic = handle.pic.borrow(); + !pic.is_second_field() + }) + .cloned() + .collect(); + + for handle in &refs { + let surface_id = va_surface_id(&handle.reference); + let ref_pic = handle.pic.borrow(); + let pic = fill_va_h264_pic(&ref_pic, surface_id, true); + va_refs.push(pic); + } + + for _ in va_refs.len()..16 { + va_refs.push(build_invalid_va_h264_pic()); + } + + refs.clear(); + + let seq_fields = libva::H264SeqFields::new( + sps.chroma_format_idc as u32, + sps.separate_colour_plane_flag as u32, + sps.gaps_in_frame_num_value_allowed_flag as u32, + sps.frame_mbs_only_flag as u32, + sps.mb_adaptive_frame_field_flag as u32, + sps.direct_8x8_inference_flag as u32, + (sps.level_idc >= Level::L3_1) as u32, /* see A.3.3.2 */ + sps.log2_max_frame_num_minus4 as u32, + sps.pic_order_cnt_type as u32, + sps.log2_max_pic_order_cnt_lsb_minus4 as u32, + sps.delta_pic_order_always_zero_flag as u32, + ); + let interlaced = !sps.frame_mbs_only_flag as u32; + let picture_height_in_mbs_minus1 = ((sps.pic_height_in_map_units_minus1 + 1) << interlaced) - 1; + + let pic_fields = libva::H264PicFields::new( + pps.entropy_coding_mode_flag as u32, + pps.weighted_pred_flag as u32, + pps.weighted_bipred_idc as u32, + pps.transform_8x8_mode_flag as u32, + hdr.field_pic_flag as u32, + pps.constrained_intra_pred_flag as u32, + pps.bottom_field_pic_order_in_frame_present_flag as u32, + pps.deblocking_filter_control_present_flag as u32, + pps.redundant_pic_cnt_present_flag as u32, + (current_picture.nal_ref_idc != 0) as u32, + ); + + let va_refs = va_refs.try_into(); + let va_refs = match va_refs { + Ok(va_refs) => va_refs, + Err(_) => { + panic!("Bug: wrong number of references, expected 16"); + } + }; + + let pic_param = PictureParameterBufferH264::new( + curr_pic, + va_refs, + sps.pic_width_in_mbs_minus1, + picture_height_in_mbs_minus1, + sps.bit_depth_luma_minus8, + sps.bit_depth_chroma_minus8, + sps.max_num_ref_frames, + &seq_fields, + 0, /* FMO not supported by VA */ + 0, /* FMO not supported by VA */ + 0, /* FMO not supported by VA */ + pps.pic_init_qp_minus26, + pps.pic_init_qs_minus26, + pps.chroma_qp_index_offset, + pps.second_chroma_qp_index_offset, + &pic_fields, + hdr.frame_num, + ); + + Ok(BufferType::PictureParameter(PictureParameter::H264(pic_param))) +} + +fn fill_ref_pic_list( + ref_list_x: &[&DpbEntry>], +) -> [libva::PictureH264; 32] { + let mut va_pics = vec![]; + + for handle in ref_list_x { + let surface_id = va_surface_id(&handle.reference); + let ref_pic = handle.pic.borrow(); + let merge = matches!(ref_pic.field, Field::Frame); + let va_pic = fill_va_h264_pic(&ref_pic, surface_id, merge); + + va_pics.push(va_pic); + } + + for _ in va_pics.len()..32 { + va_pics.push(build_invalid_va_h264_pic()); + } + + let va_pics: [libva::PictureH264; 32] = match va_pics.try_into() { + Ok(va_pics) => va_pics, + Err(e) => panic!("Bug: wrong number of references, expected 32, got {:?}", e.len()), + }; + + va_pics +} + +fn build_slice_param( + hdr: &SliceHeader, + slice_size: usize, + ref_list_0: &[&DpbEntry>], + ref_list_1: &[&DpbEntry>], + sps: &Sps, + pps: &Pps, +) -> anyhow::Result { + let ref_list_0 = fill_ref_pic_list(ref_list_0); + let ref_list_1 = fill_ref_pic_list(ref_list_1); + let pwt = &hdr.pred_weight_table; + + let mut luma_weight_l0_flag = false; + let mut chroma_weight_l0_flag = false; + let mut luma_weight_l0 = [0i16; 32]; + let mut luma_offset_l0 = [0i16; 32]; + let mut chroma_weight_l0: [[i16; 2]; 32] = [[0i16; 2]; 32]; + let mut chroma_offset_l0: [[i16; 2]; 32] = [[0i16; 2]; 32]; + + let mut luma_weight_l1_flag = false; + let mut chroma_weight_l1_flag = false; + let mut luma_weight_l1 = [0i16; 32]; + let mut luma_offset_l1 = [0i16; 32]; + let mut chroma_weight_l1: [[i16; 2]; 32] = [[0i16; 2]; 32]; + let mut chroma_offset_l1: [[i16; 2]; 32] = [[0i16; 2]; 32]; + + let mut fill_l0 = false; + let mut fill_l1 = false; + + if pps.weighted_pred_flag && (hdr.slice_type.is_p() || hdr.slice_type.is_sp()) { + fill_l0 = true; + } else if pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b() { + fill_l0 = true; + fill_l1 = true; + } + + if fill_l0 { + luma_weight_l0_flag = true; + + for i in 0..=hdr.num_ref_idx_l0_active_minus1 as usize { + luma_weight_l0[i] = pwt.luma_weight_l0[i]; + luma_offset_l0[i] = i16::from(pwt.luma_offset_l0[i]); + } + + chroma_weight_l0_flag = sps.chroma_array_type() != 0; + if chroma_weight_l0_flag { + for i in 0..=hdr.num_ref_idx_l0_active_minus1 as usize { + for j in 0..2 { + chroma_weight_l0[i][j] = pwt.chroma_weight_l0[i][j]; + chroma_offset_l0[i][j] = i16::from(pwt.chroma_offset_l0[i][j]); + } + } + } + } + + if fill_l1 { + luma_weight_l1_flag = true; + + luma_weight_l1[..(hdr.num_ref_idx_l1_active_minus1 as usize + 1)].clone_from_slice( + &pwt.luma_weight_l1[..(hdr.num_ref_idx_l1_active_minus1 as usize + 1)], + ); + luma_offset_l1[..(hdr.num_ref_idx_l1_active_minus1 as usize + 1)].clone_from_slice( + &pwt.luma_offset_l1[..(hdr.num_ref_idx_l1_active_minus1 as usize + 1)], + ); + + chroma_weight_l1_flag = sps.chroma_array_type() != 0; + if chroma_weight_l1_flag { + for i in 0..=hdr.num_ref_idx_l1_active_minus1 as usize { + for j in 0..2 { + chroma_weight_l1[i][j] = pwt.chroma_weight_l1[i][j]; + chroma_offset_l1[i][j] = i16::from(pwt.chroma_offset_l1[i][j]); + } + } + } + } + + let slice_param = libva::SliceParameterBufferH264::new( + slice_size as u32, + 0, + libva::VA_SLICE_DATA_FLAG_ALL, + hdr.header_bit_size as u16, + hdr.first_mb_in_slice as u16, + hdr.slice_type as u8, + hdr.direct_spatial_mv_pred_flag as u8, + hdr.num_ref_idx_l0_active_minus1, + hdr.num_ref_idx_l1_active_minus1, + hdr.cabac_init_idc, + hdr.slice_qp_delta, + hdr.disable_deblocking_filter_idc, + hdr.slice_alpha_c0_offset_div2, + hdr.slice_beta_offset_div2, + ref_list_0, + ref_list_1, + pwt.luma_log2_weight_denom, + pwt.chroma_log2_weight_denom, + luma_weight_l0_flag as u8, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag as u8, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag as u8, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag as u8, + chroma_weight_l1, + chroma_offset_l1, + ); + + Ok(BufferType::SliceParameter(SliceParameter::H264(slice_param))) +} + +impl StatelessDecoderBackendPicture for VaapiBackend { + type Picture = VaapiPicture; +} + +impl StatelessH264DecoderBackend for VaapiBackend { + fn new_sequence(&mut self, sps: &Rc) -> StatelessBackendResult<()> { + self.new_sequence(sps) + } + + fn start_picture( + &mut self, + picture: &mut Self::Picture, + picture_data: &PictureData, + sps: &Sps, + pps: &Pps, + dpb: &Dpb, + hdr: &SliceHeader, + ) -> StatelessBackendResult<()> { + let context = &self.context; + + let surface_id = picture.surface().id(); + + let pic_param = build_pic_param(hdr, picture_data, surface_id, dpb, sps, pps)?; + let pic_param = + context.create_buffer(pic_param).context("while creating picture parameter buffer")?; + + let iq_matrix = build_iq_matrix(pps); + let iq_matrix = + context.create_buffer(iq_matrix).context("while creating IQ matrix buffer")?; + + picture.add_buffer(pic_param); + picture.add_buffer(iq_matrix); + + Ok(()) + } + + fn decode_slice( + &mut self, + picture: &mut Self::Picture, + slice: &Slice, + sps: &Sps, + pps: &Pps, + ref_pic_list0: &[&DpbEntry], + ref_pic_list1: &[&DpbEntry], + ) -> StatelessBackendResult<()> { + let context = &self.context; + + let slice_param = context + .create_buffer(build_slice_param( + &slice.header, + slice.nalu.size, + ref_pic_list0, + ref_pic_list1, + sps, + pps, + )?) + .context("while creating slice params buffer")?; + + picture.add_buffer(slice_param); + + let slice_data = context + .create_buffer(BufferType::SliceData(Vec::from(slice.nalu.as_ref()))) + .context("while creating slice data buffer")?; + + picture.add_buffer(slice_data); + + Ok(()) + } + + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult { + self.process_picture::(picture) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + Ok(VaapiPicture::new( + timestamp, + Rc::clone(&self.context), + alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, + )) + } + + fn new_field_picture( + &mut self, + timestamp: u64, + first_field: &Self::Handle, + ) -> NewPictureResult { + // Decode to the same surface as the first field picture. + Ok(first_field.borrow().new_picture_from_same_surface(timestamp)) + } +} + +impl StatelessDecoder> { + // Creates a new instance of the decoder using the VAAPI backend. + pub fn new_vaapi( + display: Rc, + blocking_mode: BlockingMode, + ) -> Result { + Self::new(VaapiBackend::new(display, false), blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::Display; + + use crate::bitstream_utils::NalIterator; + use crate::codec::h264::parser::Nalu; + use crate::decoder::stateless::h264::H264; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the vaapi decoder, in both blocking and non-blocking modes. + fn test_decoder_vaapi( + test: &TestStream, + output_format: DecodedFormat, + blocking_mode: BlockingMode, + ) { + let display = Display::open().unwrap(); + let decoder = StatelessDecoder::::new_vaapi::<()>(display, blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + NalIterator::::new(s), + f, + &mut simple_playback_loop_owned_frames, + output_format, + blocking_mode, + ) + }, + decoder, + test, + true, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_block() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_block() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_block() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_high_block() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_high_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P_HIGH, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_block() { + use crate::decoder::stateless::h264::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::Blocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::NonBlocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_interlaced_block() { + use crate::decoder::stateless::h264::tests::DECODE_TEST_25FPS_INTERLACED; + test_decoder_vaapi( + &DECODE_TEST_25FPS_INTERLACED, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_interlaced_nonblock() { + use crate::decoder::stateless::h264::tests::DECODE_TEST_25FPS_INTERLACED; + test_decoder_vaapi( + &DECODE_TEST_25FPS_INTERLACED, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h265.rs b/vendor/cros-codecs/src/decoder/stateless/h265.rs new file mode 100644 index 0000000..ddb9aa2 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h265.rs @@ -0,0 +1,1365 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(test)] +mod dummy; +#[cfg(feature = "vaapi")] +mod vaapi; + +use std::cell::RefCell; +use std::io::Cursor; +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; + +use crate::codec::h265::dpb::Dpb; +use crate::codec::h265::dpb::DpbEntry; +use crate::codec::h265::parser::Nalu; +use crate::codec::h265::parser::NaluType; +use crate::codec::h265::parser::Parser; +use crate::codec::h265::parser::Pps; +use crate::codec::h265::parser::ShortTermRefPicSet; +use crate::codec::h265::parser::Slice; +use crate::codec::h265::parser::SliceHeader; +use crate::codec::h265::parser::Sps; +use crate::codec::h265::picture::PictureData; +use crate::codec::h265::picture::Reference; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DecodingState; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::decoder::DecoderEvent; +use crate::decoder::StreamInfo; +use crate::Resolution; + +const MAX_DPB_SIZE: usize = 16; +/// Stateless backend methods specific to H.265. +pub trait StatelessH265DecoderBackend: + StatelessDecoderBackend + StatelessDecoderBackendPicture +{ + /// Called when a new SPS is parsed. + fn new_sequence(&mut self, sps: &Sps) -> StatelessBackendResult<()>; + + /// Called when the decoder determines that a frame or field was found. + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult; + + /// Called by the decoder for every frame or field found. + #[allow(clippy::too_many_arguments)] + fn begin_picture( + &mut self, + picture: &mut Self::Picture, + picture_data: &PictureData, + sps: &Sps, + pps: &Pps, + dpb: &Dpb, + rps: &RefPicSet, + slice: &Slice, + ) -> StatelessBackendResult<()>; + + /// Called to dispatch a decode operation to the backend. + #[allow(clippy::too_many_arguments)] + fn decode_slice( + &mut self, + picture: &mut Self::Picture, + slice: &Slice, + sps: &Sps, + pps: &Pps, + ref_pic_list0: &[Option>; 16], + ref_pic_list1: &[Option>; 16], + ) -> StatelessBackendResult<()>; + + /// Called when the decoder wants the backend to finish the decoding + /// operations for `picture`. At this point, `decode_slice` has been called + /// for all slices. + fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult; +} + +/// An entry in the Reference Picture Lists. Unlike H.264, H.265 can use the +/// current picture itself as a reference. +#[derive(Clone)] +pub enum RefPicListEntry { + CurrentPicture(PictureData), + DpbEntry(DpbEntry), +} + +enum BumpingType { + BeforeDecoding, + AfterDecoding, +} + +enum RenegotiationType<'a> { + CurrentSps, + NewSps(&'a Sps), +} + +/// Keeps track of the last values seen for negotiation purposes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct NegotiationInfo { + /// The current coded resolution + coded_resolution: Resolution, + general_profile_idc: u8, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + chroma_format_idc: u8, +} + +impl From<&Sps> for NegotiationInfo { + fn from(sps: &Sps) -> Self { + NegotiationInfo { + coded_resolution: Resolution { width: sps.width().into(), height: sps.height().into() }, + general_profile_idc: sps.profile_tier_level.general_profile_idc, + bit_depth_luma_minus8: sps.bit_depth_luma_minus8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8, + chroma_format_idc: sps.chroma_format_idc, + } + } +} + +/// The RefPicSet data, derived once per picture. +#[derive(Clone, Debug)] +pub struct RefPicSet { + curr_delta_poc_msb_present_flag: [bool; MAX_DPB_SIZE], + foll_delta_poc_msb_present_flag: [bool; MAX_DPB_SIZE], + + num_poc_st_curr_before: usize, + num_poc_st_curr_after: usize, + num_poc_st_foll: usize, + num_poc_lt_curr: usize, + num_poc_lt_foll: usize, + + poc_st_curr_before: [i32; MAX_DPB_SIZE], + poc_st_curr_after: [i32; MAX_DPB_SIZE], + poc_st_foll: [i32; MAX_DPB_SIZE], + poc_lt_curr: [i32; MAX_DPB_SIZE], + poc_lt_foll: [i32; MAX_DPB_SIZE], + + ref_pic_set_lt_curr: [Option>; MAX_DPB_SIZE], + ref_pic_set_st_curr_after: [Option>; MAX_DPB_SIZE], + ref_pic_set_st_curr_before: [Option>; MAX_DPB_SIZE], + ref_pic_set_st_foll: [Option>; MAX_DPB_SIZE], + ref_pic_set_lt_foll: [Option>; MAX_DPB_SIZE], +} + +impl RefPicSet +where + T: Clone, +{ + // See 8.3.4. + // Builds the reference picture list for `hdr` for P and B slices. + fn build_ref_pic_lists( + &self, + hdr: &SliceHeader, + pps: &Pps, + cur_pic: &PictureData, + ) -> anyhow::Result> { + let mut ref_pic_lists = ReferencePicLists::default(); + + // I slices do not use inter prediction. + if !hdr.type_.is_p() && !hdr.type_.is_b() { + return Ok(ref_pic_lists); + } + + if self.num_poc_st_curr_before == 0 + && self.num_poc_st_curr_after == 0 + && self.num_poc_lt_curr == 0 + && pps.scc_extension_flag + && !pps.scc_extension.curr_pic_ref_enabled_flag + { + // Let's try and keep going, if it is a broken stream then maybe it + // will sort itself out as we go. In any case, we must not loop + // infinitely here. + log::error!("Bug or broken stream: out of pictures and can't build ref pic lists."); + return Ok(ref_pic_lists); + } + + let rplm = &hdr.ref_pic_list_modification; + + let num_rps_curr_temp_list0 = + std::cmp::max(u32::from(hdr.num_ref_idx_l0_active_minus1) + 1, hdr.num_pic_total_curr); + + // This could be simplified using a Vec, but lets not change the + // algorithm from the spec too much. + let mut ref_pic_list_temp0: [Option>; MAX_DPB_SIZE] = Default::default(); + + // Equation 8-8 + let mut r_idx = 0; + assert!(num_rps_curr_temp_list0 as usize <= MAX_DPB_SIZE); + while r_idx < num_rps_curr_temp_list0 { + let mut i = 0; + while i < self.num_poc_st_curr_before && r_idx < num_rps_curr_temp_list0 { + ref_pic_list_temp0[r_idx as usize] = + self.ref_pic_set_st_curr_before[i].clone().map(RefPicListEntry::DpbEntry); + + i += 1; + r_idx += 1; + } + + let mut i = 0; + while i < self.num_poc_st_curr_after && r_idx < num_rps_curr_temp_list0 { + ref_pic_list_temp0[r_idx as usize] = + self.ref_pic_set_st_curr_after[i].clone().map(RefPicListEntry::DpbEntry); + + i += 1; + r_idx += 1; + } + + let mut i = 0; + while i < self.num_poc_lt_curr && r_idx < num_rps_curr_temp_list0 { + ref_pic_list_temp0[r_idx as usize] = + self.ref_pic_set_lt_curr[i].clone().map(RefPicListEntry::DpbEntry); + + i += 1; + r_idx += 1; + } + + if pps.scc_extension.curr_pic_ref_enabled_flag { + ref_pic_list_temp0[r_idx as usize] = + Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); + + r_idx += 1; + } + } + + // Equation 8-9 + for r_idx in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { + let entry = if rplm.ref_pic_list_modification_flag_l0 { + let idx = rplm.list_entry_l0[r_idx]; + ref_pic_list_temp0[idx as usize].clone() + } else { + ref_pic_list_temp0[r_idx].clone() + }; + + ref_pic_lists.ref_pic_list0[r_idx] = entry; + } + + if pps.scc_extension.curr_pic_ref_enabled_flag + && !rplm.ref_pic_list_modification_flag_l0 + && num_rps_curr_temp_list0 > (u32::from(hdr.num_ref_idx_l0_active_minus1) + 1) + { + ref_pic_lists.ref_pic_list0[r_idx as usize] = + Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); + } + + if hdr.type_.is_b() { + let mut ref_pic_list_temp1: [Option>; MAX_DPB_SIZE] = + Default::default(); + + let num_rps_curr_temp_list1 = std::cmp::max( + u32::from(hdr.num_ref_idx_l1_active_minus1) + 1, + hdr.num_pic_total_curr, + ); + + // Equation 8-10 + let mut r_idx = 0; + assert!(num_rps_curr_temp_list1 as usize <= MAX_DPB_SIZE); + while r_idx < num_rps_curr_temp_list1 { + let mut i = 0; + while i < self.num_poc_st_curr_after && r_idx < num_rps_curr_temp_list1 { + ref_pic_list_temp1[r_idx as usize] = + self.ref_pic_set_st_curr_after[i].clone().map(RefPicListEntry::DpbEntry); + i += 1; + r_idx += 1; + } + + let mut i = 0; + while i < self.num_poc_st_curr_before && r_idx < num_rps_curr_temp_list1 { + ref_pic_list_temp1[r_idx as usize] = + self.ref_pic_set_st_curr_before[i].clone().map(RefPicListEntry::DpbEntry); + i += 1; + r_idx += 1; + } + + let mut i = 0; + while i < self.num_poc_lt_curr && r_idx < num_rps_curr_temp_list1 { + ref_pic_list_temp1[r_idx as usize] = + self.ref_pic_set_lt_curr[i].clone().map(RefPicListEntry::DpbEntry); + i += 1; + r_idx += 1; + } + + if pps.scc_extension.curr_pic_ref_enabled_flag { + ref_pic_list_temp1[r_idx as usize] = + Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); + + r_idx += 1; + } + } + + // Equation 8-11 + for r_idx in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { + let entry = if rplm.ref_pic_list_modification_flag_l1 { + let idx = rplm.list_entry_l1[r_idx]; + ref_pic_list_temp1[idx as usize].clone() + } else { + ref_pic_list_temp1[r_idx].clone() + }; + + ref_pic_lists.ref_pic_list1[r_idx] = entry; + } + } + + Ok(ref_pic_lists) + } +} + +impl Default for RefPicSet { + fn default() -> Self { + Self { + curr_delta_poc_msb_present_flag: Default::default(), + foll_delta_poc_msb_present_flag: Default::default(), + num_poc_st_curr_before: Default::default(), + num_poc_st_curr_after: Default::default(), + num_poc_st_foll: Default::default(), + num_poc_lt_curr: Default::default(), + num_poc_lt_foll: Default::default(), + poc_st_curr_before: Default::default(), + poc_st_curr_after: Default::default(), + poc_st_foll: Default::default(), + poc_lt_curr: Default::default(), + poc_lt_foll: Default::default(), + ref_pic_set_lt_curr: Default::default(), + ref_pic_set_st_curr_after: Default::default(), + ref_pic_set_st_curr_before: Default::default(), + ref_pic_set_st_foll: Default::default(), + ref_pic_set_lt_foll: Default::default(), + } + } +} + +/// State of the picture being currently decoded. +/// +/// Stored between calls to [`StatelessDecoder::handle_slice`] that belong to the same picture. +struct CurrentPicState { + /// Data for the current picture as extracted from the stream. + pic: PictureData, + /// Backend-specific data for that picture. + backend_pic: P, + /// List of reference pictures, used once per slice. + ref_pic_lists: ReferencePicLists, +} + +/// All the reference picture lists used to decode a stream. +struct ReferencePicLists { + /// Reference picture list 0 for P and B slices. Retains the same meaning as + /// in the specification. Points into the pictures stored in the DPB. + /// Derived once per slice. + ref_pic_list0: [Option>; MAX_DPB_SIZE], + /// Reference picture list 1 for B slices. Retains the same meaning as in + /// the specification. Points into the pictures stored in the DPB. Derived + /// once per slice. + ref_pic_list1: [Option>; MAX_DPB_SIZE], +} + +impl Default for ReferencePicLists { + fn default() -> Self { + Self { ref_pic_list0: Default::default(), ref_pic_list1: Default::default() } + } +} + +pub struct H265DecoderState { + /// A parser to extract bitstream metadata + parser: Parser, + + /// Keeps track of the last values seen for negotiation purposes. + negotiation_info: NegotiationInfo, + /// The set of reference pictures. + rps: RefPicSet, + + /// The decoded picture buffer + dpb: Dpb, + + /// The current active SPS id. + cur_sps_id: u8, + + /// Used to identify first picture in decoding order or first picture that + /// follows an EOS NALU. + first_picture_after_eos: bool, + + /// Whether this is the first picture in the bitstream in decoding order. + first_picture_in_bitstream: bool, + // Same as PrevTid0Pic in the specification. + prev_tid_0_pic: Option, + + /// A H.265 syntax element. + max_pic_order_cnt_lsb: i32, + /// The value of NoRaslOutputFlag for the last IRAP picture. + irap_no_rasl_output_flag: bool, + + /// We keep track of the last independent header so we can copy that into + /// dependent slices. + last_independent_slice_header: Option, + + /// The picture currently being decoded. We need to preserve it between + /// calls to `decode` because multiple slices will be processed in different + /// calls to `decode`. + current_pic: Option>, + + pending_pps: Vec>, +} + +impl Default for H265DecoderState +where + H: DecodedHandle + Clone, +{ + fn default() -> Self { + H265DecoderState { + parser: Default::default(), + negotiation_info: Default::default(), + rps: Default::default(), + dpb: Default::default(), + cur_sps_id: Default::default(), + first_picture_after_eos: true, + first_picture_in_bitstream: true, + prev_tid_0_pic: Default::default(), + max_pic_order_cnt_lsb: Default::default(), + irap_no_rasl_output_flag: Default::default(), + last_independent_slice_header: Default::default(), + current_pic: Default::default(), + pending_pps: Default::default(), + } + } +} + +/// [`StatelessCodec`] structure to use in order to create a H.265 stateless decoder. +/// +/// # Accepted input +/// +/// A decoder using this codec processes exactly one NAL unit of input per call to +/// [`StatelessDecoder::decode`], and returns the number of bytes until the end of this NAL unit. +/// This makes it possible to call [`Decode`](StatelessDecoder::decode) repeatedly on some unsplit +/// Annex B stream and shrinking it by the number of bytes processed after each call, until the +/// stream ends up being empty. +pub struct H265; + +impl StatelessCodec for H265 { + type FormatInfo = Sps; + type DecoderState = H265DecoderState; +} + +impl StatelessDecoder +where + B: StatelessH265DecoderBackend, + B::Handle: Clone, +{ + /// Whether the stream parameters have changed, indicating that a negotiation window has opened. + fn negotiation_possible( + sps: &Sps, + dpb: &Dpb, + old_negotiation_info: &NegotiationInfo, + ) -> bool { + let negotiation_info = NegotiationInfo::from(sps); + let max_dpb_size = std::cmp::min(sps.max_dpb_size(), 16); + let prev_max_dpb_size = dpb.max_num_pics(); + + *old_negotiation_info != negotiation_info || prev_max_dpb_size != max_dpb_size + } + + /// Apply the parameters of `sps` to the decoder. + fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> { + self.drain()?; + self.codec.negotiation_info = NegotiationInfo::from(sps); + + let max_dpb_size = std::cmp::min(sps.max_dpb_size(), 16); + self.codec.dpb.set_max_num_pics(max_dpb_size); + self.coded_resolution = + Resolution { width: u32::from(sps.width()), height: u32::from(sps.height()) }; + Ok(()) + } + + // See 8.3.2, Note 2. + fn st_ref_pic_set<'a>(hdr: &'a SliceHeader, sps: &'a Sps) -> &'a ShortTermRefPicSet { + if hdr.curr_rps_idx == sps.num_short_term_ref_pic_sets { + &hdr.short_term_ref_pic_set + } else { + &sps.short_term_ref_pic_set[usize::from(hdr.curr_rps_idx)] + } + } + + // See 8.3.2. + fn decode_rps( + &mut self, + slice: &Slice, + sps: &Sps, + cur_pic: &PictureData, + ) -> anyhow::Result<()> { + let hdr = &slice.header; + + if cur_pic.nalu_type.is_irap() && cur_pic.no_rasl_output_flag { + self.codec.dpb.mark_all_as_unused_for_ref(); + } + + if slice.nalu.header.type_.is_idr() { + self.codec.rps.poc_st_curr_before = Default::default(); + self.codec.rps.poc_st_curr_after = Default::default(); + self.codec.rps.poc_st_foll = Default::default(); + self.codec.rps.poc_lt_curr = Default::default(); + self.codec.rps.poc_lt_foll = Default::default(); + + self.codec.rps.num_poc_st_curr_before = 0; + self.codec.rps.num_poc_st_curr_after = 0; + self.codec.rps.num_poc_st_foll = 0; + self.codec.rps.num_poc_lt_curr = 0; + self.codec.rps.num_poc_lt_foll = 0; + } else { + let curr_st_rps = Self::st_ref_pic_set(hdr, sps); + let mut j = 0; + let mut k = 0; + for i in 0..usize::from(curr_st_rps.num_negative_pics) { + let poc = cur_pic.pic_order_cnt_val + curr_st_rps.delta_poc_s0[i]; + + if curr_st_rps.used_by_curr_pic_s0[i] { + self.codec.rps.poc_st_curr_before[j] = poc; + j += 1; + } else { + self.codec.rps.poc_st_foll[k] = poc; + k += 1; + } + } + + self.codec.rps.num_poc_st_curr_before = j as _; + + let mut j = 0; + for i in 0..usize::from(curr_st_rps.num_positive_pics) { + let poc = cur_pic.pic_order_cnt_val + curr_st_rps.delta_poc_s1[i]; + + if curr_st_rps.used_by_curr_pic_s1[i] { + self.codec.rps.poc_st_curr_after[j] = poc; + j += 1; + } else { + self.codec.rps.poc_st_foll[k] = poc; + k += 1; + } + } + + self.codec.rps.num_poc_st_curr_after = j as _; + self.codec.rps.num_poc_st_foll = k as _; + + let mut j = 0; + let mut k = 0; + for i in 0..usize::from(hdr.num_long_term_sps + hdr.num_long_term_pics) { + let mut poc_lt = hdr.poc_lsb_lt[i] as i32; + if hdr.delta_poc_msb_present_flag[i] { + poc_lt += cur_pic.pic_order_cnt_val; + let delta_poc = + hdr.delta_poc_msb_cycle_lt[i] as i32 * self.codec.max_pic_order_cnt_lsb; + + poc_lt -= delta_poc; + poc_lt -= cur_pic.pic_order_cnt_val & (self.codec.max_pic_order_cnt_lsb - 1); + } + + if hdr.used_by_curr_pic_lt[i] { + self.codec.rps.poc_lt_curr[j] = poc_lt; + self.codec.rps.curr_delta_poc_msb_present_flag[j] = + hdr.delta_poc_msb_present_flag[i]; + j += 1; + } else { + self.codec.rps.poc_lt_foll[k] = poc_lt; + self.codec.rps.foll_delta_poc_msb_present_flag[k] = + hdr.delta_poc_msb_present_flag[i]; + k += 1; + } + } + + self.codec.rps.num_poc_lt_curr = j as _; + self.codec.rps.num_poc_lt_foll = k as _; + } + + self.derive_and_mark_rps()?; + Ok(()) + } + + // See the derivation process in the second half of 8.3.2. + fn derive_and_mark_rps(&mut self) -> anyhow::Result<()> { + let max_pic_order_cnt_lsb = self.codec.max_pic_order_cnt_lsb; + + // Equation 8-6 + for i in 0..self.codec.rps.num_poc_lt_curr { + if !self.codec.rps.curr_delta_poc_msb_present_flag[i] { + let poc = self.codec.rps.poc_lt_curr[i]; + let mask = max_pic_order_cnt_lsb - 1; + let reference = self.codec.dpb.find_ref_by_poc_masked(poc, mask); + + if reference.is_none() { + log::warn!("No reference found for poc {} and mask {}", poc, mask); + } + + self.codec.rps.ref_pic_set_lt_curr[i] = reference; + } else { + let poc = self.codec.rps.poc_lt_curr[i]; + let reference = self.codec.dpb.find_ref_by_poc(poc); + + if reference.is_none() { + log::warn!("No reference found for poc {}", poc); + } + + self.codec.rps.ref_pic_set_lt_curr[i] = reference; + } + } + + for i in 0..self.codec.rps.num_poc_lt_foll { + if !self.codec.rps.foll_delta_poc_msb_present_flag[i] { + let poc = self.codec.rps.poc_lt_foll[i]; + let mask = max_pic_order_cnt_lsb - 1; + let reference = self.codec.dpb.find_ref_by_poc_masked(poc, mask); + + if reference.is_none() { + log::warn!("No reference found for poc {} and mask {}", poc, mask); + } + + self.codec.rps.ref_pic_set_lt_foll[i] = reference; + } else { + let poc = self.codec.rps.poc_lt_foll[i]; + let reference = self.codec.dpb.find_ref_by_poc(poc); + + if reference.is_none() { + log::warn!("No reference found for poc {}", poc); + } + + self.codec.rps.ref_pic_set_lt_foll[i] = reference; + } + } + + for pic in self.codec.rps.ref_pic_set_lt_curr.iter().flatten() { + pic.0.borrow_mut().set_reference(Reference::LongTerm); + } + + for pic in self.codec.rps.ref_pic_set_lt_foll.iter().flatten() { + pic.0.borrow_mut().set_reference(Reference::LongTerm); + } + + // Equation 8-7 + for i in 0..self.codec.rps.num_poc_st_curr_before { + let poc = self.codec.rps.poc_st_curr_before[i]; + let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); + + if reference.is_none() { + log::warn!("No reference found for poc {}", poc); + } + + self.codec.rps.ref_pic_set_st_curr_before[i] = reference; + } + + for i in 0..self.codec.rps.num_poc_st_curr_after { + let poc = self.codec.rps.poc_st_curr_after[i]; + let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); + + if reference.is_none() { + log::warn!("No reference found for poc {}", poc); + } + + self.codec.rps.ref_pic_set_st_curr_after[i] = reference; + } + + for i in 0..self.codec.rps.num_poc_st_foll { + let poc = self.codec.rps.poc_st_foll[i]; + let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); + + if reference.is_none() { + log::warn!("No reference found for poc {}", poc); + } + + self.codec.rps.ref_pic_set_st_foll[i] = reference; + } + + // 4. All reference pictures in the DPB that are not included in + // RefPicSetLtCurr, RefPicSetLtFoll, RefPicSetStCurrBefore, + // RefPicSetStCurrAfter, or RefPicSetStFoll and have nuh_layer_id equal + // to currPicLayerId are marked as "unused for reference" + for dpb_pic in self.codec.dpb.entries() { + let find_predicate = |p: &Option>| match p { + Some(p) => p.0.borrow().pic_order_cnt_val == dpb_pic.0.borrow().pic_order_cnt_val, + None => false, + }; + + if !self.codec.rps.ref_pic_set_lt_curr[0..self.codec.rps.num_poc_lt_curr] + .iter() + .any(find_predicate) + && !self.codec.rps.ref_pic_set_lt_foll[0..self.codec.rps.num_poc_lt_foll] + .iter() + .any(find_predicate) + && !self.codec.rps.ref_pic_set_st_curr_after + [0..self.codec.rps.num_poc_st_curr_after] + .iter() + .any(find_predicate) + && !self.codec.rps.ref_pic_set_st_curr_before + [0..self.codec.rps.num_poc_st_curr_before] + .iter() + .any(find_predicate) + && !self.codec.rps.ref_pic_set_st_foll[0..self.codec.rps.num_poc_st_foll] + .iter() + .any(find_predicate) + { + dpb_pic.0.borrow_mut().set_reference(Reference::None); + } + } + + let total_rps_len = self.codec.rps.ref_pic_set_lt_curr[0..self.codec.rps.num_poc_lt_curr] + .len() + + self.codec.rps.ref_pic_set_lt_foll[0..self.codec.rps.num_poc_lt_foll].len() + + self.codec.rps.ref_pic_set_st_curr_after[0..self.codec.rps.num_poc_st_curr_after] + .len() + + self.codec.rps.ref_pic_set_st_curr_before[0..self.codec.rps.num_poc_st_curr_before] + .len() + + self.codec.rps.ref_pic_set_st_foll[0..self.codec.rps.num_poc_st_foll].len(); + + let dpb_len = self.codec.dpb.entries().len(); + if dpb_len != total_rps_len { + log::warn!( + "The total RPS length {} is not the same as the DPB length {}", + total_rps_len, + dpb_len + ); + log::warn!("A reference pic may be in more than one RPS list. This is against the specification. See 8.3.2. NOTE 5") + } + + // According to Chromium, unavailable reference pictures are handled by + // the accelerators internally. + Ok(()) + } + + /// Drain the decoder, processing all pending frames. + fn drain(&mut self) -> anyhow::Result<()> { + log::debug!("Draining the decoder"); + + // Finish the current picture if there is one pending. + if let Some(cur_pic) = self.codec.current_pic.take() { + self.finish_picture(cur_pic)?; + } + + let pics = self.codec.dpb.drain(); + + log::debug!( + "Adding POCs {:?} to the ready queue while draining", + pics.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::>() + ); + + log::trace!("{:#?}", pics.iter().map(|p| p.0.borrow()).collect::>()); + + self.ready_queue.extend(pics.into_iter().map(|h| h.1)); + self.codec.dpb.clear(); + + Ok(()) + } + + fn clear_ref_lists(&mut self) { + if let Some(pic) = self.codec.current_pic.as_mut() { + pic.ref_pic_lists = Default::default(); + } + + self.codec.rps.ref_pic_set_lt_curr = Default::default(); + self.codec.rps.ref_pic_set_st_curr_after = Default::default(); + self.codec.rps.ref_pic_set_st_curr_before = Default::default(); + + self.codec.rps.num_poc_lt_curr = Default::default(); + self.codec.rps.num_poc_lt_foll = Default::default(); + self.codec.rps.num_poc_st_curr_after = Default::default(); + self.codec.rps.num_poc_st_curr_before = Default::default(); + self.codec.rps.num_poc_st_foll = Default::default(); + } + + /// Bumps the DPB if needed. + fn bump_as_needed( + &mut self, + bumping_type: BumpingType, + ) -> anyhow::Result>> { + let mut pics = vec![]; + + let needs_bumping = match bumping_type { + BumpingType::BeforeDecoding => Dpb::::needs_bumping, + BumpingType::AfterDecoding => Dpb::::needs_additional_bumping, + }; + + let sps = self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS id")?; + + while needs_bumping(&mut self.codec.dpb, sps) { + match self.codec.dpb.bump(false) { + Some(pic) => pics.push(pic), + None => return Ok(pics), + } + } + + Ok(pics) + } + + // See C.5.2.2 + fn update_dpb_before_decoding(&mut self, cur_pic: &PictureData) -> anyhow::Result<()> { + if cur_pic.nalu_type.is_irap() + && cur_pic.no_rasl_output_flag + && !self.codec.first_picture_after_eos + { + if cur_pic.no_output_of_prior_pics_flag { + self.codec.dpb.clear(); + } else { + self.drain()?; + } + } else { + self.codec.dpb.remove_unused(); + let bumped = self.bump_as_needed(BumpingType::BeforeDecoding)?; + + log::debug!( + "Adding POCs {:?} to the ready queue before decoding", + bumped.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::>() + ); + + log::trace!("{:#?}", bumped.iter().map(|p| p.0.borrow()).collect::>()); + + let bumped = bumped.into_iter().map(|p| p.1).collect::>(); + self.ready_queue.extend(bumped); + } + + Ok(()) + } + + /// Called once per picture to start it. + #[allow(clippy::type_complexity)] + fn begin_picture( + &mut self, + timestamp: u64, + slice: &Slice, + alloc_cb: &mut dyn FnMut() -> Option<::Frame>, + ) -> Result>, DecodeError> { + self.update_current_set_ids(slice.header.pic_parameter_set_id)?; + self.renegotiate_if_needed(RenegotiationType::CurrentSps)?; + // We renegotiated and must return the NALU and wait. + if matches!(self.decoding_state, DecodingState::AwaitingFormat(_)) { + return Err(DecodeError::CheckEvents); + } + + let mut backend_pic = self.backend.new_picture(timestamp, alloc_cb)?; + + let pic = PictureData::new_from_slice( + slice, + self.codec.first_picture_in_bitstream, + self.codec.first_picture_after_eos, + self.codec.prev_tid_0_pic.as_ref(), + self.codec.max_pic_order_cnt_lsb, + ); + + self.codec.first_picture_after_eos = false; + self.codec.first_picture_in_bitstream = false; + + if pic.nalu_type.is_irap() { + self.codec.irap_no_rasl_output_flag = pic.no_rasl_output_flag; + } else if pic.nalu_type.is_rasl() && self.codec.irap_no_rasl_output_flag { + // NOTE – All RASL pictures are leading pictures of an associated + // BLA or CRA picture. When the associated IRAP picture has + // NoRaslOutputFlag equal to 1, the RASL picture is not output and + // may not be correctly decodable, as the RASL picture may contain + // references to pictures that are not present in the bitstream. + // RASL pictures are not used as reference pictures for the decoding + // process of non-RASL pictures. + log::debug!( + "Dropping POC {}, as it may not be decodable according to the specification", + pic.pic_order_cnt_val + ); + + return Ok(None); + } + + log::debug!("Decode picture POC {}", pic.pic_order_cnt_val); + + let pps = self + .codec + .parser + .get_pps(slice.header.pic_parameter_set_id) + .context("invalid PPS ID")? + .clone(); + + self.decode_rps(slice, &pps.sps, &pic)?; + self.update_dpb_before_decoding(&pic)?; + + self.backend.begin_picture( + &mut backend_pic, + &pic, + pps.sps.as_ref(), + &pps, + &self.codec.dpb, + &self.codec.rps, + slice, + )?; + + Ok(Some(CurrentPicState { pic, backend_pic, ref_pic_lists: Default::default() })) + } + + fn update_current_set_ids(&mut self, pps_id: u8) -> anyhow::Result<()> { + let pps = self.codec.parser.get_pps(pps_id).context("Invalid PPS")?; + + self.codec.cur_sps_id = pps.seq_parameter_set_id; + Ok(()) + } + + /// Handle a slice. Called once per slice NALU. + fn handle_slice( + &mut self, + pic: &mut CurrentPicState, + slice: &Slice, + ) -> anyhow::Result<()> { + // A dependent slice may refer to a previous SPS which + // is not the one currently in use. + self.update_current_set_ids(slice.header.pic_parameter_set_id)?; + + let pps = self + .codec + .parser + .get_pps(slice.header.pic_parameter_set_id) + .context("invalid PPS ID")?; + let sps = pps.sps.as_ref(); + + pic.ref_pic_lists = self.codec.rps.build_ref_pic_lists(&slice.header, pps, &pic.pic)?; + + // Make sure that no negotiation is possible mid-picture. How could it? + // We'd lose the context with the previous slices on it. + if Self::negotiation_possible(sps, &self.codec.dpb, &self.codec.negotiation_info) { + anyhow::bail!("invalid stream: mid-frame format negotiation requested"); + } + + self.backend.decode_slice( + &mut pic.backend_pic, + slice, + sps, + pps, + &pic.ref_pic_lists.ref_pic_list0, + &pic.ref_pic_lists.ref_pic_list1, + )?; + + Ok(()) + } + + fn finish_picture( + &mut self, + pic: CurrentPicState, + ) -> anyhow::Result<()> { + log::debug!("Finishing picture POC {:?}", pic.pic.pic_order_cnt_val); + + // Submit the picture to the backend. + let handle = self.submit_picture(pic.backend_pic)?; + let pic = pic.pic; + + // 8.3.1 + if pic.valid_for_prev_tid0_pic { + self.codec.prev_tid_0_pic = Some(pic.clone()); + } + + self.clear_ref_lists(); + + // First store the current picture in the DPB, only then we should + // decide whether to bump. + self.codec + .dpb + .store_picture(Rc::new(RefCell::new(pic)), handle) + .map_err(|err| anyhow!(err))?; + let bumped = self.bump_as_needed(BumpingType::AfterDecoding)?; + + log::debug!( + "Adding POCs {:?} to the ready queue after decoding", + bumped.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::>() + ); + + log::trace!("{:#?}", bumped.iter().map(|p| p.0.borrow()).collect::>()); + + let bumped = bumped.into_iter().map(|p| p.1).collect::>(); + self.ready_queue.extend(bumped); + + Ok(()) + } + + fn renegotiate_if_needed( + &mut self, + renegotiation_type: RenegotiationType, + ) -> anyhow::Result<()> { + let sps = match renegotiation_type { + RenegotiationType::CurrentSps => { + self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS")? + } + RenegotiationType::NewSps(sps) => sps, + }; + + if Self::negotiation_possible(sps, &self.codec.dpb, &self.codec.negotiation_info) { + // Make sure all the frames we decoded so far are in the ready queue. + self.drain()?; + let sps = match renegotiation_type { + RenegotiationType::CurrentSps => { + self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS")? + } + RenegotiationType::NewSps(sps) => sps, + }; + self.backend.new_sequence(sps)?; + self.await_format_change(sps.clone()); + } + + Ok(()) + } + + fn process_nalu( + &mut self, + timestamp: u64, + nalu: Nalu, + alloc_cb: &mut dyn FnMut() -> Option<::Frame>, + ) -> Result<(), DecodeError> { + log::debug!("Processing NALU {:?}, length is {}", nalu.header.type_, nalu.size); + + match nalu.header.type_ { + NaluType::VpsNut => { + self.codec + .parser + .parse_vps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + } + NaluType::SpsNut => { + let sps = self + .codec + .parser + .parse_sps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + self.codec.max_pic_order_cnt_lsb = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); + + let pending_pps = std::mem::take(&mut self.codec.pending_pps); + + // Try parsing the PPS again. + for pps in pending_pps.into_iter() { + if self.codec.parser.parse_pps(&pps).is_err() { + // Failed to parse PPS add it again to pending + self.codec.pending_pps.push(pps); + } + } + } + + NaluType::PpsNut => { + if self.codec.parser.parse_pps(&nalu).is_err() { + self.codec.pending_pps.push(nalu.into_owned()) + } + } + + NaluType::BlaWLp + | NaluType::BlaWRadl + | NaluType::BlaNLp + | NaluType::IdrWRadl + | NaluType::IdrNLp + | NaluType::TrailN + | NaluType::TrailR + | NaluType::TsaN + | NaluType::TsaR + | NaluType::StsaN + | NaluType::StsaR + | NaluType::RadlN + | NaluType::RadlR + | NaluType::RaslN + | NaluType::RaslR + | NaluType::CraNut => { + let mut slice = self + .codec + .parser + .parse_slice_header(nalu) + .map_err(|err| DecodeError::ParseFrameError(err))?; + + let first_slice_segment_in_pic_flag = slice.header.first_slice_segment_in_pic_flag; + + if slice.header.dependent_slice_segment_flag { + let previous_independent_header = self.codec.last_independent_slice_header.as_ref().ok_or(anyhow!("Cannot process an dependent slice without first processing and independent one"))?.clone(); + slice + .replace_header(previous_independent_header) + .map_err(|err| DecodeError::ParseFrameError(err))?; + } else { + self.codec.last_independent_slice_header = Some(slice.header.clone()); + } + + let cur_pic = match self.codec.current_pic.take() { + // No current picture, start a new one. + None => self.begin_picture(timestamp, &slice, alloc_cb)?, + Some(cur_pic) if first_slice_segment_in_pic_flag => { + self.finish_picture(cur_pic)?; + self.begin_picture(timestamp, &slice, alloc_cb)? + } + Some(cur_pic) => Some(cur_pic), + }; + + // Picture may have been dropped during begin_picture() + if let Some(mut cur_pic) = cur_pic { + self.handle_slice(&mut cur_pic, &slice)?; + self.codec.current_pic = Some(cur_pic); + } + } + + NaluType::EosNut => { + self.codec.first_picture_after_eos = true; + } + + NaluType::EobNut => { + self.codec.first_picture_in_bitstream = true; + } + + other => { + log::debug!("Unsupported NAL unit type {:?}", other,); + } + } + + Ok(()) + } + + /// Submits the picture to the accelerator. + fn submit_picture(&mut self, backend_pic: B::Picture) -> Result { + let handle = self.backend.submit_picture(backend_pic)?; + + if self.blocking_mode == BlockingMode::Blocking { + handle.sync()?; + } + + Ok(handle) + } +} + +impl StatelessVideoDecoder for StatelessDecoder +where + B: StatelessH265DecoderBackend, + B::Handle: Clone + 'static, +{ + type Handle = B::Handle; + + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result { + let mut cursor = Cursor::new(bitstream); + let nalu = Nalu::next(&mut cursor).map_err(|err| DecodeError::ParseFrameError(err))?; + + if nalu.header.type_ == NaluType::SpsNut { + let sps = self + .codec + .parser + .parse_sps(&nalu) + .map_err(|err| DecodeError::ParseFrameError(err))? + .clone(); + if matches!(self.decoding_state, DecodingState::AwaitingStreamInfo) { + // If more SPS come along we will renegotiate in begin_picture(). + self.renegotiate_if_needed(RenegotiationType::NewSps(&sps))?; + } else if matches!(self.decoding_state, DecodingState::Reset) { + // We can resume decoding since the decoding parameters have not changed. + self.decoding_state = DecodingState::Decoding; + } + } else if matches!(self.decoding_state, DecodingState::Reset) { + let mut cursor = Cursor::new(bitstream); + + while let Ok(nalu) = Nalu::next(&mut cursor) { + // In the Reset state we can resume decoding from any key frame. + if nalu.header.type_.is_idr() { + self.decoding_state = DecodingState::Decoding; + break; + } + } + } + + let nalu_len = nalu.offset + nalu.size; + + match &mut self.decoding_state { + // Process parameter sets, but skip input until we get information + // from the stream. + DecodingState::AwaitingStreamInfo | DecodingState::Reset => { + if matches!( + nalu.header.type_, + NaluType::VpsNut | NaluType::SpsNut | NaluType::PpsNut + ) { + self.process_nalu(timestamp, nalu, alloc_cb)?; + } + } + // Ask the client to confirm the format before we can process this. + DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + DecodingState::Decoding => { + self.process_nalu(timestamp, nalu, alloc_cb)?; + } + } + + Ok(nalu_len) + } + + fn flush(&mut self) -> Result<(), DecodeError> { + self.drain()?; + self.decoding_state = DecodingState::Reset; + + Ok(()) + } + + fn next_event(&mut self) -> Option> { + self.query_next_event(|decoder, sps| { + // Apply the SPS settings to the decoder so we don't enter the AwaitingFormat state + // on the next decode() call. + // TODO: unwrap this for now, but ideally change this closure to return Result + decoder.apply_sps(sps).unwrap(); + }) + } + + fn stream_info(&self) -> Option<&StreamInfo> { + self.backend.stream_info() + } + + fn poll_fd(&self) -> BorrowedFd { + self.epoll_fd.0.as_fd() + } +} + +#[cfg(test)] +pub mod tests { + + use crate::bitstream_utils::NalIterator; + use crate::codec::h265::parser::Nalu; + use crate::decoder::stateless::h265::H265; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. + fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { + let decoder = StatelessDecoder::::new_dummy(blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + NalIterator::::new(s), + f, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + blocking_mode, + ) + }, + decoder, + test, + false, + false, + ); + } + + /// A 64x64 progressive byte-stream encoded I-frame to make it easier to + /// spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// + /// gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,format=I420,width=64,height=64 ! x265enc ! video/x-h265,profile=main ! filesink location="64x64-I.h265" + pub const DECODE_64X64_PROGRESSIVE_I: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/64x64-I.h265"), + crcs: include_str!("../../codec/h265/test_data/64x64-I.h265.crc"), + }; + + #[test] + fn test_64x64_progressive_i_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::NonBlocking); + } + + /// A 64x64 progressive byte-stream encoded I-frame and P-frame to make + /// it easier to spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// gst-launch-1.0 videotestsrc num-buffers=2 ! video/x-raw,format=I420,width=64,height=64 ! x265enc option-string="b-adapt=0" ! video/x-h265,profile=main ! filesink location="64x64-I-P.h265" + pub const DECODE_64X64_PROGRESSIVE_I_P: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/64x64-I-P.h265"), + crcs: include_str!("../../codec/h265/test_data/64x64-I-P.h265.crc"), + }; + + #[test] + fn test_64x64_progressive_i_p_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_p_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::NonBlocking); + } + + /// A 64x64 progressive byte-stream encoded I-P-B-P sequence to make it + /// easier to it easier to spot errors on the libva trace. + /// Encoded with the following GStreamer pipeline: + /// gst-launch-1.0 videotestsrc num-buffers=3 ! video/x-raw,format=I420,width=64,height=64 ! x265enc option-string="b-adapt=0:bframes=1" ! video/x-h265,profile=main ! filesink location="64x64-I-P-B-P.h265" + pub const DECODE_64X64_PROGRESSIVE_I_P_B_P: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/64x64-I-P-B-P.h265"), + crcs: include_str!("../../codec/h265/test_data/64x64-I-P-B-P.h265.crc"), + }; + + #[test] + fn test_64x64_progressive_i_p_b_p_block() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::Blocking); + } + + #[test] + fn test_64x64_progressive_i_p_b_p_nonblock() { + test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::NonBlocking); + } + + /// Same as Chromium's test-25fps.h265 + pub const DECODE_TEST_25FPS: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/test-25fps.h265"), + crcs: include_str!("../../codec/h265/test_data/test-25fps.h265.crc"), + }; + + #[test] + fn test_25fps_block() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); + } + + /// Same as Chromium's bear.h265 + pub const DECODE_BEAR: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/bear.h265"), + crcs: include_str!("../../codec/h265/test_data/bear.h265.crc"), + }; + + #[test] + fn test_bear_block() { + test_decoder_dummy(&DECODE_BEAR, BlockingMode::Blocking); + } + + #[test] + fn test_bear_nonblock() { + test_decoder_dummy(&DECODE_BEAR, BlockingMode::NonBlocking); + } + + /// Same as Chromium's bbb.h265 + pub const DECODE_BBB: TestStream = TestStream { + stream: include_bytes!("../../codec/h265/test_data/bbb.h265"), + crcs: include_str!("../../codec/h265/test_data/bbb.h265.crc"), + }; + + #[test] + fn test_bbb_block() { + test_decoder_dummy(&DECODE_BBB, BlockingMode::Blocking); + } + + #[test] + fn test_bbb_nonblock() { + test_decoder_dummy(&DECODE_BBB, BlockingMode::NonBlocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h265/dummy.rs b/vendor/cros-codecs/src/decoder/stateless/h265/dummy.rs new file mode 100644 index 0000000..4329b72 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h265/dummy.rs @@ -0,0 +1,74 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backend whose only purpose is to let the decoder +//! run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::dummy::decoder::Backend; +use crate::backend::dummy::decoder::Handle; +use crate::decoder::stateless::h265::H265; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::BlockingMode; + +use crate::decoder::stateless::h265::StatelessH265DecoderBackend; +use crate::Resolution; + +impl StatelessH265DecoderBackend for Backend { + fn new_sequence( + &mut self, + _: &crate::codec::h265::parser::Sps, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn new_picture( + &mut self, + _: Resolution, + _: u64, + ) -> crate::decoder::stateless::NewPictureResult { + Ok(()) + } + + fn begin_picture( + &mut self, + _: &mut Self::Picture, + _: &crate::codec::h265::picture::PictureData, + _: &crate::codec::h265::parser::Sps, + _: &crate::codec::h265::parser::Pps, + _: &crate::codec::h265::dpb::Dpb, + _: &crate::decoder::stateless::h265::RefPicSet, + _: &crate::codec::h265::parser::Slice, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn decode_slice( + &mut self, + _: &mut Self::Picture, + _: &crate::codec::h265::parser::Slice, + _: &crate::codec::h265::parser::Sps, + _: &crate::codec::h265::parser::Pps, + _: &[Option>; 16], + _: &[Option>; 16], + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + Ok(()) + } + + fn submit_picture( + &mut self, + _: Self::Picture, + ) -> crate::decoder::stateless::StatelessBackendResult { + Ok(Handle { handle: Rc::new(RefCell::new(Default::default())) }) + } +} +impl StatelessDecoder { + // Creates a new instance of the decoder using the dummy backend. + pub fn new_dummy(blocking_mode: BlockingMode) -> Result { + Self::new(Backend::new(), blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/h265/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/h265/vaapi.rs new file mode 100644 index 0000000..87eaea3 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/h265/vaapi.rs @@ -0,0 +1,980 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; +use libva::{ + BufferType, Display, HevcSliceExtFlags, IQMatrix, IQMatrixBufferHEVC, PictureHEVC, + PictureParameterBufferHEVC, SliceParameter, SliceParameterBufferHEVC, + SliceParameterBufferHEVCRext, +}; + +use crate::backend::vaapi::decoder::DecodedHandle as VADecodedHandle; +use crate::backend::vaapi::decoder::VaStreamInfo; +use crate::backend::vaapi::decoder::VaapiBackend; +use crate::backend::vaapi::decoder::VaapiPicture; +use crate::codec::h265::dpb::Dpb; +use crate::codec::h265::parser::NaluType; +use crate::codec::h265::parser::Pps; +use crate::codec::h265::parser::Profile; +use crate::codec::h265::parser::Slice; +use crate::codec::h265::parser::Sps; +use crate::codec::h265::picture::PictureData; +use crate::codec::h265::picture::Reference; +use crate::decoder::stateless::h265::RefPicListEntry; +use crate::decoder::stateless::h265::RefPicSet; +use crate::decoder::stateless::h265::StatelessH265DecoderBackend; +use crate::decoder::stateless::h265::H265; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::video_frame::VideoFrame; +use crate::Rect; +use crate::Resolution; + +// Equation 5-8 +fn clip3(x: i32, y: i32, z: i32) -> i32 { + if z < x { + x + } else if z > y { + y + } else { + z + } +} + +// See 6.5.3 +const fn up_right_diagonal() -> [usize; N] { + // Generics can't be used in const operations for now, so [0; ROWS * ROWS] + // is rejected by the compiler + assert!(ROWS * ROWS == N); + + let mut i = 0; + let mut x = 0i32; + let mut y = 0i32; + let mut ret = [0; N]; + + loop { + while y >= 0 { + if x < (ROWS as i32) && y < (ROWS as i32) { + ret[i] = (x + ROWS as i32 * y) as usize; + i += 1; + } + y -= 1; + x += 1; + } + + y = x; + x = 0; + if i >= N { + break; + } + } + + ret +} + +const UP_RIGHT_DIAGONAL_4X4: [usize; 16] = up_right_diagonal::<16, 4>(); +const UP_RIGHT_DIAGONAL_8X8: [usize; 64] = up_right_diagonal::<64, 8>(); + +fn get_raster_from_up_right_diagonal_8x8(src: [u8; 64], dst: &mut [u8; 64]) { + for i in 0..64 { + dst[UP_RIGHT_DIAGONAL_8X8[i]] = src[i]; + } +} + +fn get_raster_from_up_right_diagonal_4x4(src: [u8; 16], dst: &mut [u8; 16]) { + for i in 0..16 { + dst[UP_RIGHT_DIAGONAL_4X4[i]] = src[i]; + } +} + +enum ScalingListType { + Sps, + Pps, + None, +} + +impl VaStreamInfo for &Sps { + fn va_profile(&self) -> anyhow::Result { + let profile_idc = self.profile_tier_level.general_profile_idc; + let profile = Profile::try_from(profile_idc).map_err(|err| anyhow!(err))?; + + let bit_depth = + std::cmp::max(self.bit_depth_luma_minus8 + 8, self.bit_depth_chroma_minus8 + 8); + + let chroma_format_idc = self.chroma_format_idc; + let err = Err(anyhow!( + "Invalid combination of profile, bit depth an chroma_format_idc: ({:?}, {}, {}", + profile, + bit_depth, + chroma_format_idc + )); + + // TODO: This can still be much improved in light of table A.2. + match profile { + Profile::Main | Profile::MainStill | Profile::Main10 => { + match (bit_depth, chroma_format_idc) { + (8, 0) | (8, 1) => Ok(libva::VAProfile::VAProfileHEVCMain), + (8, 3) => Ok(libva::VAProfile::VAProfileHEVCMain444), + (10, 0) | (10, 1) => Ok(libva::VAProfile::VAProfileHEVCMain10), + (10, 2) => Ok(libva::VAProfile::VAProfileHEVCMain422_10), + (12, 1) => Ok(libva::VAProfile::VAProfileHEVCMain12), + (12, 2) => Ok(libva::VAProfile::VAProfileHEVCMain422_12), + (12, 3) => Ok(libva::VAProfile::VAProfileHEVCMain444_12), + _ => err, + } + } + + // See table A.4. + Profile::ScalableMain => match (bit_depth, chroma_format_idc) { + (8, 1) => Ok(libva::VAProfile::VAProfileHEVCSccMain), + (8, 3) => Ok(libva::VAProfile::VAProfileHEVCSccMain444), + (10, 1) => Ok(libva::VAProfile::VAProfileHEVCSccMain10), + (10, 3) => Ok(libva::VAProfile::VAProfileHEVCSccMain444_10), + _ => err, + }, + + _ => unimplemented!("Adding more profile support based on A.3. is still TODO"), + } + } + + fn rt_format(&self) -> anyhow::Result { + let bit_depth = + std::cmp::max(self.bit_depth_luma_minus8 + 8, self.bit_depth_chroma_minus8 + 8); + + let chroma_format_idc = self.chroma_format_idc; + + match (bit_depth, chroma_format_idc) { + (8, 0) | (8, 1) => Ok(libva::VA_RT_FORMAT_YUV420), + (8, 2) => Ok(libva::VA_RT_FORMAT_YUV422), + (8, 3) => Ok(libva::VA_RT_FORMAT_YUV444), + (9, 0) | (9, 1) | (10, 0) | (10, 1) => Ok(libva::VA_RT_FORMAT_YUV420_10), + (9, 2) | (10, 2) => Ok(libva::VA_RT_FORMAT_YUV422_10), + (9, 3) | (10, 3) => Ok(libva::VA_RT_FORMAT_YUV444_10), + (11, 0) | (11, 1) | (12, 0) | (12, 1) => Ok(libva::VA_RT_FORMAT_YUV420_12), + (11, 2) | (12, 2) => Ok(libva::VA_RT_FORMAT_YUV422_12), + (11, 3) | (12, 3) => Ok(libva::VA_RT_FORMAT_YUV444_12), + _ => Err(anyhow!( + "unsupported bit depth/chroma format pair {}, {}", + bit_depth, + chroma_format_idc + )), + } + } + + fn min_num_surfaces(&self) -> usize { + self.max_dpb_size() + 4 + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width().into(), self.height().into())) + } + + fn visible_rect(&self) -> Rect { + let rect = self.visible_rectangle(); + + Rect { x: rect.min.x, y: rect.min.y, width: rect.max.x, height: rect.max.y } + } +} + +fn build_slice_ref_pic_list( + ref_pic_list: &[Option>>; 16], + va_references: &[PictureHEVC; 15], +) -> [u8; 15] { + let mut va_refs = [0xff; 15]; + + for (ref_pic_list_idx, ref_pic_list_entry) in ref_pic_list.iter().enumerate() { + if ref_pic_list_idx == 15 { + break; + } + + if let Some(ref_pic_list_entry) = ref_pic_list_entry { + for (va_ref_idx, va_ref) in va_references.iter().enumerate() { + if va_ref.picture_id() == libva::VA_INVALID_ID { + break; + } + + let pic_order_cnt = match ref_pic_list_entry { + RefPicListEntry::CurrentPicture(p) => p.pic_order_cnt_val, + RefPicListEntry::DpbEntry(p) => p.0.borrow().pic_order_cnt_val, + }; + + if va_ref.pic_order_cnt() == pic_order_cnt { + va_refs[ref_pic_list_idx] = va_ref_idx as u8; + } + } + } + } + + va_refs +} + +fn va_rps_flag(hevc_pic: &PictureData, rps: &RefPicSet>) -> u32 { + if rps + .ref_pic_set_st_curr_before + .iter() + .flatten() + .any(|dpb_entry| *dpb_entry.0.borrow() == *hevc_pic) + { + libva::VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE + } else if rps + .ref_pic_set_st_curr_after + .iter() + .flatten() + .any(|dpb_entry| *dpb_entry.0.borrow() == *hevc_pic) + { + libva::VA_PICTURE_HEVC_RPS_ST_CURR_AFTER + } else if rps + .ref_pic_set_lt_curr + .iter() + .flatten() + .any(|dpb_entry| *dpb_entry.0.borrow() == *hevc_pic) + { + libva::VA_PICTURE_HEVC_RPS_LT_CURR + } else { + 0 + } +} + +/// Builds an invalid VaPictureHEVC. These pictures are used to fill empty +/// array slots there is no data to fill them with. +fn build_invalid_va_hevc_pic() -> libva::PictureHEVC { + libva::PictureHEVC::new(libva::VA_INVALID_ID, 0, libva::VA_PICTURE_HEVC_INVALID) +} + +fn fill_va_hevc_pic( + hevc_pic: &PictureData, + surface_id: libva::VASurfaceID, + rps: &RefPicSet>, +) -> libva::PictureHEVC { + let mut flags = 0; + + if matches!(hevc_pic.reference(), Reference::LongTerm) { + flags |= libva::VA_PICTURE_HEVC_LONG_TERM_REFERENCE; + } + + flags |= va_rps_flag(hevc_pic, rps); + + libva::PictureHEVC::new(surface_id, hevc_pic.pic_order_cnt_val, flags) +} + +fn is_range_extension_profile(va_profile: libva::VAProfile::Type) -> bool { + matches!( + va_profile, + libva::VAProfile::VAProfileHEVCMain422_10 + | libva::VAProfile::VAProfileHEVCMain444 + | libva::VAProfile::VAProfileHEVCMain444_10 + | libva::VAProfile::VAProfileHEVCMain12 + | libva::VAProfile::VAProfileHEVCMain422_12 + | libva::VAProfile::VAProfileHEVCMain444_12 + ) +} + +fn is_scc_ext_profile(va_profile: libva::VAProfile::Type) -> bool { + matches!( + va_profile, + libva::VAProfile::VAProfileHEVCSccMain + | libva::VAProfile::VAProfileHEVCSccMain10 + | libva::VAProfile::VAProfileHEVCSccMain444 + | libva::VAProfile::VAProfileHEVCMain444_10, + ) +} + +fn build_picture_rext(sps: &Sps, pps: &Pps) -> anyhow::Result { + let sps_rext = &sps.range_extension; + let pps_rext = &pps.range_extension; + + let range_extension_pic_fields = libva::HevcRangeExtensionPicFields::new( + sps_rext.transform_skip_rotation_enabled_flag as u32, + sps_rext.transform_skip_context_enabled_flag as u32, + sps_rext.implicit_rdpcm_enabled_flag as u32, + sps_rext.explicit_rdpcm_enabled_flag as u32, + sps_rext.extended_precision_processing_flag as u32, + sps_rext.intra_smoothing_disabled_flag as u32, + sps_rext.high_precision_offsets_enabled_flag as u32, + sps_rext.persistent_rice_adaptation_enabled_flag as u32, + sps_rext.cabac_bypass_alignment_enabled_flag as u32, + pps_rext.cross_component_prediction_enabled_flag as u32, + pps_rext.chroma_qp_offset_list_enabled_flag as u32, + ); + + let rext = libva::PictureParameterBufferHEVCRext::new( + &range_extension_pic_fields, + pps_rext.diff_cu_chroma_qp_offset_depth as u8, + pps_rext.chroma_qp_offset_list_len_minus1 as u8, + pps_rext.log2_sao_offset_scale_luma as u8, + pps_rext.log2_sao_offset_scale_chroma as u8, + pps_rext.log2_max_transform_skip_block_size_minus2 as u8, + pps_rext.cb_qp_offset_list.map(|x| x as i8), + pps_rext.cr_qp_offset_list.map(|x| x as i8), + ); + + Ok(BufferType::PictureParameter(libva::PictureParameter::HEVCRext(rext))) +} + +fn build_picture_scc(sps: &Sps, pps: &Pps) -> anyhow::Result { + let sps_scc = &sps.scc_extension; + let pps_scc = &pps.scc_extension; + + let scc_pic_fields = libva::HevcScreenContentPicFields::new( + pps_scc.curr_pic_ref_enabled_flag as u32, + sps_scc.palette_mode_enabled_flag as u32, + sps_scc.motion_vector_resolution_control_idc as u32, + sps_scc.intra_boundary_filtering_disabled_flag as u32, + pps_scc.residual_adaptive_colour_transform_enabled_flag as u32, + pps_scc.slice_act_qp_offsets_present_flag as u32, + ); + + let (predictor_palette_entries, predictor_palette_size) = + if pps_scc.palette_predictor_initializers_present_flag { + ( + pps_scc.palette_predictor_initializer.map(|outer| outer.map(u16::from)), + pps_scc.num_palette_predictor_initializers, + ) + } else if sps_scc.palette_predictor_initializers_present_flag { + ( + sps_scc.palette_predictor_initializer.map(|outer| outer.map(|inner| inner as u16)), + sps_scc.num_palette_predictor_initializer_minus1 + 1, + ) + } else { + ([[0; 128]; 3], 0) + }; + + let scc = libva::PictureParameterBufferHEVCScc::new( + &scc_pic_fields, + sps_scc.palette_max_size, + sps_scc.delta_palette_max_predictor_size, + predictor_palette_size, + predictor_palette_entries, + pps_scc.act_y_qp_offset_plus5, + pps_scc.act_cb_qp_offset_plus5, + pps_scc.act_cr_qp_offset_plus3, + ); + + Ok(BufferType::PictureParameter(libva::PictureParameter::HEVCScc(scc))) +} + +fn build_pic_param( + _: &Slice, + current_picture: &PictureData, + current_surface_id: libva::VASurfaceID, + dpb: &Dpb>, + rps: &RefPicSet>, + sps: &Sps, + pps: &Pps, +) -> anyhow::Result<(BufferType, [PictureHEVC; 15])> { + let curr_pic = fill_va_hevc_pic(current_picture, current_surface_id, rps); + + let mut reference_frames = vec![]; + + for ref_pic in dpb.get_all_references() { + let surface_id = ref_pic.1.borrow().surface().id(); + let ref_pic = fill_va_hevc_pic(&ref_pic.0.borrow(), surface_id, rps); + reference_frames.push(ref_pic); + } + + // RefPicListL0 and RefPicListL1 may signal that they want to refer to + // the current picture. We must tell VA that it is a reference as it is + // not in the DPB at this point. + if pps.scc_extension.curr_pic_ref_enabled_flag { + if reference_frames.len() >= 15 { + log::warn!( + "Bug: Trying to set the current picture as a VA reference, but the VA DPB is full." + ) + } else { + reference_frames.push(curr_pic); + } + } + + for _ in reference_frames.len()..15 { + reference_frames.push(build_invalid_va_hevc_pic()); + } + + let reference_frames = reference_frames.try_into(); + let reference_frames = match reference_frames { + Ok(va_refs) => va_refs, + Err(_) => { + // Can't panic, we guarantee len() == 15. + panic!("Bug: wrong number of references, expected 15"); + } + }; + + let pic_fields = libva::HevcPicFields::new( + sps.chroma_format_idc as u32, + sps.separate_colour_plane_flag as u32, + sps.pcm_enabled_flag as u32, + sps.scaling_list_enabled_flag as u32, + pps.transform_skip_enabled_flag as u32, + sps.amp_enabled_flag as u32, + sps.strong_intra_smoothing_enabled_flag as u32, + pps.sign_data_hiding_enabled_flag as u32, + pps.constrained_intra_pred_flag as u32, + pps.cu_qp_delta_enabled_flag as u32, + pps.weighted_pred_flag as u32, + pps.weighted_bipred_flag as u32, + pps.transquant_bypass_enabled_flag as u32, + pps.tiles_enabled_flag as u32, + pps.entropy_coding_sync_enabled_flag as u32, + pps.loop_filter_across_slices_enabled_flag as u32, + pps.loop_filter_across_tiles_enabled_flag as u32, + sps.pcm_loop_filter_disabled_flag as u32, + /* lets follow the FFMPEG and GStreamer train and set these to false */ + 0, + 0, + ); + + let rap_pic_flag = current_picture.nalu_type as u32 >= NaluType::BlaWLp as u32 + && current_picture.nalu_type as u32 <= NaluType::CraNut as u32; + + let slice_parsing_fields = libva::HevcSliceParsingFields::new( + pps.lists_modification_present_flag as u32, + sps.long_term_ref_pics_present_flag as u32, + sps.temporal_mvp_enabled_flag as u32, + pps.cabac_init_present_flag as u32, + pps.output_flag_present_flag as u32, + pps.dependent_slice_segments_enabled_flag as u32, + pps.slice_chroma_qp_offsets_present_flag as u32, + sps.sample_adaptive_offset_enabled_flag as u32, + pps.deblocking_filter_override_enabled_flag as u32, + pps.deblocking_filter_disabled_flag as u32, + pps.slice_segment_header_extension_present_flag as u32, + rap_pic_flag as u32, + current_picture.nalu_type.is_idr() as u32, + current_picture.nalu_type.is_irap() as u32, + ); + + let pic_param = PictureParameterBufferHEVC::new( + curr_pic, + reference_frames, + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + &pic_fields, + sps.max_dec_pic_buffering_minus1[usize::from(sps.max_sub_layers_minus1)], + sps.bit_depth_luma_minus8, + sps.bit_depth_chroma_minus8, + sps.pcm_sample_bit_depth_luma_minus1, + sps.pcm_sample_bit_depth_chroma_minus1, + sps.log2_min_luma_coding_block_size_minus3, + sps.log2_diff_max_min_luma_coding_block_size, + sps.log2_min_luma_transform_block_size_minus2, + sps.log2_diff_max_min_luma_transform_block_size, + sps.log2_min_pcm_luma_coding_block_size_minus3, + sps.log2_diff_max_min_pcm_luma_coding_block_size, + sps.max_transform_hierarchy_depth_intra, + sps.max_transform_hierarchy_depth_inter, + pps.init_qp_minus26, + pps.diff_cu_qp_delta_depth, + pps.cb_qp_offset, + pps.cr_qp_offset, + pps.log2_parallel_merge_level_minus2, + pps.num_tile_columns_minus1, + pps.num_tile_rows_minus1, + pps.column_width_minus1.map(|x| x as u16), + pps.row_height_minus1.map(|x| x as u16), + &slice_parsing_fields, + sps.log2_max_pic_order_cnt_lsb_minus4, + sps.num_short_term_ref_pic_sets, + sps.num_long_term_ref_pics_sps, + pps.num_ref_idx_l0_default_active_minus1, + pps.num_ref_idx_l1_default_active_minus1, + pps.beta_offset_div2, + pps.tc_offset_div2, + pps.num_extra_slice_header_bits, + current_picture.short_term_ref_pic_set_size_bits, + ); + + Ok((BufferType::PictureParameter(libva::PictureParameter::HEVC(pic_param)), reference_frames)) +} + +fn find_scaling_list(sps: &Sps, pps: &Pps) -> ScalingListType { + if pps.scaling_list_data_present_flag + || (sps.scaling_list_enabled_flag && !sps.scaling_list_data_present_flag) + { + ScalingListType::Pps + } else if sps.scaling_list_enabled_flag && sps.scaling_list_data_present_flag { + ScalingListType::Sps + } else { + ScalingListType::None + } +} + +fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType { + let scaling_lists = match find_scaling_list(sps, pps) { + ScalingListType::Sps => &sps.scaling_list, + ScalingListType::Pps => &pps.scaling_list, + ScalingListType::None => panic!("No scaling list data available"), + }; + + let mut scaling_list_32x32 = [[0; 64]; 2]; + + for i in (0..6).step_by(3) { + for j in 0..64 { + scaling_list_32x32[i / 3][j] = scaling_lists.scaling_list_32x32[i][j]; + } + } + + let mut scaling_list_dc_32x32 = [0; 2]; + for i in (0..6).step_by(3) { + scaling_list_dc_32x32[i / 3] = + (scaling_lists.scaling_list_dc_coef_minus8_32x32[i] + 8) as u8; + } + + let mut scaling_list_4x4 = [[0; 16]; 6]; + let mut scaling_list_8x8 = [[0; 64]; 6]; + let mut scaling_list_16x16 = [[0; 64]; 6]; + let mut scaling_list_32x32_r = [[0; 64]; 2]; + + (0..6).for_each(|i| { + get_raster_from_up_right_diagonal_4x4( + scaling_lists.scaling_list_4x4[i], + &mut scaling_list_4x4[i], + ); + + get_raster_from_up_right_diagonal_8x8( + scaling_lists.scaling_list_8x8[i], + &mut scaling_list_8x8[i], + ); + + get_raster_from_up_right_diagonal_8x8( + scaling_lists.scaling_list_16x16[i], + &mut scaling_list_16x16[i], + ); + }); + + (0..2).for_each(|i| { + get_raster_from_up_right_diagonal_8x8(scaling_list_32x32[i], &mut scaling_list_32x32_r[i]); + }); + + BufferType::IQMatrix(IQMatrix::HEVC(IQMatrixBufferHEVC::new( + scaling_list_4x4, + scaling_list_8x8, + scaling_list_16x16, + scaling_list_32x32_r, + scaling_lists.scaling_list_dc_coef_minus8_16x16.map(|x| (x + 8) as u8), + scaling_list_dc_32x32, + ))) +} + +impl VaapiBackend { + fn submit_last_slice( + &mut self, + picture: &mut >::Picture, + ) -> anyhow::Result<()> { + if let Some(last_slice) = picture.last_slice.take() { + let context = &self.context; + let picture = &mut picture.picture; + + let slice_param = BufferType::SliceParameter(SliceParameter::HEVC(last_slice.0)); + let slice_param = context.create_buffer(slice_param)?; + picture.add_buffer(slice_param); + + if let Some(slice_param_rext) = last_slice.1 { + let slice_param_rext = + BufferType::SliceParameter(SliceParameter::HEVCRext(slice_param_rext)); + let slice_param_rext = context.create_buffer(slice_param_rext)?; + picture.add_buffer(slice_param_rext); + } + + let slice_data = BufferType::SliceData(last_slice.2); + let slice_data = context.create_buffer(slice_data)?; + picture.add_buffer(slice_data); + } + + Ok(()) + } +} + +pub struct VaapiH265Picture { + picture: Picture, + + // We are always one slice behind, so that we can mark the last one in + // submit_picture() + last_slice: Option<(SliceParameterBufferHEVC, Option, Vec)>, + + va_references: [PictureHEVC; 15], +} + +impl StatelessDecoderBackendPicture for VaapiBackend { + type Picture = VaapiH265Picture>; +} + +impl StatelessH265DecoderBackend for VaapiBackend { + fn new_sequence(&mut self, sps: &Sps) -> StatelessBackendResult<()> { + self.new_sequence(sps) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + Ok(VaapiH265Picture { + picture: VaapiPicture::new( + timestamp, + Rc::clone(&self.context), + alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, + ), + last_slice: Default::default(), + va_references: Default::default(), + }) + } + + fn begin_picture( + &mut self, + picture: &mut Self::Picture, + picture_data: &PictureData, + sps: &Sps, + pps: &Pps, + dpb: &Dpb, + rps: &RefPicSet, + slice: &Slice, + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + let context = &self.context; + + let surface_id = picture.picture.surface().id(); + + let (pic_param, reference_frames) = + build_pic_param(slice, picture_data, surface_id, dpb, rps, sps, pps)?; + + picture.va_references = reference_frames; + + let picture = &mut picture.picture; + + let pic_param = + context.create_buffer(pic_param).context("while creating picture parameter buffer")?; + + picture.add_buffer(pic_param); + + if !matches!(find_scaling_list(sps, pps), ScalingListType::None) { + let iq_matrix = build_iq_matrix(sps, pps); + let iq_matrix = + context.create_buffer(iq_matrix).context("while creating IQ matrix buffer")?; + + picture.add_buffer(iq_matrix); + } + + let va_profile = sps.va_profile()?; + if is_range_extension_profile(va_profile) || is_scc_ext_profile(va_profile) { + let rext = build_picture_rext(sps, pps)?; + let rext = context + .create_buffer(rext) + .context("while creating picture parameter range extension buffer")?; + + picture.add_buffer(rext); + + if is_scc_ext_profile(va_profile) { + let scc = build_picture_scc(sps, pps)?; + let scc = context + .create_buffer(scc) + .context("while creating picture screen content coding buffer")?; + + picture.add_buffer(scc); + } + } + + Ok(()) + } + + fn decode_slice( + &mut self, + picture: &mut Self::Picture, + slice: &Slice, + sps: &Sps, + _: &Pps, + ref_pic_list0: &[Option>; 16], + ref_pic_list1: &[Option>; 16], + ) -> crate::decoder::stateless::StatelessBackendResult<()> { + self.submit_last_slice(picture)?; + let hdr = &slice.header; + + let va_references = &picture.va_references; + let ref_pic_list0 = build_slice_ref_pic_list(ref_pic_list0, va_references); + let ref_pic_list1 = build_slice_ref_pic_list(ref_pic_list1, va_references); + + let long_slice_flags = libva::HevcLongSliceFlags::new( + 0, + hdr.dependent_slice_segment_flag as u32, + hdr.type_ as u32, + hdr.colour_plane_id as u32, + hdr.sao_luma_flag as u32, + hdr.sao_chroma_flag as u32, + hdr.mvd_l1_zero_flag as u32, + hdr.cabac_init_flag as u32, + hdr.temporal_mvp_enabled_flag as u32, + hdr.deblocking_filter_disabled_flag as u32, + hdr.collocated_from_l0_flag as u32, + hdr.loop_filter_across_slices_enabled_flag as u32, + ); + + let collocated_ref_idx = + if hdr.temporal_mvp_enabled_flag { hdr.collocated_ref_idx } else { 0xff }; + + let pwt = &hdr.pred_weight_table; + + let mut delta_luma_weight_l0: [i8; 15usize] = Default::default(); + let mut luma_offset_l0: [i8; 15usize] = Default::default(); + let mut delta_chroma_weight_l0: [[i8; 2usize]; 15usize] = Default::default(); + let mut chroma_offset_l0: [[i8; 2usize]; 15usize] = Default::default(); + let mut delta_luma_weight_l1: [i8; 15usize] = Default::default(); + let mut luma_offset_l1: [i8; 15usize] = Default::default(); + let mut delta_chroma_weight_l1: [[i8; 2usize]; 15usize] = Default::default(); + let mut chroma_offset_l1: [[i8; 2usize]; 15usize] = Default::default(); + + for i in 0..15 { + delta_luma_weight_l0[i] = pwt.delta_luma_weight_l0[i]; + luma_offset_l0[i] = pwt.luma_offset_l0[i]; + + if hdr.type_.is_b() { + delta_luma_weight_l1[i] = pwt.delta_luma_weight_l1[i]; + luma_offset_l1[i] = pwt.luma_offset_l1[i]; + } + + for j in 0..2 { + delta_chroma_weight_l0[i][j] = pwt.delta_chroma_weight_l0[i][j]; + let delta_chroma_offset = pwt.delta_chroma_offset_l0[i][j]; + + let chroma_weight_l0 = (1 << pwt.chroma_log2_weight_denom) + + i32::from(pwt.delta_chroma_weight_l0[i][j]); + + let offset = sps.wp_offset_half_range_c as i32 + delta_chroma_offset as i32 + - ((sps.wp_offset_half_range_c as i32 * chroma_weight_l0) + >> pwt.chroma_log2_weight_denom); + + chroma_offset_l0[i][j] = clip3( + -(sps.wp_offset_half_range_c as i32), + (sps.wp_offset_half_range_c - 1) as i32, + offset, + ) as _; + + if hdr.type_.is_b() { + delta_chroma_weight_l1[i][j] = pwt.delta_chroma_weight_l1[i][j]; + let delta_chroma_offset = pwt.delta_chroma_offset_l1[i][j]; + + let chroma_weight_l1 = (1 << pwt.chroma_log2_weight_denom) + + i32::from(pwt.delta_chroma_weight_l1[i][j]); + + let offset = sps.wp_offset_half_range_c as i32 + delta_chroma_offset as i32 + - ((sps.wp_offset_half_range_c as i32 * chroma_weight_l1) + >> pwt.chroma_log2_weight_denom); + + chroma_offset_l1[i][j] = clip3( + -(sps.wp_offset_half_range_c as i32), + (sps.wp_offset_half_range_c - 1) as i32, + offset, + ) as _; + } + } + } + + let slice_param = SliceParameterBufferHEVC::new( + slice.nalu.size as u32, + 0, + libva::VA_SLICE_DATA_FLAG_ALL, + (hdr.header_bit_size / 8) as _, + hdr.segment_address, + [ref_pic_list0, ref_pic_list1], + &long_slice_flags, + collocated_ref_idx, + hdr.num_ref_idx_l0_active_minus1, + hdr.num_ref_idx_l1_active_minus1, + hdr.qp_delta, + hdr.cb_qp_offset, + hdr.cr_qp_offset, + hdr.beta_offset_div2, + hdr.tc_offset_div2, + pwt.luma_log2_weight_denom, + pwt.delta_chroma_log2_weight_denom, + delta_luma_weight_l0, + luma_offset_l0, + delta_chroma_weight_l0, + chroma_offset_l0, + delta_luma_weight_l1, + luma_offset_l1, + delta_chroma_weight_l1, + chroma_offset_l1, + hdr.five_minus_max_num_merge_cand, + hdr.num_entry_point_offsets as _, + 0, + hdr.n_emulation_prevention_bytes as _, + ); + + let va_profile = sps.va_profile()?; + + let slice_param_ext = + if is_range_extension_profile(va_profile) || is_scc_ext_profile(va_profile) { + let slice_ext_flags = HevcSliceExtFlags::new( + hdr.cu_chroma_qp_offset_enabled_flag as u32, + hdr.use_integer_mv_flag as u32, + ); + + let slice_param_ext = SliceParameterBufferHEVCRext::new( + luma_offset_l0.map(i16::from), + chroma_offset_l0.map(|outer| outer.map(i16::from)), + luma_offset_l1.map(i16::from), + chroma_offset_l1.map(|outer| outer.map(i16::from)), + &slice_ext_flags, + hdr.slice_act_y_qp_offset, + hdr.slice_act_cb_qp_offset, + hdr.slice_act_cr_qp_offset, + ); + + Some(slice_param_ext) + } else { + None + }; + + let slice_data = Vec::from(slice.nalu.as_ref()); + + picture.last_slice = Some((slice_param, slice_param_ext, slice_data)); + + Ok(()) + } + + fn submit_picture( + &mut self, + mut picture: Self::Picture, + ) -> StatelessBackendResult { + if let Some(last_slice) = &mut picture.last_slice { + last_slice.0.set_as_last(); + } + self.submit_last_slice(&mut picture)?; + self.process_picture::(picture.picture) + } +} + +impl StatelessDecoder> { + // Creates a new instance of the decoder using the VAAPI backend. + pub fn new_vaapi( + display: Rc, + blocking_mode: BlockingMode, + ) -> Result { + Self::new(VaapiBackend::new(display, false), blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::Display; + + use crate::bitstream_utils::NalIterator; + use crate::codec::h265::parser::Nalu; + use crate::decoder::stateless::h265::H265; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the vaapi decoder, in both blocking and non-blocking modes. + fn test_decoder_vaapi( + test: &TestStream, + output_format: DecodedFormat, + blocking_mode: BlockingMode, + ) { + let display = Display::open().unwrap(); + let decoder = StatelessDecoder::::new_vaapi::<()>(display, blocking_mode).unwrap(); + + test_decode_stream( + |d, s, f| { + simple_playback_loop( + d, + NalIterator::::new(s), + f, + &mut simple_playback_loop_owned_frames, + output_format, + blocking_mode, + ) + }, + decoder, + test, + true, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_block() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_nonblock() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_block() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_nonblock() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_block() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_64x64_progressive_i_p_b_p_nonblock() { + use crate::decoder::stateless::h265::tests::DECODE_64X64_PROGRESSIVE_I_P_B_P; + test_decoder_vaapi( + &DECODE_64X64_PROGRESSIVE_I_P_B_P, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp8.rs b/vendor/cros-codecs/src/decoder/stateless/vp8.rs new file mode 100644 index 0000000..df4a7e6 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp8.rs @@ -0,0 +1,364 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(any(test, fuzzing))] +mod dummy; +#[cfg(feature = "v4l2")] +mod v4l2; +#[cfg(feature = "vaapi")] +mod vaapi; + +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; + +use crate::codec::vp8::parser::Frame; +use crate::codec::vp8::parser::Header; +use crate::codec::vp8::parser::MbLfAdjustments; +use crate::codec::vp8::parser::Parser; +use crate::codec::vp8::parser::Segmentation; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DecodingState; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::decoder::DecoderEvent; +use crate::decoder::StreamInfo; +use crate::Resolution; + +/// Stateless backend methods specific to VP8. +pub trait StatelessVp8DecoderBackend: + StatelessDecoderBackend + StatelessDecoderBackendPicture +{ + /// Called when new stream parameters are found. + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()>; + + /// Called when the decoder determines that a frame or field was found. + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult; + + /// Called when the decoder wants the backend to finish the decoding + /// operations for `picture`. + /// + /// This call will assign the ownership of the BackendHandle to the Picture + /// and then assign the ownership of the Picture to the Handle. + #[allow(clippy::too_many_arguments)] + fn submit_picture( + &mut self, + picture: Self::Picture, + hdr: &Header, + last_ref: &Option, + golden_ref: &Option, + alt_ref: &Option, + bitstream: &[u8], + segmentation: &Segmentation, + mb_lf_adjust: &MbLfAdjustments, + ) -> StatelessBackendResult; +} + +pub struct Vp8DecoderState { + /// VP8 bitstream parser. + parser: Parser, + + /// The picture used as the last reference picture. + last_picture: Option, + /// The picture used as the golden reference picture. + golden_ref_picture: Option, + /// The picture used as the alternate reference picture. + alt_ref_picture: Option, +} + +impl Default for Vp8DecoderState { + fn default() -> Self { + Self { + parser: Default::default(), + last_picture: Default::default(), + golden_ref_picture: Default::default(), + alt_ref_picture: Default::default(), + } + } +} + +/// [`StatelessCodec`] structure to use in order to create a VP8 stateless decoder. +/// +/// # Accepted input +/// +/// A decoder using this codec processes exactly one encoded frame per call to +/// [`StatelessDecoder::decode`], and returns the number of bytes actually taken by the frame data. +/// If the frame was properly encapsulated in its container, the returned value should be equal to +/// the length of the submitted input. +pub struct Vp8; + +impl StatelessCodec for Vp8 { + type FormatInfo = Header; + type DecoderState = Vp8DecoderState; +} + +impl Vp8DecoderState +where + H: DecodedHandle + Clone, +{ + /// Replace a reference frame with `handle`. + fn replace_reference(reference: &mut Option, handle: &H) { + *reference = Some(handle.clone()); + } + + pub(crate) fn update_references( + &mut self, + header: &Header, + decoded_handle: &H, + ) -> anyhow::Result<()> { + if header.key_frame { + Self::replace_reference(&mut self.last_picture, decoded_handle); + Self::replace_reference(&mut self.golden_ref_picture, decoded_handle); + Self::replace_reference(&mut self.alt_ref_picture, decoded_handle); + } else { + if header.refresh_alternate_frame { + Self::replace_reference(&mut self.alt_ref_picture, decoded_handle); + } else { + match header.copy_buffer_to_alternate { + 0 => { /* do nothing */ } + + 1 => { + if let Some(last_picture) = &self.last_picture { + Self::replace_reference(&mut self.alt_ref_picture, last_picture); + } + } + + 2 => { + if let Some(golden_ref) = &self.golden_ref_picture { + Self::replace_reference(&mut self.alt_ref_picture, golden_ref); + } + } + + other => anyhow::bail!("invalid copy_buffer_to_alternate value: {}", other), + } + } + + if header.refresh_golden_frame { + Self::replace_reference(&mut self.golden_ref_picture, decoded_handle); + } else { + match header.copy_buffer_to_golden { + 0 => { /* do nothing */ } + + 1 => { + if let Some(last_picture) = &self.last_picture { + Self::replace_reference(&mut self.golden_ref_picture, last_picture); + } + } + + 2 => { + if let Some(alt_ref) = &self.alt_ref_picture { + Self::replace_reference(&mut self.golden_ref_picture, alt_ref); + } + } + + other => anyhow::bail!("invalid copy_buffer_to_golden value: {}", other), + } + } + + if header.refresh_last { + Self::replace_reference(&mut self.last_picture, decoded_handle); + } + } + + Ok(()) + } +} + +impl StatelessDecoder +where + B: StatelessVp8DecoderBackend, + B::Handle: Clone + DecodedHandle, +{ + /// Handle a single frame. + fn handle_frame( + &mut self, + frame: Frame, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result<(), DecodeError> { + let show_frame = frame.header.show_frame; + + let picture = self.backend.new_picture(timestamp, alloc_cb)?; + let decoded_handle = self.backend.submit_picture( + picture, + &frame.header, + &self.codec.last_picture, + &self.codec.golden_ref_picture, + &self.codec.alt_ref_picture, + frame.as_ref(), + self.codec.parser.segmentation(), + self.codec.parser.mb_lf_adjust(), + )?; + + if self.blocking_mode == BlockingMode::Blocking { + decoded_handle.sync()?; + } + + // Do DPB management + self.codec.update_references(&frame.header, &decoded_handle)?; + + if show_frame { + self.ready_queue.push(decoded_handle); + } + + Ok(()) + } + + fn negotiation_possible(&self, frame: &Frame) -> bool { + let coded_resolution = self.coded_resolution; + let hdr = &frame.header; + let width = u32::from(hdr.width); + let height = u32::from(hdr.height); + + width != coded_resolution.width || height != coded_resolution.height + } +} + +impl StatelessVideoDecoder for StatelessDecoder +where + B: StatelessVp8DecoderBackend, + B::Handle: Clone + 'static, +{ + type Handle = B::Handle; + + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result { + let frame = self + .codec + .parser + .parse_frame(bitstream) + .map_err(|err| DecodeError::ParseFrameError(err.to_string()))?; + + self.wait_for_drc_flush()?; + + if frame.header.key_frame { + if self.negotiation_possible(&frame) { + if matches!(self.decoding_state, DecodingState::Decoding) { + // DRC occurs when a key frame is seen, the format is different, + // and the decoder is already decoding frames. + self.flush()?; + self.decoding_state = DecodingState::FlushingForDRC; + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + self.backend.new_sequence(&frame.header)?; + self.await_format_change(frame.header.clone()); + } else if matches!(self.decoding_state, DecodingState::Reset) { + // We can resume decoding since the decoding parameters have not changed. + self.decoding_state = DecodingState::Decoding; + } + } + + match &mut self.decoding_state { + // Skip input until we get information from the stream. + DecodingState::AwaitingStreamInfo | DecodingState::Reset => Ok(bitstream.len()), + // Ask the client to confirm the format before we can process this. + DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { + Err(DecodeError::CheckEvents) + } + DecodingState::Decoding => { + let len = frame.header.frame_len(); + self.handle_frame(frame, timestamp, alloc_cb)?; + Ok(len) + } + } + } + + fn flush(&mut self) -> Result<(), DecodeError> { + // Note: all the submitted frames are already in the ready queue. + self.codec.last_picture = Default::default(); + self.codec.golden_ref_picture = Default::default(); + self.codec.alt_ref_picture = Default::default(); + self.decoding_state = DecodingState::Reset; + + Ok(()) + } + + fn next_event(&mut self) -> Option> { + self.query_next_event(|decoder, hdr| { + decoder.coded_resolution = + Resolution { width: hdr.width as u32, height: hdr.height as u32 }; + }) + } + + fn stream_info(&self) -> Option<&StreamInfo> { + self.backend.stream_info() + } + + fn poll_fd(&self) -> BorrowedFd { + self.epoll_fd.0.as_fd() + } +} + +#[cfg(test)] +pub mod tests { + use crate::bitstream_utils::IvfIterator; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::vp8::Vp8; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. + fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { + let decoder = StatelessDecoder::::new_dummy(blocking_mode).unwrap(); + + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + blocking_mode, + ) + }, + decoder, + test, + false, + false, + ); + } + + /// Same as Chromium's test-25fps.vp8 + pub const DECODE_TEST_25FPS: TestStream = TestStream { + stream: include_bytes!("../../codec/vp8/test_data/test-25fps.vp8"), + crcs: include_str!("../../codec/vp8/test_data/test-25fps.vp8.crc"), + }; + + #[test] + fn test_25fps_block() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp8/dummy.rs b/vendor/cros-codecs/src/decoder/stateless/vp8/dummy.rs new file mode 100644 index 0000000..beefa38 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp8/dummy.rs @@ -0,0 +1,53 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file contains a dummy backend whose only purpose is to let the decoder +// run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::dummy::decoder::Backend; +use crate::backend::dummy::decoder::Handle; +use crate::codec::vp8::parser::Header; +use crate::codec::vp8::parser::MbLfAdjustments; +use crate::codec::vp8::parser::Segmentation; +use crate::decoder::stateless::vp8::StatelessVp8DecoderBackend; +use crate::decoder::stateless::vp8::Vp8; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::BlockingMode; + +impl StatelessVp8DecoderBackend for Backend { + fn new_sequence(&mut self, _: &Header) -> StatelessBackendResult<()> { + Ok(()) + } + + fn new_picture(&mut self, _: u64) -> NewPictureResult { + Ok(()) + } + + fn submit_picture( + &mut self, + _: Self::Picture, + _: &Header, + _: &Option, + _: &Option, + _: &Option, + _: &[u8], + _: &Segmentation, + _: &MbLfAdjustments, + ) -> StatelessBackendResult { + Ok(Handle { handle: Rc::new(RefCell::new(Default::default())) }) + } +} + +impl StatelessDecoder { + // Creates a new instance of the decoder using the dummy backend. + pub fn new_dummy(blocking_mode: BlockingMode) -> Result { + Self::new(Backend::new(), blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp8/v4l2.rs b/vendor/cros-codecs/src/decoder/stateless/vp8/v4l2.rs new file mode 100644 index 0000000..6c0df2e --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp8/v4l2.rs @@ -0,0 +1,151 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::v4l2::decoder::stateless::V4l2Picture; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderBackend; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderHandle; +use crate::backend::v4l2::decoder::V4l2StreamInfo; +use crate::backend::v4l2::decoder::ADDITIONAL_REFERENCE_FRAME_BUFFER; +use crate::codec::vp8::parser::Header; +use crate::codec::vp8::parser::MbLfAdjustments; +use crate::codec::vp8::parser::Segmentation; +use crate::decoder::stateless::vp8::StatelessVp8DecoderBackend; +use crate::decoder::stateless::vp8::Vp8; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::device::v4l2::stateless::controls::vp8::V4l2CtrlVp8FrameParams; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Rect; +use crate::Resolution; + +const NUM_REF_FRAMES: usize = 3; + +impl V4l2StreamInfo for &Header { + fn min_num_frames(&self) -> usize { + NUM_REF_FRAMES + ADDITIONAL_REFERENCE_FRAME_BUFFER + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width as u32, self.height as u32)) + } + + fn visible_rect(&self) -> Rect { + Rect::from(self.coded_size()) + } +} + +impl StatelessDecoderBackendPicture for V4l2StatelessDecoderBackend { + type Picture = Rc>>; +} + +impl StatelessVp8DecoderBackend for V4l2StatelessDecoderBackend { + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()> { + self.new_sequence(header, Fourcc::from(b"VP8F")) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?; + let request_buffer = match self.device.alloc_request(timestamp, frame) { + Ok(buffer) => buffer, + _ => return Err(NewPictureError::OutOfOutputBuffers), + }; + let picture = Rc::new(RefCell::new(V4l2Picture::new(request_buffer.clone()))); + request_buffer + .as_ref() + .borrow_mut() + .set_picture_ref(Rc::>>::downgrade(&picture)); + Ok(picture) + } + + fn submit_picture( + &mut self, + picture: Self::Picture, + hdr: &Header, + last_ref: &Option, + golden_ref: &Option, + alt_ref: &Option, + bitstream: &[u8], + segmentation: &Segmentation, + mb_lf_adjust: &MbLfAdjustments, + ) -> StatelessBackendResult { + let mut vp8_frame_params = V4l2CtrlVp8FrameParams::new(); + + let request = picture.borrow_mut().request(); + let mut request = request.as_ref().borrow_mut(); + request.write(bitstream); + + let mut ref_pictures = Vec::>>>::new(); + + let mut last_frame_ts: u64 = 0; + let mut golden_frame_ts: u64 = 0; + let mut alt_frame_ts: u64 = 0; + + match &last_ref { + Some(handle) => { + ref_pictures.push(handle.picture.clone()); + last_frame_ts = handle.timestamp(); + } + None => (), + }; + + match &golden_ref { + Some(handle) => { + ref_pictures.push(handle.picture.clone()); + golden_frame_ts = handle.timestamp(); + } + None => (), + }; + + match &alt_ref { + Some(handle) => { + ref_pictures.push(handle.picture.clone()); + alt_frame_ts = handle.timestamp(); + } + None => (), + }; + + picture.borrow_mut().set_ref_pictures(ref_pictures); + + // last_ref, golden_ref, alt_ref are all None on key frame + // and Some on other frames + vp8_frame_params + .set_loop_filter_params(hdr, mb_lf_adjust) + .set_quantization_params(hdr) + .set_segmentation_params(segmentation) + .set_entropy_params(hdr) + .set_bool_ctx(hdr) + .set_frame_params(hdr, last_frame_ts, golden_frame_ts, alt_frame_ts); + + request.ioctl(&vp8_frame_params)?; + + request.submit()?; + Ok(V4l2StatelessDecoderHandle { + picture: picture.clone(), + stream_info: self.stream_info.clone(), + }) + } +} + +impl StatelessDecoder> { + pub fn new_v4l2(blocking_mode: BlockingMode) -> Result { + Self::new(V4l2StatelessDecoderBackend::new()?, blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp8/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/vp8/vaapi.rs new file mode 100644 index 0000000..db85665 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp8/vaapi.rs @@ -0,0 +1,707 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::convert::TryFrom; +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; +use libva::BufferType; +use libva::Display; +use libva::IQMatrix; +use libva::IQMatrixBufferVP8; +use libva::ProbabilityDataBufferVP8; + +use crate::backend::vaapi::decoder::va_surface_id; +use crate::backend::vaapi::decoder::VaStreamInfo; +use crate::backend::vaapi::decoder::VaapiBackend; +use crate::backend::vaapi::decoder::VaapiPicture; +use crate::codec::vp8::parser::Header; +use crate::codec::vp8::parser::MbLfAdjustments; +use crate::codec::vp8::parser::Segmentation; +use crate::decoder::stateless::vp8::StatelessVp8DecoderBackend; +use crate::decoder::stateless::vp8::Vp8; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::video_frame::VideoFrame; +use crate::Rect; +use crate::Resolution; + +/// The number of surfaces to allocate for this codec. Same as GStreamer's vavp8dec. +const NUM_SURFACES: usize = 7; + +impl VaStreamInfo for &Header { + fn va_profile(&self) -> anyhow::Result { + Ok(libva::VAProfile::VAProfileVP8Version0_3) + } + + fn rt_format(&self) -> anyhow::Result { + Ok(libva::VA_RT_FORMAT_YUV420) + } + + fn min_num_surfaces(&self) -> usize { + NUM_SURFACES + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width as u32, self.height as u32)) + } + + fn visible_rect(&self) -> Rect { + Rect { x: 0, y: 0, width: self.coded_size().width, height: self.coded_size().height } + } +} + +/// A clamp such that min <= x <= max +fn clamp(x: T, low: T, high: T) -> T { + if x > high { + high + } else if x < low { + low + } else { + x + } +} + +fn build_iq_matrix( + frame_hdr: &Header, + segmentation: &Segmentation, +) -> anyhow::Result { + let mut quantization_index: [[u16; 6]; 4] = Default::default(); + + for (i, quantization_index) in quantization_index.iter_mut().enumerate() { + let mut qi_base: i16; + + if segmentation.segmentation_enabled { + qi_base = i16::from(segmentation.quantizer_update_value[i]); + if !segmentation.segment_feature_mode { + qi_base += i16::from(frame_hdr.quant_indices.y_ac_qi); + } + } else { + qi_base = i16::from(frame_hdr.quant_indices.y_ac_qi); + } + + let mut qi = qi_base; + quantization_index[0] = u16::try_from(clamp(qi, 0, 127))?; + qi = qi_base + i16::from(frame_hdr.quant_indices.y_dc_delta); + quantization_index[1] = u16::try_from(clamp(qi, 0, 127))?; + qi = qi_base + i16::from(frame_hdr.quant_indices.y2_dc_delta); + quantization_index[2] = u16::try_from(clamp(qi, 0, 127))?; + qi = qi_base + i16::from(frame_hdr.quant_indices.y2_ac_delta); + quantization_index[3] = u16::try_from(clamp(qi, 0, 127))?; + qi = qi_base + i16::from(frame_hdr.quant_indices.uv_dc_delta); + quantization_index[4] = u16::try_from(clamp(qi, 0, 127))?; + qi = qi_base + i16::from(frame_hdr.quant_indices.uv_ac_delta); + quantization_index[5] = u16::try_from(clamp(qi, 0, 127))?; + } + + Ok(BufferType::IQMatrix(IQMatrix::VP8(IQMatrixBufferVP8::new(quantization_index)))) +} + +fn build_probability_table(frame_hdr: &Header) -> libva::BufferType { + BufferType::Probability(ProbabilityDataBufferVP8::new(frame_hdr.coeff_prob)) +} + +fn build_pic_param( + frame_hdr: &Header, + resolution: &Resolution, + seg: &Segmentation, + adj: &MbLfAdjustments, + last: u32, + golden: u32, + alt: u32, +) -> anyhow::Result { + let mut loop_filter_level: [u8; 4] = Default::default(); + let mut loop_filter_deltas_ref_frame: [i8; 4] = Default::default(); + let mut loop_filter_deltas_mode: [i8; 4] = Default::default(); + + for i in 0..4 { + let mut level; + if seg.segmentation_enabled { + level = seg.lf_update_value[i]; + if !seg.segment_feature_mode { + level += i8::try_from(frame_hdr.loop_filter_level)?; + } + } else { + level = i8::try_from(frame_hdr.loop_filter_level)?; + } + + loop_filter_level[i] = clamp(u8::try_from(level)?, 0, 63); + loop_filter_deltas_ref_frame[i] = adj.ref_frame_delta[i]; + loop_filter_deltas_mode[i] = adj.mb_mode_delta[i]; + } + + let pic_fields = libva::VP8PicFields::new( + u32::from(!frame_hdr.key_frame), + u32::from(frame_hdr.version), + u32::from(seg.segmentation_enabled), + u32::from(seg.update_mb_segmentation_map), + u32::from(seg.update_segment_feature_data), + u32::from(frame_hdr.filter_type), + u32::from(frame_hdr.sharpness_level), + u32::from(adj.loop_filter_adj_enable), + u32::from(adj.mode_ref_lf_delta_update), + u32::from(frame_hdr.sign_bias_golden), + u32::from(frame_hdr.sign_bias_alternate), + u32::from(frame_hdr.mb_no_coeff_skip), + u32::from(frame_hdr.loop_filter_level == 0), + ); + + let bool_coder_ctx = libva::BoolCoderContextVPX::new( + u8::try_from(frame_hdr.bd_range)?, + u8::try_from(frame_hdr.bd_value)?, + u8::try_from(frame_hdr.bd_count)?, + ); + + let pic_param = libva::PictureParameterBufferVP8::new( + resolution.width, + resolution.height, + last, + golden, + alt, + &pic_fields, + seg.segment_prob, + loop_filter_level, + loop_filter_deltas_ref_frame, + loop_filter_deltas_mode, + frame_hdr.prob_skip_false, + frame_hdr.prob_intra, + frame_hdr.prob_last, + frame_hdr.prob_golden, + frame_hdr.mode_probs.intra_16x16_prob, + frame_hdr.mode_probs.intra_chroma_prob, + frame_hdr.mv_prob, + &bool_coder_ctx, + ); + + Ok(libva::BufferType::PictureParameter(libva::PictureParameter::VP8(pic_param))) +} + +fn build_slice_param(frame_hdr: &Header, slice_size: usize) -> anyhow::Result { + let mut partition_size: [u32; 9] = Default::default(); + let num_of_partitions = frame_hdr.num_dct_partitions() + 1; + + partition_size[0] = frame_hdr.first_part_size - ((frame_hdr.header_size + 7) >> 3); + + partition_size[1..num_of_partitions] + .clone_from_slice(&frame_hdr.partition_size[..(num_of_partitions - 1)]); + + Ok(libva::BufferType::SliceParameter(libva::SliceParameter::VP8( + libva::SliceParameterBufferVP8::new( + u32::try_from(slice_size)?, + u32::from(frame_hdr.data_chunk_size), + 0, + frame_hdr.header_size, + u8::try_from(num_of_partitions)?, + partition_size, + ), + ))) +} + +impl StatelessDecoderBackendPicture for VaapiBackend { + type Picture = VaapiPicture; +} + +impl StatelessVp8DecoderBackend for VaapiBackend { + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()> { + self.new_sequence(header) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + Ok(VaapiPicture::new( + timestamp, + Rc::clone(&self.context), + alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, + )) + } + + fn submit_picture( + &mut self, + mut picture: Self::Picture, + hdr: &Header, + last_ref: &Option, + golden_ref: &Option, + alt_ref: &Option, + bitstream: &[u8], + segmentation: &Segmentation, + mb_lf_adjust: &MbLfAdjustments, + ) -> StatelessBackendResult { + let last_ref = va_surface_id(last_ref); + let golden_ref = va_surface_id(golden_ref); + let alt_ref = va_surface_id(alt_ref); + + let coded_resolution = + &self.stream_info().ok_or(anyhow!("No stream info found!"))?.coded_resolution; + let context = &self.context; + + let iq_buffer = context + .create_buffer(build_iq_matrix(hdr, segmentation)?) + .context("while creating IQ matrix buffer")?; + + let probs = context + .create_buffer(build_probability_table(hdr)) + .context("while creating probability table buffer")?; + + let pic_param = context + .create_buffer(build_pic_param( + hdr, + &coded_resolution, + segmentation, + mb_lf_adjust, + last_ref, + golden_ref, + alt_ref, + )?) + .context("while creating pic params buffer")?; + + let slice_param = context + .create_buffer(build_slice_param(hdr, bitstream.len())?) + .context("while creating slice params buffer")?; + + let slice_data = context + .create_buffer(libva::BufferType::SliceData(Vec::from(bitstream))) + .context("while creating slice data buffer")?; + + // Add buffers with the parsed data. + picture.add_buffer(iq_buffer); + picture.add_buffer(probs); + picture.add_buffer(pic_param); + picture.add_buffer(slice_param); + picture.add_buffer(slice_data); + + self.process_picture::(picture) + } +} + +impl StatelessDecoder> { + // Creates a new instance of the decoder using the VAAPI backend. + pub fn new_vaapi( + display: Rc, + blocking_mode: BlockingMode, + ) -> Result { + Self::new(VaapiBackend::new(display, false), blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::BufferType; + use libva::Display; + use libva::IQMatrix; + use libva::PictureParameter; + use libva::SliceParameter; + + use crate::bitstream_utils::IvfIterator; + use crate::codec::vp8::parser::Parser; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + use crate::Resolution; + + use super::*; + + /// Run `test` using the vaapi decoder, in both blocking and non-blocking modes. + fn test_decoder_vaapi( + test: &TestStream, + output_format: DecodedFormat, + blocking_mode: BlockingMode, + ) { + let display = Display::open().unwrap(); + let decoder = StatelessDecoder::::new_vaapi::<()>(display, blocking_mode).unwrap(); + + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + output_format, + blocking_mode, + ) + }, + decoder, + test, + true, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_block() { + use crate::decoder::stateless::vp8::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::Blocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_nonblock() { + use crate::decoder::stateless::vp8::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::NonBlocking); + } + + #[test] + /// Check that we are able to build the VA picture parameters from the stream properly. + fn build_pic_params() { + const TEST_STREAM: &[u8] = include_bytes!("../../../codec/vp8/test_data/test-25fps.vp8"); + const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_0: &[u8] = + include_bytes!("../../../codec/vp8/test_data/test-25fps-vp8-probability-table-0.bin"); + const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_1: &[u8] = + include_bytes!("../../../codec/vp8/test_data/test-25fps-vp8-probability-table-1.bin"); + const TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_2: &[u8] = + include_bytes!("../../../codec/vp8/test_data/test-25fps-vp8-probability-table-2.bin"); + + let mut parser: Parser = Default::default(); + let mut ivf_iter = IvfIterator::new(TEST_STREAM); + + // FRAME 0 + + let packet = ivf_iter.next().unwrap(); + assert_eq!(packet.len(), 14788); + + let frame = parser.parse_frame(packet).unwrap(); + + let resolution = + Resolution { width: frame.header.width as u32, height: frame.header.height as u32 }; + + let pic_param = build_pic_param( + &frame.header, + &resolution, + parser.segmentation(), + parser.mb_lf_adjust(), + libva::VA_INVALID_SURFACE, + libva::VA_INVALID_SURFACE, + libva::VA_INVALID_SURFACE, + ) + .unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP8(pic_param)) => pic_param, + _ => panic!(), + }; + + let iq_matrix = build_iq_matrix(&frame.header, parser.segmentation()).unwrap(); + let iq_matrix = match iq_matrix { + BufferType::IQMatrix(IQMatrix::VP8(iq_matrix)) => iq_matrix, + _ => panic!(), + }; + + let prob_table = build_probability_table(&frame.header); + let prob_table = match prob_table { + BufferType::Probability(prob_table) => prob_table, + _ => panic!(), + }; + + let slice_param = build_slice_param(&frame.header, packet.len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP8(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(iq_matrix.inner().quantization_index, [[4; 6]; 4]); + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for l in 0..11 { + const OFF_I: usize = 8 * 3 * 11; + const OFF_J: usize = 3 * 11; + const OFF_K: usize = 11; + // maybe std::transmute? + assert_eq!( + prob_table.inner().dct_coeff_probs[i][j][k][l], + TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_0 + [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l] + ); + } + } + } + } + + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().last_ref_frame, libva::VA_INVALID_SURFACE); + assert_eq!(pic_param.inner().golden_ref_frame, libva::VA_INVALID_SURFACE); + assert_eq!(pic_param.inner().alt_ref_frame, libva::VA_INVALID_SURFACE); + assert_eq!(pic_param.inner().out_of_loop_frame, libva::VA_INVALID_SURFACE); + + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP8PicFields::new(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1).inner().value + }); + + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]); + assert_eq!(pic_param.inner().loop_filter_level, [0; 4]); + assert_eq!(pic_param.inner().loop_filter_deltas_ref_frame, [2, 0, -2, -2]); + assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]); + assert_eq!(pic_param.inner().prob_skip_false, 0xbe); + assert_eq!(pic_param.inner().prob_intra, 0); + assert_eq!(pic_param.inner().prob_last, 0); + assert_eq!(pic_param.inner().prob_gf, 0); + + assert_eq!(pic_param.inner().y_mode_probs, [0x91, 0x9c, 0xa3, 0x80]); + assert_eq!(pic_param.inner().uv_mode_probs, [0x8e, 0x72, 0xb7]); + assert_eq!( + pic_param.inner().mv_probs[0], + [ + 0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81, 0x84, 0x4b, 0x91, + 0xb2, 0xce, 0xef, 0xfe, 0xfe + ] + ); + assert_eq!( + pic_param.inner().mv_probs[1], + [ + 0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82, 0x82, 0x4a, 0x94, + 0xb4, 0xcb, 0xec, 0xfe, 0xfe, + ] + ); + + assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xfc); + assert_eq!(pic_param.inner().bool_coder_ctx.value, 0x39); + assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x0); + + assert_eq!( + slice_param.inner(), + libva::SliceParameterBufferVP8::new( + 14788, + 10, + 0, + 3040, + 2, + [926, 13472, 0, 0, 0, 0, 0, 0, 0], + ) + .inner(), + ); + + // FRAME 1 + + let packet = ivf_iter.next().unwrap(); + assert_eq!(packet.len(), 257); + + let frame = parser.parse_frame(packet).unwrap(); + + let pic_param = build_pic_param( + &frame.header, + &resolution, + parser.segmentation(), + parser.mb_lf_adjust(), + 0, + 0, + 0, + ) + .unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP8(pic_param)) => pic_param, + _ => panic!(), + }; + + let iq_matrix = build_iq_matrix(&frame.header, parser.segmentation()).unwrap(); + let iq_matrix = match iq_matrix { + BufferType::IQMatrix(IQMatrix::VP8(iq_matrix)) => iq_matrix, + _ => panic!(), + }; + + let prob_table = build_probability_table(&frame.header); + let prob_table = match prob_table { + BufferType::Probability(prob_table) => prob_table, + _ => panic!(), + }; + + let slice_param = build_slice_param(&frame.header, packet.len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP8(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(iq_matrix.inner().quantization_index, [[0x7f; 6]; 4]); + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for l in 0..11 { + const OFF_I: usize = 8 * 3 * 11; + const OFF_J: usize = 3 * 11; + const OFF_K: usize = 11; + // maybe std::transmute? + assert_eq!( + prob_table.inner().dct_coeff_probs[i][j][k][l], + TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_1 + [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l] + ); + } + } + } + } + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().last_ref_frame, 0); + assert_eq!(pic_param.inner().golden_ref_frame, 0); + assert_eq!(pic_param.inner().alt_ref_frame, 0); + assert_eq!(pic_param.inner().out_of_loop_frame, libva::VA_INVALID_SURFACE); + + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP8PicFields::new(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0).inner().value + }); + + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]); + assert_eq!(pic_param.inner().loop_filter_level, [44; 4]); + assert_eq!(pic_param.inner().loop_filter_deltas_ref_frame, [2, 0, -2, -2]); + assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]); + assert_eq!(pic_param.inner().prob_skip_false, 0x11); + assert_eq!(pic_param.inner().prob_intra, 0x2a); + assert_eq!(pic_param.inner().prob_last, 0xff); + assert_eq!(pic_param.inner().prob_gf, 0x80); + + assert_eq!(pic_param.inner().y_mode_probs, [0x70, 0x56, 0x8c, 0x25]); + assert_eq!(pic_param.inner().uv_mode_probs, [0xa2, 0x65, 0xcc]); + assert_eq!( + pic_param.inner().mv_probs[0], + [ + 0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81, 0x84, 0x4b, 0x91, + 0xb2, 0xce, 0xef, 0xfe, 0xfe, + ] + ); + assert_eq!( + pic_param.inner().mv_probs[1], + [ + 0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82, 0x82, 0x4a, 0x94, + 0xb4, 0xcb, 0xec, 0xfe, 0xfe, + ] + ); + + assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xde); + assert_eq!(pic_param.inner().bool_coder_ctx.value, 0x39); + assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x7); + + assert_eq!( + slice_param.inner(), + libva::SliceParameterBufferVP8::new(257, 3, 0, 129, 2, [143, 94, 0, 0, 0, 0, 0, 0, 0],) + .inner() + ); + + // FRAME 2 + + let packet = ivf_iter.next().unwrap(); + assert_eq!(packet.len(), 131); + + let frame = parser.parse_frame(packet).unwrap(); + + let pic_param = build_pic_param( + &frame.header, + &resolution, + parser.segmentation(), + parser.mb_lf_adjust(), + 1, + 0, + 0, + ) + .unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP8(pic_param)) => pic_param, + _ => panic!(), + }; + + let iq_matrix = build_iq_matrix(&frame.header, parser.segmentation()).unwrap(); + let iq_matrix = match iq_matrix { + BufferType::IQMatrix(IQMatrix::VP8(iq_matrix)) => iq_matrix, + _ => panic!(), + }; + + let prob_table = build_probability_table(&frame.header); + let prob_table = match prob_table { + BufferType::Probability(prob_table) => prob_table, + _ => panic!(), + }; + + let slice_param = build_slice_param(&frame.header, packet.len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP8(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(iq_matrix.inner().quantization_index, [[0x7f; 6]; 4]); + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for l in 0..11 { + const OFF_I: usize = 8 * 3 * 11; + const OFF_J: usize = 3 * 11; + const OFF_K: usize = 11; + // maybe std::transmute? + assert_eq!( + prob_table.inner().dct_coeff_probs[i][j][k][l], + TEST_25_FPS_VP8_STREAM_PROBABILITY_TABLE_2 + [(i * OFF_I) + (j * OFF_J) + (k * OFF_K) + l] + ); + } + } + } + } + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().last_ref_frame, 1); + assert_eq!(pic_param.inner().golden_ref_frame, 0); + assert_eq!(pic_param.inner().alt_ref_frame, 0); + assert_eq!(pic_param.inner().out_of_loop_frame, libva::VA_INVALID_SURFACE); + + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP8PicFields::new(1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0).inner().value + }); + + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 3]); + assert_eq!(pic_param.inner().loop_filter_level, [28; 4]); + assert_eq!(pic_param.inner().loop_filter_deltas_ref_frame, [2, 0, -2, -2]); + assert_eq!(pic_param.inner().loop_filter_deltas_mode, [4, -2, 2, 4]); + assert_eq!(pic_param.inner().prob_skip_false, 0x6); + assert_eq!(pic_param.inner().prob_intra, 0x1); + assert_eq!(pic_param.inner().prob_last, 0xf8); + assert_eq!(pic_param.inner().prob_gf, 0xff); + + assert_eq!(pic_param.inner().y_mode_probs, [0x70, 0x56, 0x8c, 0x25]); + assert_eq!(pic_param.inner().uv_mode_probs, [0xa2, 0x65, 0xcc]); + assert_eq!( + pic_param.inner().mv_probs[0], + [ + 0xa2, 0x80, 0xe1, 0x92, 0xac, 0x93, 0xd6, 0x27, 0x9c, 0x80, 0x81, 0x84, 0x4b, 0x91, + 0xb2, 0xce, 0xef, 0xfe, 0xfe, + ] + ); + assert_eq!( + pic_param.inner().mv_probs[1], + [ + 0xa4, 0x80, 0xcc, 0xaa, 0x77, 0xeb, 0x8c, 0xe6, 0xe4, 0x80, 0x82, 0x82, 0x4a, 0x94, + 0xb4, 0xcb, 0xec, 0xfe, 0xfe, + ] + ); + + assert_eq!(pic_param.inner().bool_coder_ctx.range, 0xb1); + assert_eq!(pic_param.inner().bool_coder_ctx.value, 0xd); + assert_eq!(pic_param.inner().bool_coder_ctx.count, 0x2); + + assert_eq!( + slice_param.inner(), + libva::SliceParameterBufferVP8::new(131, 3, 0, 86, 2, [66, 51, 0, 0, 0, 0, 0, 0, 0],) + .inner() + ); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp9.rs b/vendor/cros-codecs/src/decoder/stateless/vp9.rs new file mode 100644 index 0000000..1939bd3 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp9.rs @@ -0,0 +1,461 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(test)] +mod dummy; +#[cfg(feature = "v4l2")] +mod v4l2; +#[cfg(feature = "vaapi")] +mod vaapi; + +use std::os::fd::AsFd; +use std::os::fd::BorrowedFd; + +use log::debug; + +use crate::codec::vp9::parser::BitDepth; +use crate::codec::vp9::parser::Frame; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::Parser; +use crate::codec::vp9::parser::Profile; +use crate::codec::vp9::parser::Segmentation; +use crate::codec::vp9::parser::MAX_SEGMENTS; +use crate::codec::vp9::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::DecodingState; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessCodec; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::stateless::StatelessVideoDecoder; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::decoder::DecoderEvent; +use crate::decoder::StreamInfo; +use crate::Resolution; + +/// Stateless backend methods specific to VP9. +pub trait StatelessVp9DecoderBackend: + StatelessDecoderBackend + StatelessDecoderBackendPicture +{ + /// Called when new stream parameters are found. + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()>; + + /// Allocate all resources required to process a new picture. + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult; + + /// Called when the decoder wants the backend to finish the decoding + /// operations for `picture`. + /// + /// This call will assign the ownership of the BackendHandle to the Picture + /// and then assign the ownership of the Picture to the Handle. + fn submit_picture( + &mut self, + picture: Self::Picture, + hdr: &Header, + reference_frames: &[Option; NUM_REF_FRAMES], + bitstream: &[u8], + segmentation: &[Segmentation; MAX_SEGMENTS], + ) -> StatelessBackendResult; +} + +pub struct Vp9DecoderState { + /// VP9 bitstream parser. + parser: Parser, + + /// The reference frames in use. + reference_frames: [Option; NUM_REF_FRAMES], + + /// Per-segment data. + segmentation: [Segmentation; MAX_SEGMENTS], + + /// Keeps track of the last values seen for negotiation purposes. + negotiation_info: NegotiationInfo, +} + +impl Default for Vp9DecoderState +where + H: DecodedHandle, +{ + fn default() -> Self { + Self { + parser: Default::default(), + reference_frames: Default::default(), + segmentation: Default::default(), + negotiation_info: Default::default(), + } + } +} + +/// Keeps track of the last values seen for negotiation purposes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct NegotiationInfo { + /// The current coded resolution + coded_resolution: Resolution, + /// Cached value for bit depth + bit_depth: BitDepth, + /// Cached value for profile + profile: Profile, +} + +impl From<&Header> for NegotiationInfo { + fn from(hdr: &Header) -> Self { + NegotiationInfo { + coded_resolution: Resolution { width: hdr.width, height: hdr.height }, + bit_depth: hdr.bit_depth, + profile: hdr.profile, + } + } +} + +/// [`StatelessCodec`] structure to use in order to create a VP9 stateless decoder. +/// +/// # Accepted input +/// +/// the VP9 specification requires the last byte of the chunk to contain the superframe marker. +/// Thus, a decoder using this codec processes exactly one encoded chunk per call to +/// [`StatelessDecoder::decode`], and always returns the size of the passed input if successful. +pub struct Vp9; + +impl StatelessCodec for Vp9 { + type FormatInfo = Header; + type DecoderState = Vp9DecoderState; +} + +impl StatelessDecoder +where + B: StatelessVp9DecoderBackend, + B::Handle: Clone, +{ + fn update_references( + reference_frames: &mut [Option; NUM_REF_FRAMES], + picture: &B::Handle, + mut refresh_frame_flags: u8, + ) -> anyhow::Result<()> { + #[allow(clippy::needless_range_loop)] + for i in 0..NUM_REF_FRAMES { + if (refresh_frame_flags & 1) == 1 { + debug!("Replacing reference frame {}", i); + reference_frames[i] = Some(picture.clone()); + } + + refresh_frame_flags >>= 1; + } + + Ok(()) + } + + /// Handle a frame which `show_existing_frame` flag is `true`. + fn handle_show_existing_frame(&mut self, frame_to_show_map_idx: u8) -> Result<(), DecodeError> { + // Frame to be shown. Because the spec mandates that frame_to_show_map_idx references a + // valid entry in the DPB, an non-existing index means that the stream is invalid. + let idx = usize::from(frame_to_show_map_idx); + let ref_frame = self + .codec + .reference_frames + .get(idx) + .ok_or_else(|| anyhow::anyhow!("invalid reference frame index in header"))? + .as_ref() + .ok_or_else(|| anyhow::anyhow!("empty reference frame referenced in frame header"))?; + + // We are done, no further processing needed. + let decoded_handle = ref_frame.clone(); + + self.ready_queue.push(decoded_handle); + + Ok(()) + } + + /// Decode a single frame. + fn handle_frame(&mut self, frame: &Frame, picture: B::Picture) -> Result<(), DecodeError> { + let refresh_frame_flags = frame.header.refresh_frame_flags; + + Segmentation::update_segmentation(&mut self.codec.segmentation, &frame.header); + + let decoded_handle = self.backend.submit_picture( + picture, + &frame.header, + &self.codec.reference_frames, + frame.as_ref(), + &self.codec.segmentation, + )?; + + if self.blocking_mode == BlockingMode::Blocking { + decoded_handle.sync()?; + } + + // Do DPB management + Self::update_references( + &mut self.codec.reference_frames, + &decoded_handle, + refresh_frame_flags, + )?; + + if frame.header.show_frame { + self.ready_queue.push(decoded_handle); + } + + Ok(()) + } + + fn negotiation_possible(&self, hdr: &Header, old_negotiation_info: &NegotiationInfo) -> bool { + let negotiation_info = NegotiationInfo::from(hdr); + + if negotiation_info.coded_resolution.width == 0 + || negotiation_info.coded_resolution.height == 0 + { + false + } else { + *old_negotiation_info != negotiation_info + } + } +} + +impl StatelessVideoDecoder for StatelessDecoder +where + B: StatelessVp9DecoderBackend, + B::Handle: Clone + 'static, +{ + type Handle = B::Handle; + + fn decode( + &mut self, + timestamp: u64, + bitstream: &[u8], + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> Result { + let frames = self + .codec + .parser + .parse_chunk(bitstream) + .map_err(|err| DecodeError::ParseFrameError(err))?; + + self.wait_for_drc_flush()?; + + // With SVC, the first frame will usually be a key-frame, with + // inter-frames carrying the other layers. + // + // We do not want each of those to be considered as a separate DRC + // event. Not only that, allowing them to be will cause an infinite + // loop. + // + // Instead, negotiate based on the largest spatial layer. That will be + // enough to house the other layers in between. + let largest_in_superframe = frames.iter().max_by(|&a, &b| { + let a_res = Resolution::from((a.header.width, a.header.height)); + let b_res = Resolution::from((b.header.width, b.header.height)); + if a_res == b_res { + std::cmp::Ordering::Equal + } else if a_res.can_contain(b_res) { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Less + } + }); + + if let Some(frame) = largest_in_superframe { + if self.negotiation_possible(&frame.header, &self.codec.negotiation_info) { + if matches!(self.decoding_state, DecodingState::Decoding) { + // DRC occurs when a key frame is seen, the format is different, + // and the decoder is already decoding frames. + self.flush()?; + self.decoding_state = DecodingState::FlushingForDRC; + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + self.backend.new_sequence(&frame.header)?; + self.await_format_change(frame.header.clone()); + } else if matches!(self.decoding_state, DecodingState::Reset) { + // We can resume decoding since the decoding parameters have not changed. + self.decoding_state = DecodingState::Decoding; + } + } + + match &mut self.decoding_state { + // Skip input until we get information from the stream. + DecodingState::AwaitingStreamInfo | DecodingState::Reset => (), + // Ask the client to confirm the format before we can process this. + DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { + // Start signaling the awaiting format event to process a format change. + self.awaiting_format_event.write(1).unwrap(); + return Err(DecodeError::CheckEvents); + } + DecodingState::Decoding => { + // First allocate all the pictures we need for this superframe. + let num_required_pictures = + frames.iter().filter(|f| !f.header.show_existing_frame).count(); + let frames_with_pictures = frames + .into_iter() + .enumerate() + .map(|(i, frame)| { + if frame.header.show_existing_frame { + Ok((frame, None)) + } else { + self.backend + .new_picture(timestamp, alloc_cb) + .map_err(|e| match e { + NewPictureError::OutOfOutputBuffers => { + DecodeError::NotEnoughOutputBuffers( + num_required_pictures - i, + ) + } + e => DecodeError::from(e), + }) + .map(|picture| (frame, Some(picture))) + } + }) + .collect::, _>>()?; + + // Then process each frame. + for (frame, picture) in frames_with_pictures { + match picture { + None => { + self.handle_show_existing_frame(frame.header.frame_to_show_map_idx)? + } + Some(picture) => self.handle_frame(&frame, picture)?, + } + } + } + } + + Ok(bitstream.len()) + } + + fn flush(&mut self) -> Result<(), DecodeError> { + // Note: all the submitted frames are already in the ready queue. + self.codec.reference_frames = Default::default(); + self.decoding_state = DecodingState::Reset; + + Ok(()) + } + + fn next_event(&mut self) -> Option> { + self.query_next_event(|decoder, hdr| { + decoder.codec.negotiation_info = hdr.into(); + }) + } + + fn stream_info(&self) -> Option<&StreamInfo> { + self.backend.stream_info() + } + + fn poll_fd(&self) -> BorrowedFd { + self.epoll_fd.0.as_fd() + } +} + +#[cfg(test)] +pub mod tests { + use crate::bitstream_utils::IvfIterator; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::vp9::Vp9; + use crate::decoder::stateless::StatelessDecoder; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. + fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { + let decoder = StatelessDecoder::::new_dummy(blocking_mode).unwrap(); + + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + blocking_mode, + ) + }, + decoder, + test, + false, + false, + ); + } + + /// Same as Chromium's test-25fps.vp8 + pub const DECODE_TEST_25FPS: TestStream = TestStream { + stream: include_bytes!("../../codec/vp9/test_data/test-25fps.vp9"), + crcs: include_str!("../../codec/vp9/test_data/test-25fps.vp9.crc"), + }; + + #[test] + fn test_25fps_block() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); + } + + #[test] + fn test_25fps_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); + } + + // Remuxed from the original matroska source in libvpx using ffmpeg: + // ffmpeg -i vp90-2-10-show-existing-frame.webm/vp90-2-10-show-existing-frame.webm -c:v copy /tmp/vp90-2-10-show-existing-frame.vp9.ivf + pub const DECODE_TEST_25FPS_SHOW_EXISTING_FRAME: TestStream = TestStream { + stream: include_bytes!("../../codec/vp9/test_data/vp90-2-10-show-existing-frame.vp9.ivf"), + crcs: include_str!("../../codec/vp9/test_data/vp90-2-10-show-existing-frame.vp9.ivf.crc"), + }; + + #[test] + fn show_existing_frame_block() { + test_decoder_dummy(&DECODE_TEST_25FPS_SHOW_EXISTING_FRAME, BlockingMode::Blocking); + } + + #[test] + fn show_existing_frame_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS_SHOW_EXISTING_FRAME, BlockingMode::NonBlocking); + } + + pub const DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2: TestStream = TestStream { + stream: include_bytes!("../../codec/vp9/test_data/vp90-2-10-show-existing-frame2.vp9.ivf"), + crcs: include_str!("../../codec/vp9/test_data/vp90-2-10-show-existing-frame2.vp9.ivf.crc"), + }; + + #[test] + fn show_existing_frame2_block() { + test_decoder_dummy(&DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2, BlockingMode::Blocking); + } + + #[test] + fn show_existing_frame2_nonblock() { + test_decoder_dummy(&DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2, BlockingMode::NonBlocking); + } + + // Remuxed from the original matroska source in libvpx using ffmpeg: + // ffmpeg -i vp90-2-10-show-existing-frame.webm/vp90-2-10-show-existing-frame.webm -c:v copy /tmp/vp90-2-10-show-existing-frame.vp9.ivf + // There are some weird padding issues introduced by GStreamer for + // resolutions that are not multiple of 4, so we're ignoring CRCs for + // this one. + pub const DECODE_RESOLUTION_CHANGE_500FRAMES: TestStream = TestStream { + stream: include_bytes!("../../codec/vp9/test_data/resolution_change_500frames-vp9.ivf"), + crcs: include_str!("../../codec/vp9/test_data/resolution_change_500frames-vp9.ivf.crc"), + }; + + #[test] + fn test_resolution_change_500frames_block() { + test_decoder_dummy(&DECODE_RESOLUTION_CHANGE_500FRAMES, BlockingMode::Blocking); + } + + #[test] + fn test_resolution_change_500frames_nonblock() { + test_decoder_dummy(&DECODE_RESOLUTION_CHANGE_500FRAMES, BlockingMode::Blocking); + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp9/dummy.rs b/vendor/cros-codecs/src/decoder/stateless/vp9/dummy.rs new file mode 100644 index 0000000..c3c1a99 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp9/dummy.rs @@ -0,0 +1,51 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This file contains a dummy backend whose only purpose is to let the decoder +//! run so we can test it in isolation. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::backend::dummy::decoder::Backend; +use crate::backend::dummy::decoder::Handle; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::MAX_SEGMENTS; +use crate::codec::vp9::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::vp9::Segmentation; +use crate::decoder::stateless::vp9::StatelessVp9DecoderBackend; +use crate::decoder::stateless::vp9::Vp9; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::BlockingMode; + +impl StatelessVp9DecoderBackend for Backend { + fn new_sequence(&mut self, _: &Header) -> StatelessBackendResult<()> { + Ok(()) + } + + fn new_picture(&mut self, _: u64) -> NewPictureResult { + Ok(()) + } + + fn submit_picture( + &mut self, + _: Self::Picture, + _: &Header, + _: &[Option; NUM_REF_FRAMES], + _: &[u8], + _: &[Segmentation; MAX_SEGMENTS], + ) -> StatelessBackendResult { + Ok(Handle { handle: Rc::new(RefCell::new(Default::default())) }) + } +} + +impl StatelessDecoder { + // Creates a new instance of the decoder using the dummy backend. + pub fn new_dummy(blocking_mode: BlockingMode) -> Result { + Self::new(Backend::new(), blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp9/v4l2.rs b/vendor/cros-codecs/src/decoder/stateless/vp9/v4l2.rs new file mode 100644 index 0000000..8933a48 --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp9/v4l2.rs @@ -0,0 +1,154 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::rc::Rc; + +use v4l2r::ioctl; + +use crate::backend::v4l2::decoder::stateless::V4l2Picture; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderBackend; +use crate::backend::v4l2::decoder::stateless::V4l2StatelessDecoderHandle; +use crate::backend::v4l2::decoder::V4l2StreamInfo; +use crate::backend::v4l2::decoder::ADDITIONAL_REFERENCE_FRAME_BUFFER; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::Segmentation; +use crate::codec::vp9::parser::ALTREF_FRAME; +use crate::codec::vp9::parser::GOLDEN_FRAME; +use crate::codec::vp9::parser::LAST_FRAME; +use crate::codec::vp9::parser::MAX_SEGMENTS; +use crate::codec::vp9::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::vp9::StatelessVp9DecoderBackend; +use crate::decoder::stateless::vp9::Vp9; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::device::v4l2::stateless::controls::vp9::V4l2CtrlVp9FrameParams; +use crate::device::v4l2::stateless::controls::vp9::Vp9V4l2Control; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Rect; +use crate::Resolution; + +impl V4l2StreamInfo for &Header { + fn min_num_frames(&self) -> usize { + NUM_REF_FRAMES + ADDITIONAL_REFERENCE_FRAME_BUFFER + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width, self.height)) + } + + fn visible_rect(&self) -> Rect { + Rect::from(((0, 0), (self.render_width, self.render_height))) + } +} + +impl StatelessDecoderBackendPicture for V4l2StatelessDecoderBackend { + type Picture = Rc>>; +} + +impl StatelessVp9DecoderBackend for V4l2StatelessDecoderBackend { + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()> { + self.new_sequence(header, Fourcc::from(b"VP9F")) + } + + fn new_picture( + &mut self, + _timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + let timestamp = self.frame_counter; + let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?; + let request_buffer = match self.device.alloc_request(timestamp, frame) { + Ok(buffer) => buffer, + _ => return Err(NewPictureError::OutOfOutputBuffers), + }; + let picture = Rc::new(RefCell::new(V4l2Picture::new(request_buffer.clone()))); + request_buffer + .as_ref() + .borrow_mut() + .set_picture_ref(Rc::>>::downgrade(&picture)); + + self.frame_counter = self.frame_counter + 1; + Ok(picture) + } + + fn submit_picture( + &mut self, + picture: Self::Picture, + hdr: &Header, + reference_frames: &[Option; NUM_REF_FRAMES], + bitstream: &[u8], + _segmentation: &[Segmentation; MAX_SEGMENTS], + ) -> StatelessBackendResult { + let mut vp9_frame_params = V4l2CtrlVp9FrameParams::new(); + + let last_frame_idx = hdr.ref_frame_idx[LAST_FRAME - 1]; + let golden_frame_idx = hdr.ref_frame_idx[GOLDEN_FRAME - 1]; + let alt_frame_idx = hdr.ref_frame_idx[ALTREF_FRAME - 1]; + + let last_frame_ts = match &reference_frames[last_frame_idx as usize] { + Some(handle) => handle.timestamp(), + None => 0, + }; + + let golden_frame_ts = match &reference_frames[golden_frame_idx as usize] { + Some(handle) => handle.timestamp(), + None => 0, + }; + + let alt_frame_ts = match &reference_frames[alt_frame_idx as usize] { + Some(handle) => handle.timestamp(), + None => 0, + }; + + vp9_frame_params + .set_loop_filter_params(hdr) + .set_quantization_params(hdr) + .set_segmentation_params(hdr) + .set_frame_params(hdr, last_frame_ts, golden_frame_ts, alt_frame_ts); + + let mut ctrl = Vp9V4l2Control::from(&vp9_frame_params); + + let request = picture.borrow_mut().request(); + let mut request = request.as_ref().borrow_mut(); + + // We have to do this manually since v4l2r does not directly support VP9 + let which = request.which(); + ioctl::s_ext_ctrls(&self.device, which, &mut ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + + let mut reference_pictures = Vec::>>>::new(); + for frame in reference_frames { + if frame.is_some() { + reference_pictures.push(frame.as_ref().unwrap().picture.clone()); + } + } + picture.borrow_mut().set_ref_pictures(reference_pictures); + + request.write(bitstream); + request.submit()?; + + Ok(V4l2StatelessDecoderHandle { + picture: picture.clone(), + stream_info: self.stream_info.clone(), + }) + } +} + +impl StatelessDecoder> { + pub fn new_v4l2(blocking_mode: BlockingMode) -> Result { + Self::new(V4l2StatelessDecoderBackend::new()?, blocking_mode) + } +} diff --git a/vendor/cros-codecs/src/decoder/stateless/vp9/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/vp9/vaapi.rs new file mode 100644 index 0000000..8acaa5c --- /dev/null +++ b/vendor/cros-codecs/src/decoder/stateless/vp9/vaapi.rs @@ -0,0 +1,651 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use anyhow::anyhow; +use anyhow::Context; +use libva::Display; +use libva::SegmentParameterVP9; + +use crate::backend::vaapi::decoder::va_surface_id; +use crate::backend::vaapi::decoder::VaStreamInfo; +use crate::backend::vaapi::decoder::VaapiBackend; +use crate::backend::vaapi::decoder::VaapiPicture; +use crate::codec::vp9::parser::BitDepth; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::Profile; +use crate::codec::vp9::parser::ALTREF_FRAME; +use crate::codec::vp9::parser::GOLDEN_FRAME; +use crate::codec::vp9::parser::LAST_FRAME; +use crate::codec::vp9::parser::MAX_SEGMENTS; +use crate::codec::vp9::parser::NUM_REF_FRAMES; +use crate::decoder::stateless::vp9::Segmentation; +use crate::decoder::stateless::vp9::StatelessVp9DecoderBackend; +use crate::decoder::stateless::vp9::Vp9; +use crate::decoder::stateless::NewPictureError; +use crate::decoder::stateless::NewPictureResult; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::decoder::stateless::StatelessDecoder; +use crate::decoder::stateless::StatelessDecoderBackend; +use crate::decoder::stateless::StatelessDecoderBackendPicture; +use crate::decoder::BlockingMode; +use crate::decoder::DecodedHandle; +use crate::video_frame::VideoFrame; +use crate::Rect; +use crate::Resolution; + +/// The number of surfaces to allocate for this codec. +const NUM_SURFACES: usize = 12; + +/// Returns the RT format matching the input parameters. +fn get_rt_format( + profile: Profile, + bit_depth: BitDepth, + subsampling_x: bool, + subsampling_y: bool, +) -> anyhow::Result { + match profile { + Profile::Profile0 => Ok(libva::VA_RT_FORMAT_YUV420), + Profile::Profile1 => { + if subsampling_x && !subsampling_y { + Ok(libva::VA_RT_FORMAT_YUV422) + } else if !subsampling_x && !subsampling_y { + Ok(libva::VA_RT_FORMAT_YUV444) + } else { + Err(anyhow!( + "Unsupported subsampling for profile 1: X: {:?} Y: {:?}", + subsampling_x, + subsampling_y + )) + } + } + Profile::Profile2 => match bit_depth { + BitDepth::Depth8 => { + Err(anyhow!("Unsupported bit depth for profile 2: {:?}", bit_depth)) + } + BitDepth::Depth10 => Ok(libva::VA_RT_FORMAT_YUV420_10), + BitDepth::Depth12 => Ok(libva::VA_RT_FORMAT_YUV420_12), + }, + Profile::Profile3 => { + if subsampling_x && !subsampling_y { + match bit_depth { + BitDepth::Depth8 => Err(anyhow!( + "Unsupported (subsampling_x, subsampling_y, bit depth) combination for profile 3: ({:?}, {:?}, {:?})", + subsampling_x, + subsampling_y, + bit_depth + )), + BitDepth::Depth10 => Ok(libva::VA_RT_FORMAT_YUV422_10), + BitDepth::Depth12 => Ok(libva::VA_RT_FORMAT_YUV422_12), + } + } else if !subsampling_x && !subsampling_y { + match bit_depth { + BitDepth::Depth8 => Err(anyhow!( + "Unsupported (subsampling_x, subsampling_y, bit depth) combination for profile 3: ({:?}, {:?}, {:?})", + subsampling_x, + subsampling_y, + bit_depth + )), + BitDepth::Depth10 => Ok(libva::VA_RT_FORMAT_YUV444_10), + BitDepth::Depth12 => Ok(libva::VA_RT_FORMAT_YUV444_12), + } + } else { + Err(anyhow!( + "Unsupported (subsampling_x, subsampling_y, bit depth) combination for profile 3: ({:?}, {:?}, {:?})", + subsampling_x, + subsampling_y, + bit_depth + )) + } + } + } +} + +impl VaStreamInfo for &Header { + fn va_profile(&self) -> anyhow::Result { + Ok(match self.profile { + Profile::Profile0 => libva::VAProfile::VAProfileVP9Profile0, + Profile::Profile1 => libva::VAProfile::VAProfileVP9Profile1, + Profile::Profile2 => libva::VAProfile::VAProfileVP9Profile2, + Profile::Profile3 => libva::VAProfile::VAProfileVP9Profile3, + }) + } + + fn rt_format(&self) -> anyhow::Result { + get_rt_format(self.profile, self.bit_depth, self.subsampling_x, self.subsampling_y) + } + + fn min_num_surfaces(&self) -> usize { + NUM_SURFACES + } + + fn coded_size(&self) -> Resolution { + Resolution::from((self.width, self.height)) + } + + fn visible_rect(&self) -> Rect { + Rect::from(self.coded_size()) + } +} + +fn build_pic_param( + hdr: &Header, + reference_frames: [u32; NUM_REF_FRAMES], +) -> anyhow::Result { + let pic_fields = libva::VP9PicFields::new( + hdr.subsampling_x as u32, + hdr.subsampling_y as u32, + hdr.frame_type as u32, + hdr.show_frame as u32, + hdr.error_resilient_mode as u32, + hdr.intra_only as u32, + hdr.allow_high_precision_mv as u32, + hdr.interpolation_filter as u32, + hdr.frame_parallel_decoding_mode as u32, + hdr.reset_frame_context as u32, + hdr.refresh_frame_context as u32, + hdr.frame_context_idx as u32, + hdr.seg.enabled as u32, + hdr.seg.temporal_update as u32, + hdr.seg.update_map as u32, + hdr.ref_frame_idx[LAST_FRAME - 1] as u32, + hdr.ref_frame_sign_bias[LAST_FRAME] as u32, + hdr.ref_frame_idx[GOLDEN_FRAME - 1] as u32, + hdr.ref_frame_sign_bias[GOLDEN_FRAME] as u32, + hdr.ref_frame_idx[ALTREF_FRAME - 1] as u32, + hdr.ref_frame_sign_bias[ALTREF_FRAME] as u32, + hdr.lossless as u32, + ); + + let lf = &hdr.lf; + let seg = &hdr.seg; + + let seg_pred_prob = if seg.temporal_update { seg.pred_probs } else { [0xff, 0xff, 0xff] }; + + let pic_param = libva::PictureParameterBufferVP9::new( + hdr.width.try_into().unwrap(), + hdr.height.try_into().unwrap(), + reference_frames, + &pic_fields, + lf.level, + lf.sharpness, + hdr.tile_rows_log2, + hdr.tile_cols_log2, + hdr.uncompressed_header_size_in_bytes.try_into().unwrap(), + hdr.header_size_in_bytes, + seg.tree_probs, + seg_pred_prob, + hdr.profile as u8, + hdr.bit_depth as u8, + ); + + Ok(libva::BufferType::PictureParameter(libva::PictureParameter::VP9(pic_param))) +} + +fn build_slice_param( + seg: &[Segmentation; MAX_SEGMENTS], + slice_size: usize, +) -> anyhow::Result { + let seg_params: std::result::Result<[SegmentParameterVP9; MAX_SEGMENTS], _> = seg + .iter() + .map(|s| { + let seg_flags = libva::VP9SegmentFlags::new( + s.reference_frame_enabled as u16, + s.reference_frame as u16, + s.reference_skip_enabled as u16, + ); + + libva::SegmentParameterVP9::new( + &seg_flags, + s.lvl_lookup, + s.luma_ac_quant_scale, + s.luma_dc_quant_scale, + s.chroma_ac_quant_scale, + s.chroma_dc_quant_scale, + ) + }) + .collect::>() + .try_into(); + + let seg_params = match seg_params { + Ok(seg_params) => seg_params, + + // Impossible, this is just a detour to collect into a fixed-size + // array whose size is the same size of the `seg` argument. + Err(_) => panic!("Invalid segment parameters"), + }; + + Ok(libva::BufferType::SliceParameter(libva::SliceParameter::VP9( + libva::SliceParameterBufferVP9::new( + slice_size as u32, + 0, + libva::VA_SLICE_DATA_FLAG_ALL, + seg_params, + ), + ))) +} + +impl StatelessDecoderBackendPicture for VaapiBackend { + type Picture = VaapiPicture; +} + +impl StatelessVp9DecoderBackend for VaapiBackend { + fn new_sequence(&mut self, header: &Header) -> StatelessBackendResult<()> { + self.new_sequence(header) + } + + fn new_picture( + &mut self, + timestamp: u64, + alloc_cb: &mut dyn FnMut() -> Option< + <::Handle as DecodedHandle>::Frame, + >, + ) -> NewPictureResult { + let context = &self.context; + + Ok(VaapiPicture::new( + timestamp, + Rc::clone(context), + alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, + )) + } + + fn submit_picture( + &mut self, + mut picture: Self::Picture, + hdr: &Header, + reference_frames: &[Option; NUM_REF_FRAMES], + bitstream: &[u8], + segmentation: &[Segmentation; MAX_SEGMENTS], + ) -> StatelessBackendResult { + let context = &self.context; + + let reference_frames: [u32; NUM_REF_FRAMES] = + reference_frames.iter().map(va_surface_id).collect::>().try_into().unwrap(); + + let pic_param = context + .create_buffer(build_pic_param(hdr, reference_frames)?) + .context("while creating pic params buffer")?; + + let slice_param = context + .create_buffer(build_slice_param(segmentation, bitstream.len())?) + .context("while creating slice params buffer")?; + + let slice_data = context + .create_buffer(libva::BufferType::SliceData(Vec::from(bitstream))) + .context("while creating slice data buffer")?; + + // Add buffers with the parsed data. + picture.add_buffer(pic_param); + picture.add_buffer(slice_param); + picture.add_buffer(slice_data); + + self.process_picture::(picture) + } +} + +impl StatelessDecoder> { + // Creates a new instance of the decoder using the VAAPI backend. + pub fn new_vaapi( + display: Rc, + blocking_mode: BlockingMode, + ) -> Result { + Self::new(VaapiBackend::new(display, true), blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::BufferType; + use libva::Display; + use libva::PictureParameter; + use libva::SliceParameter; + + use crate::bitstream_utils::IvfIterator; + use crate::codec::vp9::parser::Parser; + use crate::codec::vp9::parser::MAX_SEGMENTS; + use crate::codec::vp9::parser::NUM_REF_FRAMES; + use crate::decoder::stateless::tests::test_decode_stream; + use crate::decoder::stateless::tests::TestStream; + use crate::decoder::stateless::vp9::Segmentation; + use crate::decoder::BlockingMode; + use crate::utils::simple_playback_loop; + use crate::utils::simple_playback_loop_owned_frames; + use crate::DecodedFormat; + + use super::*; + + /// Run `test` using the vaapi decoder, in both blocking and non-blocking modes. + fn test_decoder_vaapi( + test: &TestStream, + output_format: DecodedFormat, + blocking_mode: BlockingMode, + ) { + let display = Display::open().unwrap(); + let decoder = StatelessDecoder::::new_vaapi::<()>(display, blocking_mode).unwrap(); + + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + output_format, + blocking_mode, + ) + }, + decoder, + test, + true, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_block() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::Blocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_25fps_nonblock() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS; + test_decoder_vaapi(&DECODE_TEST_25FPS, DecodedFormat::NV12, BlockingMode::NonBlocking); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn show_existing_frame_block() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS_SHOW_EXISTING_FRAME; + test_decoder_vaapi( + &DECODE_TEST_25FPS_SHOW_EXISTING_FRAME, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn show_existing_frame_nonblock() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS_SHOW_EXISTING_FRAME; + test_decoder_vaapi( + &DECODE_TEST_25FPS_SHOW_EXISTING_FRAME, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn show_existing_frame2_block() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2; + test_decoder_vaapi( + &DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2, + DecodedFormat::NV12, + BlockingMode::Blocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn show_existing_frame2_nonblock() { + use crate::decoder::stateless::vp9::tests::DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2; + test_decoder_vaapi( + &DECODE_TEST_25FPS_SHOW_EXISTING_FRAME2, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_resolution_change_500frames_block() { + use crate::decoder::stateless::vp9::tests::DECODE_RESOLUTION_CHANGE_500FRAMES; + let display = Display::open().unwrap(); + let decoder = + StatelessDecoder::::new_vaapi::<()>(display, BlockingMode::Blocking).unwrap(); + + // Skip CRC checking as they have not been generated properly? + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + BlockingMode::Blocking, + ) + }, + decoder, + &DECODE_RESOLUTION_CHANGE_500FRAMES, + false, + false, + ); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_resolution_change_500frames_nonblock() { + use crate::decoder::stateless::vp9::tests::DECODE_RESOLUTION_CHANGE_500FRAMES; + let display = Display::open().unwrap(); + let decoder = + StatelessDecoder::::new_vaapi::<()>(display, BlockingMode::Blocking).unwrap(); + + // Skip CRC checking as they have not been generated properly? + test_decode_stream( + |d, s, c| { + simple_playback_loop( + d, + IvfIterator::new(s), + c, + &mut simple_playback_loop_owned_frames, + DecodedFormat::NV12, + BlockingMode::NonBlocking, + ) + }, + decoder, + &DECODE_RESOLUTION_CHANGE_500FRAMES, + false, + false, + ); + } + + #[test] + /// Check that we are able to build the VA picture parameters from the stream properly. + fn build_pic_params() { + const TEST_STREAM: &[u8] = include_bytes!("../../../codec/vp9/test_data/test-25fps.vp9"); + let mut parser: Parser = Default::default(); + let mut segmentation: [Segmentation; MAX_SEGMENTS] = Default::default(); + let mut ivf_iter = IvfIterator::new(TEST_STREAM); + + // FRAME 0 + + let packet = ivf_iter.next().unwrap(); + let mut frames = parser.parse_chunk(packet).unwrap(); + assert_eq!(frames.len(), 1); + let frame = frames.remove(0); + + assert_eq!(frame.as_ref().len(), 10674); + + let pic_param = + build_pic_param(&frame.header, [libva::VA_INVALID_SURFACE; NUM_REF_FRAMES]).unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP9(pic_param)) => pic_param, + _ => panic!(), + }; + + Segmentation::update_segmentation(&mut segmentation, &frame.header); + let slice_param = build_slice_param(&segmentation, frame.as_ref().len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP9(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().reference_frames, [libva::VA_INVALID_SURFACE; NUM_REF_FRAMES]); + + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP9PicFields::new( + 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ) + .inner() + .value + }); + + assert_eq!(pic_param.inner().filter_level, 9); + assert_eq!(pic_param.inner().sharpness_level, 0); + assert_eq!(pic_param.inner().log2_tile_rows, 0); + assert_eq!(pic_param.inner().log2_tile_columns, 0); + assert_eq!(pic_param.inner().frame_header_length_in_bytes, 18); + assert_eq!(pic_param.inner().first_partition_size, 120); + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 7]); + assert_eq!(pic_param.inner().segment_pred_probs, [0xff; 3]); + assert_eq!(pic_param.inner().profile, 0); + assert_eq!(pic_param.inner().bit_depth, 8); + + assert_eq!(slice_param.inner().slice_data_size, 10674); + assert_eq!(slice_param.inner().slice_data_offset, 0); + assert_eq!(slice_param.inner().slice_data_flag, libva::VA_SLICE_DATA_FLAG_ALL); + + for seg_param in &slice_param.inner().seg_param { + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { seg_param.segment_flags.value }, 0); + assert_eq!(seg_param.filter_level, [[10, 0], [9, 9], [8, 8], [8, 8]]); + assert_eq!(seg_param.luma_ac_quant_scale, 72); + assert_eq!(seg_param.luma_dc_quant_scale, 62); + assert_eq!(seg_param.chroma_ac_quant_scale, 72); + assert_eq!(seg_param.chroma_dc_quant_scale, 62); + } + + // FRAME 1 + + let packet = ivf_iter.next().unwrap(); + let mut frames = parser.parse_chunk(packet).unwrap(); + assert_eq!(frames.len(), 2); + let frame = frames.remove(0); + assert_eq!(frame.as_ref().len(), 2390); + + let pic_param = build_pic_param(&frame.header, [0; NUM_REF_FRAMES]).unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP9(pic_param)) => pic_param, + _ => panic!(), + }; + + Segmentation::update_segmentation(&mut segmentation, &frame.header); + let slice_param = build_slice_param(&segmentation, frame.as_ref().len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP9(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().reference_frames, [0; NUM_REF_FRAMES]); + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP9PicFields::new( + 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, + ) + .inner() + .value + }); + + assert_eq!(pic_param.inner().filter_level, 15); + assert_eq!(pic_param.inner().sharpness_level, 0); + assert_eq!(pic_param.inner().log2_tile_rows, 0); + assert_eq!(pic_param.inner().log2_tile_columns, 0); + assert_eq!(pic_param.inner().frame_header_length_in_bytes, 11); + assert_eq!(pic_param.inner().first_partition_size, 48); + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 7]); + assert_eq!(pic_param.inner().segment_pred_probs, [0xff; 3]); + assert_eq!(pic_param.inner().profile, 0); + assert_eq!(pic_param.inner().bit_depth, 8); + + assert_eq!(slice_param.inner().slice_data_size, 2390); + assert_eq!(slice_param.inner().slice_data_offset, 0); + assert_eq!(slice_param.inner().slice_data_flag, libva::VA_SLICE_DATA_FLAG_ALL); + + for seg_param in &slice_param.inner().seg_param { + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { seg_param.segment_flags.value }, 0); + assert_eq!(seg_param.filter_level, [[16, 0], [15, 15], [14, 14], [14, 14]]); + assert_eq!(seg_param.luma_ac_quant_scale, 136); + assert_eq!(seg_param.luma_dc_quant_scale, 111); + assert_eq!(seg_param.chroma_ac_quant_scale, 136); + assert_eq!(seg_param.chroma_dc_quant_scale, 111); + } + + // FRAME 2 + + let frame = frames.remove(0); + assert_eq!(frame.as_ref().len(), 108); + + let pic_param = build_pic_param(&frame.header, [0, 0, 1, 0, 0, 0, 0, 0]).unwrap(); + let pic_param = match pic_param { + BufferType::PictureParameter(PictureParameter::VP9(pic_param)) => pic_param, + _ => panic!(), + }; + + Segmentation::update_segmentation(&mut segmentation, &frame.header); + let slice_param = build_slice_param(&segmentation, frame.as_ref().len()).unwrap(); + let slice_param = match slice_param { + BufferType::SliceParameter(SliceParameter::VP9(slice_param)) => slice_param, + _ => panic!(), + }; + + assert_eq!(pic_param.inner().frame_width, 320); + assert_eq!(pic_param.inner().frame_height, 240); + assert_eq!(pic_param.inner().reference_frames, [0, 0, 1, 0, 0, 0, 0, 0]); + + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { pic_param.inner().pic_fields.value }, unsafe { + libva::VP9PicFields::new( + 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 0, + ) + .inner() + .value + }); + + assert_eq!(pic_param.inner().filter_level, 36); + assert_eq!(pic_param.inner().sharpness_level, 0); + assert_eq!(pic_param.inner().log2_tile_rows, 0); + assert_eq!(pic_param.inner().log2_tile_columns, 0); + assert_eq!(pic_param.inner().frame_header_length_in_bytes, 10); + assert_eq!(pic_param.inner().first_partition_size, 9); + assert_eq!(pic_param.inner().mb_segment_tree_probs, [0; 7]); + assert_eq!(pic_param.inner().segment_pred_probs, [0xff; 3]); + assert_eq!(pic_param.inner().profile, 0); + assert_eq!(pic_param.inner().bit_depth, 8); + + assert_eq!(slice_param.inner().slice_data_size, 108); + assert_eq!(slice_param.inner().slice_data_offset, 0); + assert_eq!(slice_param.inner().slice_data_flag, libva::VA_SLICE_DATA_FLAG_ALL); + + for seg_param in &slice_param.inner().seg_param { + // Safe because this bitfield is initialized by the decoder. + assert_eq!(unsafe { seg_param.segment_flags.value }, 0); + assert_eq!(seg_param.filter_level, [[38, 0], [36, 36], [34, 34], [34, 34]]); + assert_eq!(seg_param.luma_ac_quant_scale, 864); + assert_eq!(seg_param.luma_dc_quant_scale, 489); + assert_eq!(seg_param.chroma_ac_quant_scale, 864); + assert_eq!(seg_param.chroma_dc_quant_scale, 489); + } + } +} diff --git a/vendor/cros-codecs/src/device.rs b/vendor/cros-codecs/src/device.rs new file mode 100644 index 0000000..e82a330 --- /dev/null +++ b/vendor/cros-codecs/src/device.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +pub mod v4l2; diff --git a/vendor/cros-codecs/src/device/v4l2.rs b/vendor/cros-codecs/src/device/v4l2.rs new file mode 100644 index 0000000..64491e3 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +pub mod stateless; +pub mod utils; diff --git a/vendor/cros-codecs/src/device/v4l2/stateless.rs b/vendor/cros-codecs/src/device/v4l2/stateless.rs new file mode 100644 index 0000000..0a6a11b --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless.rs @@ -0,0 +1,8 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +pub mod controls; +pub mod device; +pub mod queue; +pub mod request; diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/controls.rs b/vendor/cros-codecs/src/device/v4l2/stateless/controls.rs new file mode 100644 index 0000000..dcecf6f --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/controls.rs @@ -0,0 +1,8 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +pub mod av1; +pub mod h264; +pub mod vp8; +pub mod vp9; diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/controls/av1.rs b/vendor/cros-codecs/src/device/v4l2/stateless/controls/av1.rs new file mode 100644 index 0000000..4b9762e --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/controls/av1.rs @@ -0,0 +1,689 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::marker::PhantomData; + +use v4l2r::bindings::v4l2_ctrl_av1_film_grain; +use v4l2r::bindings::v4l2_ctrl_av1_frame; +use v4l2r::bindings::v4l2_ctrl_av1_sequence; +use v4l2r::bindings::v4l2_ctrl_av1_tile_group_entry; +use v4l2r::bindings::v4l2_ext_control; +use v4l2r::bindings::v4l2_ext_control__bindgen_ty_1; +use v4l2r::bindings::V4L2_AV1_AR_COEFFS_SIZE; +use v4l2r::bindings::V4L2_AV1_CDEF_MAX; +use v4l2r::bindings::V4L2_AV1_FILM_GRAIN_FLAG_APPLY_GRAIN; +use v4l2r::bindings::V4L2_AV1_FILM_GRAIN_FLAG_CHROMA_SCALING_FROM_LUMA; +use v4l2r::bindings::V4L2_AV1_FILM_GRAIN_FLAG_CLIP_TO_RESTRICTED_RANGE; +use v4l2r::bindings::V4L2_AV1_FILM_GRAIN_FLAG_OVERLAP; +use v4l2r::bindings::V4L2_AV1_FILM_GRAIN_FLAG_UPDATE_GRAIN; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_ALLOW_HIGH_PRECISION_MV; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_ALLOW_INTRABC; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_ALLOW_SCREEN_CONTENT_TOOLS; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_ALLOW_WARPED_MOTION; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_BUFFER_REMOVAL_TIME_PRESENT; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_DISABLE_CDF_UPDATE; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_DISABLE_FRAME_END_UPDATE_CDF; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_ERROR_RESILIENT_MODE; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_FORCE_INTEGER_MV; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_FRAME_REFS_SHORT_SIGNALING; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_FRAME_SIZE_OVERRIDE; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_IS_MOTION_MODE_SWITCHABLE; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_REDUCED_TX_SET; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_REFERENCE_SELECT; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_SHOWABLE_FRAME; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_SHOW_FRAME; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_SKIP_MODE_ALLOWED; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_SKIP_MODE_PRESENT; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_USE_REF_FRAME_MVS; +use v4l2r::bindings::V4L2_AV1_FRAME_FLAG_USE_SUPERRES; +use v4l2r::bindings::V4L2_AV1_GLOBAL_MOTION_FLAG_IS_GLOBAL; +use v4l2r::bindings::V4L2_AV1_GLOBAL_MOTION_FLAG_IS_ROT_ZOOM; +use v4l2r::bindings::V4L2_AV1_GLOBAL_MOTION_FLAG_IS_TRANSLATION; +use v4l2r::bindings::V4L2_AV1_LOOP_FILTER_FLAG_DELTA_ENABLED; +use v4l2r::bindings::V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_MULTI; +use v4l2r::bindings::V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_PRESENT; +use v4l2r::bindings::V4L2_AV1_LOOP_FILTER_FLAG_DELTA_UPDATE; +use v4l2r::bindings::V4L2_AV1_LOOP_RESTORATION_FLAG_USES_CHROMA_LR; +use v4l2r::bindings::V4L2_AV1_LOOP_RESTORATION_FLAG_USES_LR; +use v4l2r::bindings::V4L2_AV1_MAX_NUM_CB_POINTS; +use v4l2r::bindings::V4L2_AV1_MAX_NUM_CR_POINTS; +use v4l2r::bindings::V4L2_AV1_MAX_NUM_Y_POINTS; +use v4l2r::bindings::V4L2_AV1_MAX_OPERATING_POINTS; +use v4l2r::bindings::V4L2_AV1_MAX_SEGMENTS; +use v4l2r::bindings::V4L2_AV1_MAX_TILE_COLS; +use v4l2r::bindings::V4L2_AV1_MAX_TILE_ROWS; +use v4l2r::bindings::V4L2_AV1_NUM_PLANES_MAX; +use v4l2r::bindings::V4L2_AV1_QUANTIZATION_FLAG_DELTA_Q_PRESENT; +use v4l2r::bindings::V4L2_AV1_QUANTIZATION_FLAG_DIFF_UV_DELTA; +use v4l2r::bindings::V4L2_AV1_QUANTIZATION_FLAG_USING_QMATRIX; +use v4l2r::bindings::V4L2_AV1_SEGMENTATION_FLAG_ENABLED; +use v4l2r::bindings::V4L2_AV1_SEGMENTATION_FLAG_SEG_ID_PRE_SKIP; +use v4l2r::bindings::V4L2_AV1_SEGMENTATION_FLAG_TEMPORAL_UPDATE; +use v4l2r::bindings::V4L2_AV1_SEGMENTATION_FLAG_UPDATE_DATA; +use v4l2r::bindings::V4L2_AV1_SEGMENTATION_FLAG_UPDATE_MAP; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_COLOR_RANGE; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_CDEF; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_DUAL_FILTER; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_FILTER_INTRA; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTERINTRA_COMPOUND; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTRA_EDGE_FILTER; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_JNT_COMP; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_MASKED_COMPOUND; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_ORDER_HINT; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_REF_FRAME_MVS; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_RESTORATION; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_SUPERRES; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_ENABLE_WARPED_MOTION; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_FILM_GRAIN_PARAMS_PRESENT; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_MONO_CHROME; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_SEPARATE_UV_DELTA_Q; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_STILL_PICTURE; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_X; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_Y; +use v4l2r::bindings::V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK; +use v4l2r::bindings::V4L2_AV1_TILE_INFO_FLAG_UNIFORM_TILE_SPACING; +use v4l2r::bindings::V4L2_AV1_TOTAL_REFS_PER_FRAME; +use v4l2r::bindings::V4L2_CID_STATELESS_AV1_FILM_GRAIN; +use v4l2r::bindings::V4L2_CID_STATELESS_AV1_FRAME; +use v4l2r::bindings::V4L2_CID_STATELESS_AV1_SEQUENCE; +use v4l2r::bindings::V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY; +use v4l2r::controls::AsV4l2ControlSlice; + +use crate::codec::av1::parser::CdefParams; +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::GlobalMotionParams; +use crate::codec::av1::parser::LoopFilterParams; +use crate::codec::av1::parser::LoopRestorationParams; +use crate::codec::av1::parser::QuantizationParams; +use crate::codec::av1::parser::SegmentationParams; +use crate::codec::av1::parser::SequenceHeaderObu; +use crate::codec::av1::parser::Tile; + +// v4l2r does not have V4L2_AV1_SEG_LVL_MAX +//use v4l2r::bindings::V4L2_AV1_SEG_LVL_MAX; +const V4L2_AV1_SEG_LVL_MAX: u32 = 8; + +#[derive(Default)] +pub struct V4l2CtrlAv1FilmGrainParams { + handle: v4l2_ctrl_av1_film_grain, +} + +impl V4l2CtrlAv1FilmGrainParams { + pub fn new() -> Self { + Default::default() + } + + pub fn set_film_grain_params(&mut self, hdr: &FrameHeaderObu) -> &mut Self { + let fg = &hdr.film_grain_params; + + if fg.apply_grain { + log::warn!("Film grain is not officially supported yet.") + } + + self.handle.flags = 0; + if fg.apply_grain { + self.handle.flags |= V4L2_AV1_FILM_GRAIN_FLAG_APPLY_GRAIN as u8; + } + + if fg.update_grain { + self.handle.flags |= V4L2_AV1_FILM_GRAIN_FLAG_UPDATE_GRAIN as u8; + } + + if fg.chroma_scaling_from_luma { + self.handle.flags |= V4L2_AV1_FILM_GRAIN_FLAG_CHROMA_SCALING_FROM_LUMA as u8; + } + + if fg.overlap_flag { + self.handle.flags |= V4L2_AV1_FILM_GRAIN_FLAG_OVERLAP as u8; + } + + if fg.clip_to_restricted_range { + self.handle.flags |= V4L2_AV1_FILM_GRAIN_FLAG_CLIP_TO_RESTRICTED_RANGE as u8; + } + + self.handle.cr_mult = fg.cr_mult; + self.handle.grain_seed = fg.grain_seed; + self.handle.film_grain_params_ref_idx = fg.film_grain_params_ref_idx; + self.handle.num_y_points = fg.num_y_points; + self.handle + .point_y_value + .copy_from_slice(&fg.point_y_scaling[0..V4L2_AV1_MAX_NUM_Y_POINTS as usize]); + self.handle + .point_y_scaling + .copy_from_slice(&fg.point_y_scaling[0..V4L2_AV1_MAX_NUM_Y_POINTS as usize]); + self.handle.num_cb_points = fg.num_cb_points; + self.handle + .point_cb_value + .copy_from_slice(&fg.point_cb_value[0..V4L2_AV1_MAX_NUM_CB_POINTS as usize]); + self.handle + .point_cb_scaling + .copy_from_slice(&fg.point_cb_scaling[0..V4L2_AV1_MAX_NUM_CB_POINTS as usize]); + self.handle.num_cr_points = fg.num_cr_points; + self.handle + .point_cr_value + .copy_from_slice(&fg.point_cr_value[0..V4L2_AV1_MAX_NUM_CR_POINTS as usize]); + self.handle + .point_cr_scaling + .copy_from_slice(&fg.point_cr_scaling[0..V4L2_AV1_MAX_NUM_CR_POINTS as usize]); + self.handle.grain_scaling_minus_8 = fg.grain_scaling_minus_8; + self.handle.ar_coeff_lag = fg.ar_coeff_lag as u8; + self.handle + .ar_coeffs_y_plus_128 + .copy_from_slice(&fg.ar_coeffs_y_plus_128[0..V4L2_AV1_AR_COEFFS_SIZE as usize]); + self.handle + .ar_coeffs_cb_plus_128 + .copy_from_slice(&fg.ar_coeffs_cb_plus_128[0..V4L2_AV1_AR_COEFFS_SIZE as usize]); + self.handle + .ar_coeffs_cr_plus_128 + .copy_from_slice(&fg.ar_coeffs_cr_plus_128[0..V4L2_AV1_AR_COEFFS_SIZE as usize]); + self.handle.ar_coeff_shift_minus_6 = fg.ar_coeff_shift_minus_6; + self.handle.grain_scale_shift = fg.grain_scale_shift; + self.handle.cb_mult = fg.cb_mult; + self.handle.cb_luma_mult = fg.cb_luma_mult; + self.handle.cr_luma_mult = fg.cr_luma_mult; + self.handle.cb_offset = fg.cb_offset; + self.handle.cr_offset = fg.cr_offset; + self + } +} + +#[derive(Default)] +pub struct V4l2CtrlAv1FrameParams { + handle: v4l2_ctrl_av1_frame, +} + +impl V4l2CtrlAv1FrameParams { + pub fn new() -> Self { + Default::default() + } + + pub fn set_tile_info_params(&mut self, hdr: &FrameHeaderObu) -> &mut Self { + let tile_info = &hdr.tile_info; + if tile_info.uniform_tile_spacing_flag { + self.handle.tile_info.flags |= V4L2_AV1_TILE_INFO_FLAG_UNIFORM_TILE_SPACING as u8; + } + self.handle.tile_info.context_update_tile_id = tile_info.context_update_tile_id as u8; + self.handle.tile_info.tile_cols = tile_info.tile_cols as u8; + self.handle.tile_info.tile_rows = tile_info.tile_rows as u8; + self.handle + .tile_info + .mi_col_starts + .copy_from_slice(&tile_info.mi_col_starts[0..(V4L2_AV1_MAX_TILE_COLS + 1) as usize]); + self.handle + .tile_info + .mi_col_starts + .copy_from_slice(&tile_info.mi_col_starts[0..(V4L2_AV1_MAX_TILE_COLS + 1) as usize]); + self.handle + .tile_info + .mi_row_starts + .copy_from_slice(&tile_info.mi_row_starts[0..(V4L2_AV1_MAX_TILE_ROWS + 1) as usize]); + self.handle + .tile_info + .width_in_sbs_minus_1 + .copy_from_slice(&tile_info.width_in_sbs_minus_1[0..V4L2_AV1_MAX_TILE_COLS as usize]); + self.handle + .tile_info + .height_in_sbs_minus_1 + .copy_from_slice(&tile_info.height_in_sbs_minus_1[0..V4L2_AV1_MAX_TILE_ROWS as usize]); + self.handle.tile_info.tile_size_bytes = tile_info.tile_size_bytes as u8; + self + } + + pub fn set_quantization_params(&mut self, quant: &QuantizationParams) -> &mut Self { + if quant.diff_uv_delta { + self.handle.quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_DIFF_UV_DELTA as u8; + } + if quant.using_qmatrix { + self.handle.quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_USING_QMATRIX as u8; + } + if quant.delta_q_present { + self.handle.quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_DELTA_Q_PRESENT as u8; + } + self.handle.quantization.base_q_idx = quant.base_q_idx as u8; + self.handle.quantization.delta_q_y_dc = quant.delta_q_y_dc as i8; + self.handle.quantization.delta_q_u_dc = quant.delta_q_u_dc as i8; + self.handle.quantization.delta_q_v_dc = quant.delta_q_v_dc as i8; + self.handle.quantization.delta_q_u_ac = quant.delta_q_u_ac as i8; + self.handle.quantization.delta_q_v_ac = quant.delta_q_v_ac as i8; + self.handle.quantization.qm_y = quant.qm_y as u8; + self.handle.quantization.qm_u = quant.qm_u as u8; + self.handle.quantization.qm_v = quant.qm_v as u8; + self.handle.quantization.delta_q_res = quant.delta_q_res as u8; + self + } + + pub fn set_segmentation_params(&mut self, seg: &SegmentationParams) -> &mut Self { + self.handle.segmentation.last_active_seg_id = seg.last_active_seg_id; + for i in 0..V4L2_AV1_MAX_SEGMENTS as usize { + for j in 0..V4L2_AV1_SEG_LVL_MAX as usize { + self.handle.segmentation.feature_enabled[i] |= + (seg.feature_enabled[i][j] as u8) << j; + self.handle.segmentation.feature_data[i][j] |= seg.feature_data[i][j]; + } + } + if seg.segmentation_enabled { + self.handle.segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_ENABLED as u8; + } + if seg.segmentation_update_map { + self.handle.segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_UPDATE_MAP as u8; + } + if seg.segmentation_temporal_update { + self.handle.segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_TEMPORAL_UPDATE as u8; + } + if seg.segmentation_update_data { + self.handle.segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_UPDATE_DATA as u8; + } + if seg.seg_id_pre_skip { + self.handle.segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_SEG_ID_PRE_SKIP as u8; + } + self + } + + pub fn set_loop_filter_params(&mut self, loop_filter: &LoopFilterParams) -> &mut Self { + if loop_filter.loop_filter_delta_enabled { + self.handle.loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_ENABLED as u8; + } + if loop_filter.loop_filter_delta_update { + self.handle.loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_UPDATE as u8; + } + if loop_filter.delta_lf_present { + self.handle.loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_PRESENT as u8; + } + if loop_filter.delta_lf_multi { + self.handle.loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_MULTI as u8; + } + self.handle.loop_filter.level.copy_from_slice(&loop_filter.loop_filter_level[0..4]); + self.handle.loop_filter.sharpness = loop_filter.loop_filter_sharpness; + self.handle.loop_filter.ref_deltas.copy_from_slice( + &loop_filter.loop_filter_ref_deltas[0..V4L2_AV1_TOTAL_REFS_PER_FRAME as usize], + ); + self.handle + .loop_filter + .mode_deltas + .copy_from_slice(&loop_filter.loop_filter_mode_deltas[0..2]); + self.handle.loop_filter.delta_lf_res = loop_filter.delta_lf_res; + self + } + + pub fn set_cdef_params(&mut self, cdef: &CdefParams) -> &mut Self { + self.handle.cdef.damping_minus_3 = cdef.cdef_damping as u8; + self.handle.cdef.bits = cdef.cdef_bits as u8; + for i in 0..V4L2_AV1_CDEF_MAX as usize { + self.handle.cdef.y_pri_strength[i] = cdef.cdef_y_pri_strength[i] as u8; + self.handle.cdef.y_sec_strength[i] = cdef.cdef_y_sec_strength[i] as u8; + self.handle.cdef.uv_pri_strength[i] = cdef.cdef_uv_pri_strength[i] as u8; + self.handle.cdef.uv_sec_strength[i] = cdef.cdef_uv_sec_strength[i] as u8; + } + self + } + + pub fn set_loop_restoration_params( + &mut self, + loop_restoration: &LoopRestorationParams, + ) -> &mut Self { + if loop_restoration.uses_lr { + self.handle.loop_restoration.flags |= V4L2_AV1_LOOP_RESTORATION_FLAG_USES_LR as u8; + } + if loop_restoration.uses_chroma_lr { + self.handle.loop_restoration.flags |= + V4L2_AV1_LOOP_RESTORATION_FLAG_USES_CHROMA_LR as u8; + } + self.handle.loop_restoration.lr_unit_shift = loop_restoration.lr_unit_shift; + self.handle.loop_restoration.lr_uv_shift = loop_restoration.lr_uv_shift; + for i in 0..V4L2_AV1_NUM_PLANES_MAX as usize { + self.handle.loop_restoration.frame_restoration_type[i] = 1; + self.handle.loop_restoration.loop_restoration_size[i] = 1; + } + self + } + + pub fn set_global_motion_params(&mut self, global_motion: &GlobalMotionParams) -> &mut Self { + for i in 0..V4L2_AV1_TOTAL_REFS_PER_FRAME as usize { + if global_motion.is_global[i] { + self.handle.global_motion.flags[i] |= V4L2_AV1_GLOBAL_MOTION_FLAG_IS_GLOBAL as u8; + } + if global_motion.is_rot_zoom[i] { + self.handle.global_motion.flags[i] |= V4L2_AV1_GLOBAL_MOTION_FLAG_IS_ROT_ZOOM as u8; + } + if global_motion.is_translation[i] { + self.handle.global_motion.flags[i] |= + V4L2_AV1_GLOBAL_MOTION_FLAG_IS_TRANSLATION as u8; + } + self.handle.global_motion.type_[i] = global_motion.gm_type[i] as u32; + self.handle.global_motion.params[i].copy_from_slice(&global_motion.gm_params[i][0..6]); + self.handle.global_motion.invalid |= (global_motion.warp_valid[i] as u8) << i; + } + self + } + + pub fn set_frame_params(&mut self, hdr: &FrameHeaderObu) -> &mut Self { + self.handle.superres_denom = hdr.superres_denom as u8; + for i in 0..2 as usize { + self.handle.skip_mode_frame[i] = hdr.skip_mode_frame[i] as u8; + } + self.handle.primary_ref_frame = hdr.primary_ref_frame as u8; + if hdr.show_frame { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_SHOW_FRAME; + } + if hdr.showable_frame { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_SHOWABLE_FRAME; + } + if hdr.error_resilient_mode { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_ERROR_RESILIENT_MODE; + } + if hdr.disable_cdf_update { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_DISABLE_CDF_UPDATE; + } + if hdr.allow_screen_content_tools != 0 { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_ALLOW_SCREEN_CONTENT_TOOLS; + } + if hdr.force_integer_mv != 0 { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_FORCE_INTEGER_MV; + } + if hdr.allow_intrabc { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_ALLOW_INTRABC; + } + if hdr.use_superres { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_USE_SUPERRES; + } + if hdr.allow_high_precision_mv { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_ALLOW_HIGH_PRECISION_MV; + } + if hdr.is_motion_mode_switchable { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_IS_MOTION_MODE_SWITCHABLE; + } + if hdr.use_ref_frame_mvs { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_USE_REF_FRAME_MVS; + } + if hdr.disable_frame_end_update_cdf { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_DISABLE_FRAME_END_UPDATE_CDF; + } + if hdr.allow_warped_motion { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_ALLOW_WARPED_MOTION; + } + if hdr.reference_select { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_REFERENCE_SELECT; + } + if hdr.reduced_tx_set { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_REDUCED_TX_SET; + } + if hdr.skip_mode_present { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_SKIP_MODE_ALLOWED; + } + if hdr.skip_mode_present { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_SKIP_MODE_PRESENT; + } + if hdr.frame_size_override_flag { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_FRAME_SIZE_OVERRIDE; + } + if hdr.buffer_removal_time_present_flag { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_BUFFER_REMOVAL_TIME_PRESENT; + self.handle.buffer_removal_time.copy_from_slice( + &hdr.buffer_removal_time[0..V4L2_AV1_MAX_OPERATING_POINTS as usize], + ); + } + if hdr.frame_refs_short_signaling { + self.handle.flags |= V4L2_AV1_FRAME_FLAG_FRAME_REFS_SHORT_SIGNALING; + } + self.handle.frame_type = hdr.frame_type as u32; + self.handle.order_hint = hdr.order_hint; + self.handle.upscaled_width = hdr.upscaled_width; + self.handle.interpolation_filter = hdr.interpolation_filter as u32; + self.handle.tx_mode = hdr.tx_mode as u32; + self.handle.frame_width_minus_1 = hdr.frame_width - 1; + self.handle.frame_height_minus_1 = hdr.frame_height - 1; + self.handle.render_width_minus_1 = hdr.render_width as u16 - 1; + self.handle.render_height_minus_1 = hdr.render_height as u16 - 1; + self.handle.current_frame_id = hdr.current_frame_id; + self.handle + .order_hints + .copy_from_slice(&hdr.order_hints[0..V4L2_AV1_TOTAL_REFS_PER_FRAME as usize]); + self + } +} + +#[derive(Default)] +pub struct V4l2CtrlAv1SequenceParams { + #[allow(dead_code)] + handle: v4l2_ctrl_av1_sequence, +} + +impl V4l2CtrlAv1SequenceParams { + pub fn new() -> Self { + Default::default() + } + pub fn set_ctrl_sequence(&mut self, hdr: &SequenceHeaderObu) -> &mut Self { + if hdr.still_picture { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_STILL_PICTURE; + } + if hdr.use_128x128_superblock { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK; + } + if hdr.enable_filter_intra { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_FILTER_INTRA; + } + if hdr.enable_intra_edge_filter { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTRA_EDGE_FILTER; + } + if hdr.enable_interintra_compound { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTERINTRA_COMPOUND; + } + if hdr.enable_masked_compound { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_MASKED_COMPOUND; + } + if hdr.enable_warped_motion { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_WARPED_MOTION; + } + if hdr.enable_dual_filter { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_DUAL_FILTER; + } + if hdr.enable_order_hint { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_ORDER_HINT; + } + if hdr.enable_jnt_comp { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_JNT_COMP; + } + if hdr.enable_ref_frame_mvs { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_REF_FRAME_MVS; + } + if hdr.enable_superres { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_SUPERRES; + } + if hdr.enable_cdef { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_CDEF; + } + if hdr.enable_restoration { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_RESTORATION; + } + if hdr.color_config.mono_chrome { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_MONO_CHROME; + } + if hdr.color_config.color_range { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_COLOR_RANGE; + } + if hdr.color_config.subsampling_x { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_X; + } + if hdr.color_config.subsampling_y { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_Y; + } + if hdr.film_grain_params_present { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_FILM_GRAIN_PARAMS_PRESENT; + } + if hdr.color_config.separate_uv_delta_q { + self.handle.flags |= V4L2_AV1_SEQUENCE_FLAG_SEPARATE_UV_DELTA_Q; + } + self.handle.seq_profile = hdr.seq_profile as u8; + self.handle.order_hint_bits = hdr.order_hint_bits as u8; + self.handle.bit_depth = hdr.bit_depth as u8; + self.handle.max_frame_width_minus_1 = hdr.max_frame_width_minus_1; + self.handle.max_frame_height_minus_1 = hdr.max_frame_height_minus_1; + self + } +} + +#[derive(Default)] +pub struct V4l2CtrlAv1TileGroupEntryParams { + #[allow(dead_code)] + handle: v4l2_ctrl_av1_tile_group_entry, +} + +impl V4l2CtrlAv1TileGroupEntryParams { + pub fn new() -> Self { + Default::default() + } + pub fn set_tile_group_entry(&mut self, tg: &Tile) -> &mut Self { + self.handle.tile_offset = tg.tile_offset; + self.handle.tile_size = tg.tile_size; + self.handle.tile_row = tg.tile_row; + self.handle.tile_col = tg.tile_col; + self + } +} + +// Cargo-culted from v4l2r's control.rs file. v4l2r does not currently support +// VP9 controls, so we work around the issue by making our own "control" struct +// and just implementing the AsV4l2ControlSlice trait. + +pub struct Av1V4l2FilmGrainCtrl(v4l2_ext_control, PhantomData); + +impl From<&V4l2CtrlAv1FilmGrainParams> for Av1V4l2FilmGrainCtrl { + fn from(decode_params: &V4l2CtrlAv1FilmGrainParams) -> Self { + let payload = Box::new(decode_params.handle); + + Self( + v4l2_ext_control { + id: V4L2_CID_STATELESS_AV1_FILM_GRAIN, + size: std::mem::size_of::() as u32, + __bindgen_anon_1: v4l2_ext_control__bindgen_ty_1 { + p_av1_film_grain: Box::into_raw(payload), + }, + ..Default::default() + }, + PhantomData, + ) + } +} + +impl AsV4l2ControlSlice for &mut Av1V4l2FilmGrainCtrl { + fn as_v4l2_control_slice(&mut self) -> &mut [v4l2_ext_control] { + std::slice::from_mut(&mut self.0) + } +} + +impl Drop for Av1V4l2FilmGrainCtrl { + fn drop(&mut self) { + // Invariant: p_av1_film_grain contains a pointer to a non-NULL + // v4l2_ctrl_av1_film_grain object. + unsafe { + let _ = Box::from_raw(self.0.__bindgen_anon_1.p_av1_film_grain); + } + } +} + +pub struct Av1V4l2FrameCtrl(v4l2_ext_control, PhantomData); + +impl From<&V4l2CtrlAv1FrameParams> for Av1V4l2FrameCtrl { + fn from(decode_params: &V4l2CtrlAv1FrameParams) -> Self { + let payload = Box::new(decode_params.handle); + + Self( + v4l2_ext_control { + id: V4L2_CID_STATELESS_AV1_FRAME, + size: std::mem::size_of::() as u32, + __bindgen_anon_1: v4l2_ext_control__bindgen_ty_1 { + p_av1_frame: Box::into_raw(payload), + }, + ..Default::default() + }, + PhantomData, + ) + } +} + +impl AsV4l2ControlSlice for &mut Av1V4l2FrameCtrl { + fn as_v4l2_control_slice(&mut self) -> &mut [v4l2_ext_control] { + std::slice::from_mut(&mut self.0) + } +} + +impl Drop for Av1V4l2FrameCtrl { + fn drop(&mut self) { + // Invariant: p_av1_frame contains a pointer to a non-NULL v4l2_ctrl_av1_frame object. + unsafe { + let _ = Box::from_raw(self.0.__bindgen_anon_1.p_av1_frame); + } + } +} + +pub struct Av1V4l2SequenceCtrl(v4l2_ext_control, PhantomData); + +impl From<&V4l2CtrlAv1SequenceParams> for Av1V4l2SequenceCtrl { + fn from(decode_params: &V4l2CtrlAv1SequenceParams) -> Self { + let payload = Box::new(decode_params.handle); + + Self( + v4l2_ext_control { + id: V4L2_CID_STATELESS_AV1_SEQUENCE, + size: std::mem::size_of::() as u32, + __bindgen_anon_1: v4l2_ext_control__bindgen_ty_1 { + p_av1_sequence: Box::into_raw(payload), + }, + ..Default::default() + }, + PhantomData, + ) + } +} + +impl AsV4l2ControlSlice for &mut Av1V4l2SequenceCtrl { + fn as_v4l2_control_slice(&mut self) -> &mut [v4l2_ext_control] { + std::slice::from_mut(&mut self.0) + } +} + +impl Drop for Av1V4l2SequenceCtrl { + fn drop(&mut self) { + // Invariant: p_av1_sequence contains a pointer to a non-NULL v4l2_ctrl_av1_sequence object. + unsafe { + let _ = Box::from_raw(self.0.__bindgen_anon_1.p_av1_sequence); + } + } +} + +pub struct Av1V4l2TileGroupEntryCtrl(v4l2_ext_control, PhantomData); + +impl From<&V4l2CtrlAv1TileGroupEntryParams> for Av1V4l2TileGroupEntryCtrl { + fn from(decode_params: &V4l2CtrlAv1TileGroupEntryParams) -> Self { + let payload = Box::new(decode_params.handle); + + Self( + v4l2_ext_control { + id: V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY, + size: std::mem::size_of::() as u32, + __bindgen_anon_1: v4l2_ext_control__bindgen_ty_1 { + p_av1_tile_group_entry: Box::into_raw(payload), + }, + ..Default::default() + }, + PhantomData, + ) + } +} + +impl AsV4l2ControlSlice for &mut Av1V4l2TileGroupEntryCtrl { + fn as_v4l2_control_slice(&mut self) -> &mut [v4l2_ext_control] { + std::slice::from_mut(&mut self.0) + } +} + +impl Drop for Av1V4l2TileGroupEntryCtrl { + fn drop(&mut self) { + // Invariant: p_av1_tile_group_entry contains a pointer to a non-NULL + // v4l2_ctrl_tile_group_entry object. + unsafe { + let _ = Box::from_raw(self.0.__bindgen_anon_1.p_av1_tile_group_entry); + } + } +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/controls/h264.rs b/vendor/cros-codecs/src/device/v4l2/stateless/controls/h264.rs new file mode 100644 index 0000000..77c1de1 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/controls/h264.rs @@ -0,0 +1,294 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use v4l2r::bindings::v4l2_ctrl_h264_decode_params; +use v4l2r::bindings::v4l2_ctrl_h264_pps; +use v4l2r::bindings::v4l2_ctrl_h264_scaling_matrix; +use v4l2r::bindings::v4l2_ctrl_h264_sps; +use v4l2r::bindings::v4l2_h264_dpb_entry; +use v4l2r::bindings::v4l2_stateless_h264_decode_mode_V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED as V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED; +use v4l2r::bindings::v4l2_stateless_h264_decode_mode_V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED as V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED; +use v4l2r::bindings::v4l2_stateless_h264_start_code_V4L2_STATELESS_H264_START_CODE_ANNEX_B as V4L2_STATELESS_H264_START_CODE_ANNEX_B; +use v4l2r::bindings::v4l2_stateless_h264_start_code_V4L2_STATELESS_H264_START_CODE_NONE as V4L2_STATELESS_H264_START_CODE_NONE; +use v4l2r::bindings::V4L2_H264_DECODE_PARAM_FLAG_BOTTOM_FIELD; +use v4l2r::bindings::V4L2_H264_DECODE_PARAM_FLAG_FIELD_PIC; +use v4l2r::bindings::V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC; +use v4l2r::bindings::V4L2_H264_DPB_ENTRY_FLAG_ACTIVE; +use v4l2r::bindings::V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM; +use v4l2r::bindings::V4L2_H264_DPB_ENTRY_FLAG_VALID; +use v4l2r::bindings::V4L2_H264_FRAME_REF; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_SCALING_MATRIX_PRESENT; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE; +use v4l2r::bindings::V4L2_H264_PPS_FLAG_WEIGHTED_PRED; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET0_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET1_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET2_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET3_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET4_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_CONSTRAINT_SET5_FLAG; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS; +use v4l2r::bindings::V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE; +use v4l2r::controls::codec::H264DecodeMode; +use v4l2r::controls::codec::H264DecodeParams; +use v4l2r::controls::codec::H264StartCode; +use v4l2r::controls::SafeExtControl; + +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::picture::Field; +use crate::codec::h264::picture::IsIdr; +use crate::codec::h264::picture::PictureData; +use crate::codec::h264::picture::RcPictureData; +use crate::codec::h264::picture::Reference; +use crate::decoder::stateless::h264::get_raster_from_zigzag_4x4; +use crate::decoder::stateless::h264::get_raster_from_zigzag_8x8; + +impl From<&Sps> for v4l2_ctrl_h264_sps { + fn from(sps: &Sps) -> Self { + let mut constraint_set_flags: u32 = 0; + if sps.constraint_set0_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET0_FLAG; + } + if sps.constraint_set1_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET1_FLAG; + } + if sps.constraint_set2_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET2_FLAG; + } + if sps.constraint_set3_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET3_FLAG; + } + if sps.constraint_set4_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET4_FLAG; + } + if sps.constraint_set5_flag { + constraint_set_flags |= V4L2_H264_SPS_CONSTRAINT_SET5_FLAG; + } + let mut flags: u32 = 0; + if sps.separate_colour_plane_flag { + flags |= V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE; + } + if sps.qpprime_y_zero_transform_bypass_flag { + flags |= V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS; + } + if sps.delta_pic_order_always_zero_flag { + flags |= V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO; + } + if sps.gaps_in_frame_num_value_allowed_flag { + flags |= V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED; + } + if sps.frame_mbs_only_flag { + flags |= V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY; + } + if sps.mb_adaptive_frame_field_flag { + flags |= V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD; + } + if sps.direct_8x8_inference_flag { + flags |= V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE; + } + Self { + profile_idc: sps.profile_idc, + constraint_set_flags: constraint_set_flags as u8, + level_idc: sps.level_idc as u8, + seq_parameter_set_id: sps.seq_parameter_set_id, + chroma_format_idc: sps.chroma_format_idc, + bit_depth_luma_minus8: sps.bit_depth_luma_minus8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8, + log2_max_frame_num_minus4: sps.log2_max_frame_num_minus4, + pic_order_cnt_type: sps.pic_order_cnt_type, + log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb_minus4, + max_num_ref_frames: sps.max_num_ref_frames as u8, + num_ref_frames_in_pic_order_cnt_cycle: sps.num_ref_frames_in_pic_order_cnt_cycle, + offset_for_ref_frame: sps.offset_for_ref_frame, + offset_for_non_ref_pic: sps.offset_for_non_ref_pic, + offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field, + pic_width_in_mbs_minus1: sps.pic_width_in_mbs_minus1 as u16, + pic_height_in_map_units_minus1: sps.pic_height_in_map_units_minus1 as u16, + flags, + ..Default::default() + } + } +} + +impl From<&Pps> for v4l2_ctrl_h264_pps { + fn from(pps: &Pps) -> Self { + let mut flags: u32 = 0; + if pps.entropy_coding_mode_flag { + flags |= V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + } + if pps.bottom_field_pic_order_in_frame_present_flag { + flags |= V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT; + } + if pps.weighted_pred_flag { + flags |= V4L2_H264_PPS_FLAG_WEIGHTED_PRED; + } + if pps.deblocking_filter_control_present_flag { + flags |= V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + } + if pps.constrained_intra_pred_flag { + flags |= V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED; + } + if pps.redundant_pic_cnt_present_flag { + flags |= V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT; + } + if pps.transform_8x8_mode_flag { + flags |= V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE; + } + if pps.pic_scaling_matrix_present_flag { + flags |= V4L2_H264_PPS_FLAG_SCALING_MATRIX_PRESENT; + } + Self { + pic_parameter_set_id: pps.pic_parameter_set_id, + seq_parameter_set_id: pps.seq_parameter_set_id, + num_slice_groups_minus1: pps.num_slice_groups_minus1 as u8, + num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1, + num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1, + weighted_bipred_idc: pps.weighted_bipred_idc, + pic_init_qp_minus26: pps.pic_init_qp_minus26, + pic_init_qs_minus26: pps.pic_init_qs_minus26, + chroma_qp_index_offset: pps.chroma_qp_index_offset, + second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset, + flags: flags as u16, + ..Default::default() + } + } +} + +impl From<&Pps> for v4l2_ctrl_h264_scaling_matrix { + fn from(pps: &Pps) -> Self { + let mut scaling_list_4x4 = [[0; 16]; 6]; + let mut scaling_list_8x8 = [[0; 64]; 6]; + + (0..6).for_each(|i| { + get_raster_from_zigzag_4x4(pps.scaling_lists_4x4[i], &mut scaling_list_4x4[i]); + }); + + (0..2).for_each(|i| { + get_raster_from_zigzag_8x8(pps.scaling_lists_8x8[i], &mut scaling_list_8x8[i]); + }); + + Self { scaling_list_4x4, scaling_list_8x8 } + } +} + +pub struct V4l2CtrlH264DpbEntry { + pub timestamp: u64, + pub pic: RcPictureData, +} + +impl From<&V4l2CtrlH264DpbEntry> for v4l2_h264_dpb_entry { + fn from(dpb: &V4l2CtrlH264DpbEntry) -> Self { + let pic: &PictureData = &dpb.pic.borrow(); + // TODO DCHECK_EQ(pic->field, H264Picture::FIELD_NONE) + // TODO << "Interlacing not supported"; + + let (frame_num, pic_num): (u16, u32) = match pic.reference() { + Reference::LongTerm => (pic.long_term_pic_num as u16, pic.long_term_frame_idx), + _ => (pic.frame_num as u16, pic.pic_num as u32), + }; + + let mut flags: u32 = V4L2_H264_DPB_ENTRY_FLAG_VALID; + if matches!(pic.reference(), Reference::LongTerm | Reference::ShortTerm) { + flags |= V4L2_H264_DPB_ENTRY_FLAG_ACTIVE; + } + if matches!(pic.reference(), Reference::LongTerm) { + flags |= V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM; + } + + Self { + reference_ts: dpb.timestamp * 1000, // usec to nsec + frame_num, + pic_num, + fields: V4L2_H264_FRAME_REF as u8, + top_field_order_cnt: pic.top_field_order_cnt, + bottom_field_order_cnt: pic.bottom_field_order_cnt, + flags, + ..Default::default() + } + } +} + +#[derive(Default)] +pub struct V4l2CtrlH264DecodeParams { + handle: v4l2_ctrl_h264_decode_params, +} + +impl V4l2CtrlH264DecodeParams { + pub fn new() -> Self { + Default::default() + } + pub fn set_picture_data(&mut self, pic: &PictureData) -> &mut Self { + self.handle.top_field_order_cnt = pic.top_field_order_cnt; + self.handle.bottom_field_order_cnt = pic.bottom_field_order_cnt; + self.handle.flags |= match pic.field { + Field::Top => V4L2_H264_DECODE_PARAM_FLAG_FIELD_PIC, + Field::Bottom => { + V4L2_H264_DECODE_PARAM_FLAG_FIELD_PIC | V4L2_H264_DECODE_PARAM_FLAG_BOTTOM_FIELD + } + _ => 0, + }; + self.handle.flags |= match pic.is_idr { + IsIdr::Yes { idr_pic_id: _ } => V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC, + _ => 0, + }; + self.handle.nal_ref_idc = pic.nal_ref_idc as u16; + self + } + pub fn set_dpb_entries(&mut self, dpb: Vec) -> &mut Self { + for i in 0..dpb.len() { + self.handle.dpb[i] = v4l2_h264_dpb_entry::from(&dpb[i]); + } + self + } + pub fn set_slice_header(&mut self, slice_header: &SliceHeader) -> &mut Self { + self.handle.frame_num = slice_header.frame_num; + self.handle.idr_pic_id = slice_header.idr_pic_id; + self.handle.pic_order_cnt_lsb = slice_header.pic_order_cnt_lsb; + self.handle.delta_pic_order_cnt_bottom = slice_header.delta_pic_order_cnt_bottom; + self.handle.delta_pic_order_cnt0 = slice_header.delta_pic_order_cnt[0]; + self.handle.delta_pic_order_cnt1 = slice_header.delta_pic_order_cnt[1]; + self.handle.dec_ref_pic_marking_bit_size = slice_header.dec_ref_pic_marking_bit_size as u32; + self.handle.pic_order_cnt_bit_size = slice_header.pic_order_cnt_bit_size as u32; + self + } +} + +impl From<&V4l2CtrlH264DecodeParams> for SafeExtControl { + fn from(decode_params: &V4l2CtrlH264DecodeParams) -> Self { + SafeExtControl::::from(decode_params.handle) + } +} + +pub enum V4l2CtrlH264DecodeMode { + SliceBased = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED as isize, + FrameBased = V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED as isize, +} + +impl From for SafeExtControl { + fn from(decode_mode: V4l2CtrlH264DecodeMode) -> Self { + SafeExtControl::::from_value(decode_mode as i32) + } +} + +impl From for SafeExtControl { + fn from(decode_mode: V4l2CtrlH264StartCode) -> Self { + SafeExtControl::::from_value(decode_mode as i32) + } +} + +pub enum V4l2CtrlH264StartCode { + None = V4L2_STATELESS_H264_START_CODE_NONE as isize, + AnnexB = V4L2_STATELESS_H264_START_CODE_ANNEX_B as isize, +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp8.rs b/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp8.rs new file mode 100644 index 0000000..c32c75a --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp8.rs @@ -0,0 +1,183 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use v4l2r::bindings::v4l2_ctrl_vp8_frame; +use v4l2r::bindings::V4L2_VP8_FRAME_FLAG_KEY_FRAME; +use v4l2r::bindings::V4L2_VP8_FRAME_FLAG_MB_NO_SKIP_COEFF; +use v4l2r::bindings::V4L2_VP8_FRAME_FLAG_SHOW_FRAME; +use v4l2r::bindings::V4L2_VP8_FRAME_FLAG_SIGN_BIAS_ALT; +use v4l2r::bindings::V4L2_VP8_FRAME_FLAG_SIGN_BIAS_GOLDEN; +use v4l2r::bindings::V4L2_VP8_LF_ADJ_ENABLE; +use v4l2r::bindings::V4L2_VP8_LF_DELTA_UPDATE; +use v4l2r::bindings::V4L2_VP8_LF_FILTER_TYPE_SIMPLE; +use v4l2r::bindings::V4L2_VP8_SEGMENT_FLAG_DELTA_VALUE_MODE; +use v4l2r::bindings::V4L2_VP8_SEGMENT_FLAG_ENABLED; +use v4l2r::bindings::V4L2_VP8_SEGMENT_FLAG_UPDATE_FEATURE_DATA; +use v4l2r::bindings::V4L2_VP8_SEGMENT_FLAG_UPDATE_MAP; +use v4l2r::controls::codec::Vp8Frame; +use v4l2r::controls::SafeExtControl; + +use crate::codec::vp8::parser::Header; +use crate::codec::vp8::parser::MbLfAdjustments; +use crate::codec::vp8::parser::Segmentation; + +#[derive(Default)] +pub struct V4l2CtrlVp8FrameParams { + handle: v4l2_ctrl_vp8_frame, +} + +impl V4l2CtrlVp8FrameParams { + pub fn new() -> Self { + Default::default() + } + + pub fn set_loop_filter_params( + &mut self, + hdr: &Header, + mb_lf_adjust: &MbLfAdjustments, + ) -> &mut Self { + for i in 0..4 { + self.handle.lf.ref_frm_delta[i] = mb_lf_adjust.ref_frame_delta[i]; + self.handle.lf.mb_mode_delta[i] = mb_lf_adjust.mb_mode_delta[i]; + } + + self.handle.lf.sharpness_level = hdr.sharpness_level; + self.handle.lf.level = hdr.loop_filter_level; + self.handle.lf.padding = 0; + + let mut flags: u32 = 0; + if hdr.filter_type { + flags |= V4L2_VP8_LF_FILTER_TYPE_SIMPLE; + } + if mb_lf_adjust.loop_filter_adj_enable { + flags |= V4L2_VP8_LF_ADJ_ENABLE; + } + if mb_lf_adjust.mode_ref_lf_delta_update { + flags |= V4L2_VP8_LF_DELTA_UPDATE; + } + self.handle.lf.flags = flags; + self + } + + pub fn set_quantization_params(&mut self, hdr: &Header) -> &mut Self { + self.handle.quant.y_ac_qi = + u8::try_from(hdr.quant_indices.y_ac_qi).expect("Value out of range for u8"); + self.handle.quant.y_dc_delta = + i8::try_from(hdr.quant_indices.y_dc_delta).expect("Value out of range for u8"); + self.handle.quant.y2_dc_delta = + i8::try_from(hdr.quant_indices.y2_dc_delta).expect("Value out of range for u8"); + self.handle.quant.y2_ac_delta = + i8::try_from(hdr.quant_indices.y2_ac_delta).expect("Value out of range for u8"); + self.handle.quant.uv_dc_delta = + i8::try_from(hdr.quant_indices.uv_dc_delta).expect("Value out of range for u8"); + self.handle.quant.uv_ac_delta = + i8::try_from(hdr.quant_indices.uv_ac_delta).expect("Value out of range for u8"); + + self.handle.quant.padding = 0; + self + } + + pub fn set_segmentation_params(&mut self, segmentation: &Segmentation) -> &mut Self { + for i in 0..4 { + self.handle.segment.quant_update[i] = segmentation.quantizer_update_value[i]; + self.handle.segment.lf_update[i] = segmentation.lf_update_value[i]; + } + + for i in 0..3 { + self.handle.segment.segment_probs[i] = segmentation.segment_prob[i]; + } + + self.handle.segment.padding = 0; + + let mut flags: u32 = 0; + if segmentation.segmentation_enabled { + flags |= V4L2_VP8_SEGMENT_FLAG_ENABLED; + } + if segmentation.update_mb_segmentation_map { + flags |= V4L2_VP8_SEGMENT_FLAG_UPDATE_MAP; + } + if segmentation.update_segment_feature_data { + flags |= V4L2_VP8_SEGMENT_FLAG_UPDATE_FEATURE_DATA; + } + if segmentation.segment_feature_mode == false { + flags |= V4L2_VP8_SEGMENT_FLAG_DELTA_VALUE_MODE; + } + self.handle.segment.flags = flags; + self + } + + pub fn set_entropy_params(&mut self, hdr: &Header) -> &mut Self { + self.handle.entropy.coeff_probs = hdr.coeff_prob; + self.handle.entropy.y_mode_probs = hdr.mode_probs.intra_16x16_prob; + self.handle.entropy.uv_mode_probs = hdr.mode_probs.intra_chroma_prob; + self.handle.entropy.mv_probs = hdr.mv_prob; + self + } + + pub fn set_bool_ctx(&mut self, hdr: &Header) -> &mut Self { + self.handle.coder_state.range = hdr.bd_range as u8; + self.handle.coder_state.value = hdr.bd_value as u8; + self.handle.coder_state.bit_count = hdr.bd_count as u8; + self.handle.coder_state.padding = 0; + self + } + + pub fn set_frame_params( + &mut self, + hdr: &Header, + last_frame_ts: u64, + golden_frame_ts: u64, + alt_frame_ts: u64, + ) -> &mut Self { + self.handle.width = hdr.width; + self.handle.height = hdr.height; + self.handle.horizontal_scale = hdr.horiz_scale_code; + self.handle.vertical_scale = hdr.vert_scale_code; + + self.handle.version = hdr.version; + self.handle.prob_skip_false = hdr.prob_skip_false; + self.handle.prob_intra = hdr.prob_intra; + self.handle.prob_last = hdr.prob_last; + self.handle.prob_gf = hdr.prob_golden; + self.handle.num_dct_parts = hdr.num_dct_partitions() as u8; + + self.handle.first_part_size = hdr.first_part_size; + self.handle.first_part_header_bits = hdr.header_size; + + for i in 0..hdr.num_dct_partitions() { + self.handle.dct_part_sizes[i] = hdr.partition_size[i]; + } + + self.handle.last_frame_ts = last_frame_ts * 1000; + self.handle.golden_frame_ts = golden_frame_ts * 1000; + self.handle.alt_frame_ts = alt_frame_ts * 1000; + + let mut flags: u32 = 0; + if hdr.key_frame { + flags |= V4L2_VP8_FRAME_FLAG_KEY_FRAME; + } + if hdr.show_frame { + flags |= V4L2_VP8_FRAME_FLAG_SHOW_FRAME; + } + if hdr.mb_no_coeff_skip { + flags |= V4L2_VP8_FRAME_FLAG_MB_NO_SKIP_COEFF; + } + if hdr.sign_bias_golden { + flags |= V4L2_VP8_FRAME_FLAG_SIGN_BIAS_GOLDEN; + } + if hdr.sign_bias_alternate { + flags |= V4L2_VP8_FRAME_FLAG_SIGN_BIAS_ALT; + } + + self.handle.flags = flags as u64; + + self + } +} + +impl From<&V4l2CtrlVp8FrameParams> for SafeExtControl { + fn from(decode_params: &V4l2CtrlVp8FrameParams) -> Self { + SafeExtControl::::from(decode_params.handle) + } +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp9.rs b/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp9.rs new file mode 100644 index 0000000..2137fc2 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/controls/vp9.rs @@ -0,0 +1,212 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::marker::PhantomData; + +use v4l2r::bindings::v4l2_ctrl_vp9_frame; +use v4l2r::bindings::v4l2_ext_control; +use v4l2r::bindings::v4l2_ext_control__bindgen_ty_1; +use v4l2r::bindings::V4L2_CID_STATELESS_VP9_FRAME; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_ALLOW_HIGH_PREC_MV; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_COLOR_RANGE_FULL_SWING; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_INTRA_ONLY; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_KEY_FRAME; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_PARALLEL_DEC_MODE; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_SHOW_FRAME; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING; +use v4l2r::bindings::V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING; +use v4l2r::bindings::V4L2_VP9_LOOP_FILTER_FLAG_DELTA_ENABLED; +use v4l2r::bindings::V4L2_VP9_LOOP_FILTER_FLAG_DELTA_UPDATE; +use v4l2r::bindings::V4L2_VP9_REFERENCE_MODE_SINGLE_REFERENCE; +use v4l2r::bindings::V4L2_VP9_SEGMENTATION_FLAG_ABS_OR_DELTA_UPDATE; +use v4l2r::bindings::V4L2_VP9_SEGMENTATION_FLAG_ENABLED; +use v4l2r::bindings::V4L2_VP9_SEGMENTATION_FLAG_TEMPORAL_UPDATE; +use v4l2r::bindings::V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA; +use v4l2r::bindings::V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP; +use v4l2r::controls::AsV4l2ControlSlice; + +use crate::codec::vp9::parser::ColorRange; +use crate::codec::vp9::parser::FrameType; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::LAST_FRAME; +use crate::codec::vp9::parser::MAX_REF_FRAMES; +use crate::codec::vp9::parser::MAX_SEGMENTS; +use crate::codec::vp9::parser::SEG_LVL_MAX; + +#[derive(Default)] +pub struct V4l2CtrlVp9FrameParams { + handle: v4l2_ctrl_vp9_frame, +} + +impl V4l2CtrlVp9FrameParams { + pub fn new() -> Self { + Default::default() + } + + pub fn set_loop_filter_params(&mut self, hdr: &Header) -> &mut Self { + self.handle.lf.level = hdr.lf.level; + self.handle.lf.sharpness = hdr.lf.sharpness; + self.handle.lf.flags = 0; + + if hdr.lf.delta_enabled { + self.handle.lf.flags |= V4L2_VP9_LOOP_FILTER_FLAG_DELTA_ENABLED as u8; + } + if hdr.lf.delta_update { + self.handle.lf.flags |= V4L2_VP9_LOOP_FILTER_FLAG_DELTA_UPDATE as u8; + } + + self.handle.lf.ref_deltas.clone_from_slice(&hdr.lf.ref_deltas); + self.handle.lf.mode_deltas.clone_from_slice(&hdr.lf.mode_deltas); + + self + } + + pub fn set_quantization_params(&mut self, hdr: &Header) -> &mut Self { + self.handle.quant.base_q_idx = hdr.quant.base_q_idx; + self.handle.quant.delta_q_y_dc = hdr.quant.delta_q_y_dc; + self.handle.quant.delta_q_uv_dc = hdr.quant.delta_q_uv_dc; + self.handle.quant.delta_q_uv_ac = hdr.quant.delta_q_uv_ac; + self + } + + pub fn set_segmentation_params(&mut self, hdr: &Header) -> &mut Self { + if hdr.seg.enabled { + self.handle.seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_ENABLED as u8; + } + if hdr.seg.update_map { + self.handle.seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP as u8; + } + if hdr.seg.temporal_update { + self.handle.seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_TEMPORAL_UPDATE as u8; + } + if hdr.seg.update_data { + self.handle.seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA as u8; + } + if hdr.seg.abs_or_delta_update { + self.handle.seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_ABS_OR_DELTA_UPDATE as u8; + } + + for i in 0..MAX_SEGMENTS { + self.handle.seg.feature_data[i].clone_from_slice(&hdr.seg.feature_data[i]); + let mut feature_enabled = 0u8; + for j in 0..SEG_LVL_MAX { + feature_enabled |= (hdr.seg.feature_enabled[i][j] as u8) << j; + } + self.handle.seg.feature_enabled[i] = feature_enabled; + } + + self.handle.seg.tree_probs.clone_from_slice(&hdr.seg.tree_probs); + self.handle.seg.pred_probs.clone_from_slice(&hdr.seg.pred_probs); + + self + } + + pub fn set_frame_params( + &mut self, + hdr: &Header, + last_frame_ts: u64, + golden_frame_ts: u64, + alt_frame_ts: u64, + ) -> &mut Self { + self.handle.compressed_header_size = hdr.header_size_in_bytes; + self.handle.uncompressed_header_size = hdr.uncompressed_header_size_in_bytes; + self.handle.frame_width_minus_1 = (hdr.width - 1) as u16; + self.handle.frame_height_minus_1 = (hdr.height - 1) as u16; + self.handle.render_width_minus_1 = (hdr.render_width - 1) as u16; + self.handle.render_height_minus_1 = (hdr.render_height - 1) as u16; + self.handle.reset_frame_context = hdr.reset_frame_context; + self.handle.frame_context_idx = hdr.frame_context_idx; + self.handle.profile = hdr.profile as u8; + self.handle.bit_depth = hdr.bit_depth as u8; + self.handle.interpolation_filter = hdr.interpolation_filter as u8; + self.handle.tile_cols_log2 = hdr.tile_cols_log2; + self.handle.tile_rows_log2 = hdr.tile_rows_log2; + + // The MTK V4L2 stateless driver ignores the reference_mode field current. + // TODO: Implement this properly for future drivers? + self.handle.reference_mode = V4L2_VP9_REFERENCE_MODE_SINGLE_REFERENCE as u8; + + for i in 0..(MAX_REF_FRAMES - LAST_FRAME) { + self.handle.ref_frame_sign_bias |= + ((hdr.ref_frame_sign_bias[i + LAST_FRAME] != 0) as u8) << i; + } + + if hdr.frame_type == FrameType::KeyFrame { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_KEY_FRAME; + } + if hdr.show_frame { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_SHOW_FRAME; + } + if hdr.error_resilient_mode { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT; + } + if hdr.intra_only { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_INTRA_ONLY; + } + if hdr.allow_high_precision_mv { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_ALLOW_HIGH_PREC_MV; + } + if hdr.refresh_frame_context { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX; + } + if hdr.frame_parallel_decoding_mode { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_PARALLEL_DEC_MODE; + } + if hdr.subsampling_x { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING; + } + if hdr.subsampling_y { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING; + } + if hdr.color_range == ColorRange::FullSwing { + self.handle.flags |= V4L2_VP9_FRAME_FLAG_COLOR_RANGE_FULL_SWING; + } + + self.handle.last_frame_ts = last_frame_ts * 1000; + self.handle.golden_frame_ts = golden_frame_ts * 1000; + self.handle.alt_frame_ts = alt_frame_ts * 1000; + + self + } +} + +// Cargo-culted from v4l2r's control.rs file. v4l2r does not currently support +// VP9 controls, so we work around the issue by making our own "control" struct +// and just implementing the AsV4l2ControlSlice trait. +pub struct Vp9V4l2Control(v4l2_ext_control, PhantomData); + +impl From<&V4l2CtrlVp9FrameParams> for Vp9V4l2Control { + fn from(decode_params: &V4l2CtrlVp9FrameParams) -> Self { + let payload = Box::new(decode_params.handle); + + Self( + v4l2_ext_control { + id: V4L2_CID_STATELESS_VP9_FRAME, + size: std::mem::size_of::() as u32, + __bindgen_anon_1: v4l2_ext_control__bindgen_ty_1 { + p_vp9_frame: Box::into_raw(payload), + }, + ..Default::default() + }, + PhantomData, + ) + } +} + +impl AsV4l2ControlSlice for &mut Vp9V4l2Control { + fn as_v4l2_control_slice(&mut self) -> &mut [v4l2_ext_control] { + std::slice::from_mut(&mut self.0) + } +} + +impl Drop for Vp9V4l2Control { + fn drop(&mut self) { + // Invariant: p_vp9_frame contains a pointer to a non-NULL v4l2_ctrl_vp9_frame object. + unsafe { + let _ = Box::from_raw(self.0.__bindgen_anon_1.p_vp9_frame); + } + } +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/device.rs b/vendor/cros-codecs/src/device/v4l2/stateless/device.rs new file mode 100644 index 0000000..b757b89 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/device.rs @@ -0,0 +1,227 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::os::fd::{AsRawFd, RawFd}; +use std::rc::{Rc, Weak}; +use std::sync::Arc; +use std::thread::sleep; +use std::time::Duration; + +use v4l2r::device::Device as VideoDevice; +use v4l2r::device::DeviceConfig; +use v4l2r::ioctl; +use v4l2r::nix::fcntl::open; +use v4l2r::nix::fcntl::OFlag; +use v4l2r::nix::sys::stat::Mode; + +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::device::v4l2::stateless::queue::QueueError; +use crate::device::v4l2::stateless::queue::V4l2CaptureBuffer; +use crate::device::v4l2::stateless::queue::V4l2CaptureQueue; +use crate::device::v4l2::stateless::queue::V4l2OutputQueue; +use crate::device::v4l2::stateless::request::V4l2Request; +use crate::device::v4l2::utils::enumerate_devices; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Resolution; + +//TODO: handle other memory backends for OUTPUT queue +//TODO: handle video formats other than h264 +//TODO: handle queue start/stop at runtime +//TODO: handle DRC at runtime +struct DeviceHandle { + video_device: Arc, + media_device: RawFd, + output_queue: V4l2OutputQueue, + capture_queue: V4l2CaptureQueue, + requests: HashMap>>>, +} + +impl DeviceHandle { + fn new() -> Result { + let devices = enumerate_devices(); + let (video_device_path, media_device_path) = match devices { + Some(paths) => paths, + None => return Err(NewStatelessDecoderError::DriverInitialization), + }; + + let video_device_config = DeviceConfig::new().non_blocking_dqbuf(); + let video_device = Arc::new( + VideoDevice::open(&video_device_path, video_device_config) + .map_err(|_| NewStatelessDecoderError::DriverInitialization)?, + ); + + let media_device = + open(&media_device_path, OFlag::O_RDWR | OFlag::O_CLOEXEC, Mode::empty()) + .map_err(|_| NewStatelessDecoderError::DriverInitialization)?; + let output_queue = V4l2OutputQueue::new(video_device.clone())?; + let capture_queue = V4l2CaptureQueue::new(video_device.clone())?; + Ok(Self { + video_device, + media_device, + output_queue, + capture_queue, + requests: HashMap::>>>::new(), + }) + } + + pub fn reset_queues(&mut self) -> Result<(), QueueError> { + self.output_queue + .reset(self.video_device.clone()) + .map_err(|_| QueueError::ResetOutputQueue)?; + self.capture_queue + .reset(self.video_device.clone()) + .map_err(|_| QueueError::ResetCaptureQueue) + } + + fn alloc_request(&self) -> ioctl::Request { + ioctl::Request::alloc(&self.media_device).expect("Failed to alloc request handle") + } + fn dequeue_output_buffer(&self) { + let mut back_off_duration = Duration::from_millis(1); + loop { + match self.output_queue.dequeue_buffer() { + Ok(_) => { + break; + } + Err(QueueError::BufferDequeue) => { + sleep(back_off_duration); + back_off_duration = back_off_duration + back_off_duration; + continue; + } + Err(_) => panic!("handle this better"), + } + } + } + fn insert_request_into_hash(&mut self, request: Weak>>) { + let timestamp = request.upgrade().unwrap().as_ref().borrow().timestamp(); + self.requests.insert(timestamp, request); + } + fn try_dequeue_capture_buffers(&mut self) { + loop { + match self.capture_queue.dequeue_buffer() { + Ok(Some(buffer)) => { + let timestamp = buffer.timestamp(); + let request = self.requests.remove(×tamp).unwrap(); + match request.upgrade().unwrap().as_ref().try_borrow_mut() { + Ok(mut request) => { + request.associate_dequeued_buffer(buffer); + } + _ => (), + } + continue; + } + _ => break, + } + } + } + fn sync(&mut self, timestamp: u64) -> V4l2CaptureBuffer { + let mut back_off_duration = Duration::from_millis(1); + let time_out = Duration::from_millis(120); + loop { + match self.capture_queue.dequeue_buffer() { + Ok(Some(buffer)) => { + let dequeued_timestamp = buffer.timestamp(); + let request = self.requests.remove(&dequeued_timestamp).unwrap(); + if dequeued_timestamp == timestamp { + return buffer; + } else { + match request.upgrade().unwrap().as_ref().try_borrow_mut() { + Ok(mut request) => { + request.associate_dequeued_buffer(buffer); + } + _ => (), + } + } + } + _ => (), + } + back_off_duration = back_off_duration + back_off_duration; + if back_off_duration > time_out { + panic!("there should not be a scenario where a queued frame is not returned."); + } + sleep(back_off_duration); + } + } +} + +pub struct V4l2Device { + handle: Rc>>, +} + +impl V4l2Device { + pub fn new() -> Result { + Ok(Self { handle: Rc::new(RefCell::new(DeviceHandle::new()?)) }) + } + + pub fn reset_queues(&mut self) -> Result<(), QueueError> { + self.handle.borrow_mut().reset_queues() + } + + pub fn initialize_queues( + &mut self, + format: Fourcc, + coded_size: Resolution, + num_buffers: u32, + ) -> Result<(), anyhow::Error> { + self.handle.borrow_mut().output_queue.initialize(format, coded_size)?; + self.handle.borrow_mut().capture_queue.initialize(num_buffers)?; + Ok(()) + } + pub fn alloc_request( + &self, + timestamp: u64, + frame: V, + ) -> Result>>, DecodeError> { + if self.handle.borrow().capture_queue.num_free_buffers() == 0 { + return Err(DecodeError::NotEnoughOutputBuffers(0)); + } + + let output_buffer = self.handle.borrow().output_queue.alloc_buffer(); + + let output_buffer = match output_buffer { + Ok(buffer) => buffer, + Err(DecodeError::NotEnoughOutputBuffers(_)) => { + self.handle.borrow_mut().dequeue_output_buffer(); + match self.handle.borrow().output_queue.alloc_buffer() { + Ok(buffer) => buffer, + Err(e) => return Err(e), + } + } + Err(error) => return Err(error), + }; + self.handle.borrow_mut().try_dequeue_capture_buffers(); + + let request = Rc::new(RefCell::new(V4l2Request::new( + self.clone(), + timestamp, + self.handle.borrow().alloc_request(), + output_buffer, + frame, + ))); + self.handle.borrow_mut().insert_request_into_hash(Rc::downgrade(&request.clone())); + Ok(request) + } + pub fn sync(&self, timestamp: u64) -> V4l2CaptureBuffer { + self.handle.borrow_mut().sync(timestamp) + } + pub fn queue_capture_buffer(&self, frame: V) -> Result<(), QueueError> { + self.handle.borrow().capture_queue.queue_buffer(frame) + } +} + +impl Clone for V4l2Device { + fn clone(&self) -> Self { + Self { handle: self.handle.clone() } + } +} + +impl AsRawFd for V4l2Device { + fn as_raw_fd(&self) -> i32 { + self.handle.borrow().video_device.as_raw_fd() + } +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/queue.rs b/vendor/cros-codecs/src/device/v4l2/stateless/queue.rs new file mode 100644 index 0000000..90c4d67 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/queue.rs @@ -0,0 +1,447 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use anyhow::anyhow; +use std::cell::RefCell; +use std::convert::Infallible; +use std::rc::Rc; +use std::sync::Arc; +use thiserror::Error; + +use v4l2r::bindings::v4l2_format; +use v4l2r::device::queue::direction; +use v4l2r::device::queue::direction::Capture; +use v4l2r::device::queue::direction::Output; +use v4l2r::device::queue::dqbuf::DqBuffer; +use v4l2r::device::queue::qbuf::QBuffer; +use v4l2r::device::queue::BuffersAllocated; +use v4l2r::device::queue::CaptureQueueable; +use v4l2r::device::queue::CreateQueueError; +use v4l2r::device::queue::GetFreeBufferError; +use v4l2r::device::queue::GetFreeCaptureBuffer; +use v4l2r::device::queue::GetFreeOutputBuffer; +use v4l2r::device::queue::Queue; +use v4l2r::device::queue::QueueInit; +use v4l2r::device::queue::RequestBuffersError; +use v4l2r::device::AllocatedQueue; +use v4l2r::device::Device; +use v4l2r::device::Stream; +use v4l2r::device::TryDequeue; +use v4l2r::ioctl::GFmtError; +use v4l2r::ioctl::IoctlConvertError; +use v4l2r::ioctl::QBufIoctlError; +use v4l2r::ioctl::SFmtError; +use v4l2r::ioctl::StreamOnError; +use v4l2r::memory::BufferHandles; +use v4l2r::memory::Memory; +use v4l2r::memory::MemoryType; +use v4l2r::memory::MmapHandle; +use v4l2r::memory::PlaneHandle; +use v4l2r::nix::sys::time::TimeVal; +use v4l2r::Format; +use v4l2r::PlaneLayout; + +use crate::decoder::stateless::DecodeError; +use crate::decoder::stateless::NewStatelessDecoderError; +use crate::decoder::stateless::StatelessBackendError; +use crate::utils::buffer_size_for_area; +use crate::video_frame::V4l2VideoFrame; +use crate::video_frame::VideoFrame; +use crate::Fourcc; +use crate::Resolution; + +//TODO: handle memory backends other than mmap +//TODO: handle video formats other than h264 +//TODO: handle synced buffers in Streaming state +#[derive(Default)] +enum V4l2OutputQueueHandle { + Init(Queue), + Streaming(Rc>>>), + #[default] + Unknown, +} + +#[derive(Default)] +enum V4l2CaptureQueueHandle { + Init(Queue), + Streaming(Rc>>>), + #[default] + Unknown, +} + +#[derive(Debug, Error)] +pub enum QueueError { + #[error("unable to create queue.")] + Creation, + #[error("failed to get format for queue.")] + FormatGet, + #[error("failed to set format for queue.")] + FormatSet, + #[error("failed requesting buffers.")] + RequestBuffers, + #[error("unable to stream on.")] + StreamOn, + #[error("driver does not support {0}.")] + UnsupportedPixelFormat(Fourcc), + #[error("operation can not be performed in this state.")] + State, + #[error("no buffer to dequeue.")] + BufferDequeue, + #[error("failed to queue buffer.")] + BufferQueue, + #[error("requested {0} buffers, only {1} allocated")] + NotEnoughRequestedBuffers(usize, usize), + #[error("failed to stream off.")] + StreamOff, + #[error("failed to get queue handle.")] + QueueHandle, + #[error("failed to free buffers.")] + FreeBuffer, + #[error("failed to reset OUTPUT queue.")] + ResetOutputQueue, + #[error("failed to reset CAPTURE queue.")] + ResetCaptureQueue, +} + +impl From for DecodeError { + fn from(err: QueueError) -> Self { + DecodeError::BackendError(StatelessBackendError::Other(anyhow::anyhow!(err))) + } +} + +impl From> for QueueError { + fn from(_err: v4l2r::device::queue::qbuf::QueueError) -> Self { + QueueError::BufferQueue + } +} + +impl From for QueueError { + fn from(_err: CreateQueueError) -> Self { + QueueError::Creation + } +} + +impl From for QueueError { + fn from(_err: GFmtError) -> Self { + QueueError::FormatGet + } +} + +impl From for QueueError { + fn from(_err: SFmtError) -> Self { + QueueError::FormatSet + } +} + +impl From for QueueError { + fn from(_err: RequestBuffersError) -> Self { + QueueError::RequestBuffers + } +} + +impl From for QueueError { + fn from(_err: StreamOnError) -> Self { + QueueError::StreamOn + } +} + +impl From for QueueError { + fn from(_err: GetFreeBufferError) -> Self { + QueueError::BufferDequeue + } +} + +impl From> for QueueError { + fn from(_err: IoctlConvertError) -> Self { + QueueError::BufferQueue + } +} + +fn check_requested_buffer_count(requested: u32, received: usize) -> Result<(), QueueError> { + if received < requested as usize { + return Err(QueueError::NotEnoughRequestedBuffers(requested as usize, received)); + } + Ok(()) +} + +//TODO: handle memory backends other than mmap +pub struct V4l2OutputBuffer { + queue: V4l2OutputQueue, + handle: QBuffer< + Output, + Vec, + Vec, + Rc>>>, + >, + length: usize, +} + +impl V4l2OutputBuffer { + fn new( + queue: V4l2OutputQueue, + handle: QBuffer< + Output, + Vec, + Vec, + Rc>>>, + >, + ) -> Self { + Self { queue, handle, length: 0 } + } + pub fn index(&self) -> usize { + self.handle.index() + } + pub fn length(&self) -> usize { + self.length + } + pub fn write(&mut self, data: &[u8]) -> &mut Self { + let mut mapping = self.handle.get_plane_mapping(0).expect("Failed to mmap output buffer"); + + mapping.as_mut()[self.length..self.length + data.len()].copy_from_slice(data); + self.length += data.len(); + + drop(mapping); + self + } + pub fn submit(self, timestamp: u64, request_fd: i32) -> Result<(), QueueError> { + let handle = &*self.queue.handle.borrow(); + match handle { + V4l2OutputQueueHandle::Streaming(_) => { + self.handle + .set_timestamp(TimeVal::new(/* FIXME: sec */ 0, timestamp as i64)) + .set_request(request_fd) + .queue(&[self.length])?; + Ok(()) + } + _ => Err(QueueError::State), + } + } +} + +#[derive(Clone)] +pub struct V4l2OutputQueue { + handle: Rc>>, +} + +const NUM_OUTPUT_BUFFERS: u32 = 2; +impl V4l2OutputQueue { + pub fn new(device: Arc) -> Result { + let handle = Queue::get_output_mplane_queue(device) + .map_err(|_| NewStatelessDecoderError::DriverInitialization)?; + log::debug!("output queue created"); + let handle = Rc::new(RefCell::new(V4l2OutputQueueHandle::Init(handle))); + Ok(Self { handle }) + } + + pub fn reset(&mut self, device: Arc) -> Result<(), QueueError> { + let handle = self.handle.take(); + let (ret, handle) = match handle { + V4l2OutputQueueHandle::Streaming(handle) => { + handle.stream_off().map_err(|_| QueueError::StreamOff)?; + (Rc::into_inner(handle).ok_or(QueueError::QueueHandle)?) + .free_buffers() + .map_err(|_| QueueError::FreeBuffer)?; + + let queue_handle = Queue::get_output_mplane_queue(device.clone()) + .map_err(|_| QueueError::QueueHandle); + + (Ok(()), V4l2OutputQueueHandle::Init(queue_handle?)) + } + _ => (Err(QueueError::State), handle), + }; + self.handle.replace(handle); + ret + } + + pub fn initialize( + &mut self, + fourcc: Fourcc, + resolution: Resolution, + ) -> Result<&mut Self, QueueError> { + self.handle.replace(match self.handle.take() { + V4l2OutputQueueHandle::Init(mut handle) => { + let (width, height) = resolution.into(); + handle + .change_format()? + .set_size(width as usize, height as usize) + .set_pixelformat(fourcc) + .set_planes_layout(vec![PlaneLayout { + sizeimage: buffer_size_for_area(width, height), + ..Default::default() + }]) + .apply::()?; + + let format: Format = handle.get_format()?; + if format.pixelformat != fourcc.into() { + return Err(QueueError::UnsupportedPixelFormat(fourcc)); + } + + let handle = handle.request_buffers_generic::>( + MemoryType::Mmap, + NUM_OUTPUT_BUFFERS, + )?; + + check_requested_buffer_count(NUM_OUTPUT_BUFFERS, handle.num_free_buffers())?; + + handle.stream_on()?; + + V4l2OutputQueueHandle::Streaming(handle.into()) + } + _ => return Err(QueueError::State), + }); + Ok(self) + } + + pub fn num_free_buffers(&self) -> usize { + let handle = &*self.handle.borrow(); + match handle { + V4l2OutputQueueHandle::Streaming(handle) => handle.num_free_buffers(), + _ => 0, + } + } + pub fn alloc_buffer(&self) -> Result { + let handle = &*self.handle.borrow(); + match handle { + V4l2OutputQueueHandle::Streaming(handle) => match handle.try_get_free_buffer() { + Ok(buffer) => Ok(V4l2OutputBuffer::new(self.clone(), buffer)), + Err(_) => Err(DecodeError::NotEnoughOutputBuffers(1)), + }, + _ => Err(DecodeError::DecoderError(anyhow!("Invalid hardware handle"))), + } + } + pub fn dequeue_buffer(&self) -> Result<(), QueueError> { + let handle = &*self.handle.borrow(); + match handle { + V4l2OutputQueueHandle::Streaming(handle) => { + handle.try_dequeue().map_err(|_| QueueError::BufferDequeue)?; + Ok(()) + } + _ => Err(QueueError::State), + } + } +} + +pub struct V4l2CaptureBuffer { + pub frame: Arc, + handle: DqBuffer>, +} + +impl V4l2CaptureBuffer { + fn new(frame: Arc, handle: DqBuffer>) -> Self { + Self { frame, handle } + } + pub fn timestamp(&self) -> u64 { + self.handle.data.timestamp().tv_usec as u64 + } + // TODO enable once upstream v4l2r has rolled + // pub fn has_error(&self) -> bool { + // self.handle.data.has_error() as u64 + // } +} + +pub struct V4l2CaptureQueue { + format: Format, + handle: RefCell>, + num_buffers: u32, + device: Arc, +} + +impl V4l2CaptureQueue { + pub fn new(device: Arc) -> Result { + let handle = Queue::get_capture_mplane_queue(device.clone()) + .map_err(|_| NewStatelessDecoderError::DriverInitialization)?; + log::debug!("capture queue created"); + let handle = RefCell::new(V4l2CaptureQueueHandle::Init(handle)); + Ok(Self { handle, num_buffers: 0, format: Default::default(), device: device }) + } + + pub fn reset(&mut self, device: Arc) -> Result<(), QueueError> { + let handle = self.handle.take(); + let (ret, handle) = match handle { + V4l2CaptureQueueHandle::Streaming(handle) => { + handle.stream_off().map_err(|_| QueueError::StreamOff)?; + (Rc::into_inner(handle).ok_or(QueueError::QueueHandle)?) + .free_buffers() + .map_err(|_| QueueError::FreeBuffer)?; + + let queue_handle = Queue::get_capture_mplane_queue(device.clone()) + .map_err(|_| QueueError::QueueHandle); + + (Ok(()), V4l2CaptureQueueHandle::Init(queue_handle?)) + } + _ => (Err(QueueError::State), handle), + }; + self.handle.replace(handle); + ret + } + + pub fn initialize(&mut self, requested_num_buffers: u32) -> Result<&mut Self, QueueError> { + // +2 due to HCMP1_HHI_A.h264 needing more + let requested_num_buffers = requested_num_buffers + 2; + + self.handle.replace(match self.handle.take() { + V4l2CaptureQueueHandle::Init(handle) => { + // TODO: check if decoded format is supported. + self.format = handle.get_format()?; + // TODO: handle 10 bit format negotiation. + let handle = handle.request_buffers_generic::>( + ::Memory::MEMORY_TYPE, + requested_num_buffers, + )?; + + check_requested_buffer_count(requested_num_buffers, handle.num_free_buffers())?; + + self.num_buffers = requested_num_buffers; + + handle.stream_on()?; + + V4l2CaptureQueueHandle::Streaming(handle.into()) + } + _ => return Err(QueueError::State), + }); + + Ok(self) + } + + pub fn dequeue_buffer(&self) -> Result>, QueueError> { + let handle = &*self.handle.borrow(); + match handle { + V4l2CaptureQueueHandle::Streaming(handle) => match handle.try_dequeue() { + Ok(mut buffer) => { + log::debug!("capture buffer {} dequeued", buffer.data.index()); + // TODO handle buffer dequeuing successfully, but having an error + // buffer.data.has_error(); + let mut frame = buffer.take_handles().expect("Missing handle on dequeue!").0; + frame.process_dqbuf(self.device.clone(), &self.format, &buffer.data); + Ok(Some(V4l2CaptureBuffer::new(Arc::new(frame), buffer))) + } + _ => Ok(None), + }, + _ => Err(QueueError::State), + } + } + + // TODO: Plumb in VideoFrames from external Gralloc frame pool instead of reallocating every + // frame every time. + pub fn queue_buffer(&self, frame: V) -> Result<(), QueueError> { + let handle = &*self.handle.borrow(); + match handle { + V4l2CaptureQueueHandle::Streaming(handle) => { + let buffer = handle.try_get_free_buffer()?; + log::debug!("capture buffer {} queued", buffer.index()); + buffer.queue_with_handles(frame.into())?; + } + _ => return Err(QueueError::State), + } + Ok(()) + } + + pub fn num_free_buffers(&self) -> usize { + let handle = &*self.handle.borrow(); + match handle { + V4l2CaptureQueueHandle::Streaming(handle) => handle.num_free_buffers(), + _ => 0, + } + } +} diff --git a/vendor/cros-codecs/src/device/v4l2/stateless/request.rs b/vendor/cros-codecs/src/device/v4l2/stateless/request.rs new file mode 100644 index 0000000..aedd12b --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/stateless/request.rs @@ -0,0 +1,249 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::os::fd::AsRawFd; +use std::rc::{Rc, Weak}; + +use v4l2r::controls::ExtControlTrait; +use v4l2r::controls::SafeExtControl; +use v4l2r::ioctl; + +use crate::backend::v4l2::decoder::stateless::V4l2Picture; +use crate::decoder::stateless::StatelessBackendError; +use crate::decoder::stateless::StatelessBackendResult; +use crate::device::v4l2::stateless::device::V4l2Device; +use crate::device::v4l2::stateless::queue::V4l2CaptureBuffer; +use crate::device::v4l2::stateless::queue::V4l2OutputBuffer; +use crate::video_frame::VideoFrame; + +struct InitRequestHandle { + device: V4l2Device, + timestamp: u64, + handle: ioctl::Request, + output_buffer: V4l2OutputBuffer, + picture: Weak>>, + frame: V, +} + +impl InitRequestHandle { + fn new( + device: V4l2Device, + timestamp: u64, + handle: ioctl::Request, + output_buffer: V4l2OutputBuffer, + frame: V, + ) -> Self { + Self { device, timestamp, handle, output_buffer, picture: Weak::new(), frame } + } + fn which(&self) -> ioctl::CtrlWhich { + ioctl::CtrlWhich::Request(self.handle.as_raw_fd()) + } + fn ioctl(&mut self, ctrl: C) -> StatelessBackendResult<&mut Self> + where + C: Into>, + T: ExtControlTrait, + { + let mut ctrl: SafeExtControl = ctrl.into(); + ioctl::s_ext_ctrls(&self.device, self.which(), &mut ctrl) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + Ok(self) + } + fn write(&mut self, data: &[u8]) -> &mut Self { + self.output_buffer.write(data); + self + } + fn submit(self) -> StatelessBackendResult> { + self.device + .queue_capture_buffer(self.frame) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + self.output_buffer + .submit(self.timestamp, self.handle.as_raw_fd()) + .map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + self.handle.queue().map_err(|e| StatelessBackendError::Other(anyhow::anyhow!(e)))?; + Ok(PendingRequestHandle { + device: self.device.clone(), + timestamp: self.timestamp, + picture: self.picture, + }) + } + fn set_picture_ref(&mut self, picture: Weak>>) { + self.picture = picture; + } +} + +struct PendingRequestHandle { + device: V4l2Device, + timestamp: u64, + picture: Weak>>, +} + +impl PendingRequestHandle { + fn sync(self) -> DoneRequestHandle { + DoneRequestHandle { + capture_buffer: Rc::new(RefCell::new(self.device.sync(self.timestamp))), + } + } + fn associate_dequeued_buffer( + &mut self, + capture_buffer: V4l2CaptureBuffer, + ) -> DoneRequestHandle { + self.picture.upgrade().unwrap().as_ref().try_borrow_mut().unwrap().drop_references(); + DoneRequestHandle { capture_buffer: Rc::new(RefCell::new(capture_buffer)) } + } +} + +struct DoneRequestHandle { + capture_buffer: Rc>>, +} + +impl DoneRequestHandle { + fn result(&self) -> V4l2Result { + V4l2Result { capture_buffer: self.capture_buffer.clone() } + } +} + +#[derive(Default)] +enum RequestHandle { + Init(InitRequestHandle), + Pending(PendingRequestHandle), + Done(DoneRequestHandle), + #[default] + Unknown, +} + +impl RequestHandle { + fn new( + device: V4l2Device, + timestamp: u64, + handle: ioctl::Request, + output_buffer: V4l2OutputBuffer, + frame: V, + ) -> Self { + Self::Init(InitRequestHandle::new(device, timestamp, handle, output_buffer, frame)) + } + fn timestamp(&self) -> u64 { + match self { + Self::Init(handle) => handle.timestamp, + Self::Pending(handle) => handle.timestamp, + Self::Done(handle) => handle.capture_buffer.borrow().timestamp(), + _ => panic!("ERROR"), + } + } + fn which(&self) -> ioctl::CtrlWhich { + match self { + Self::Init(handle) => handle.which(), + _ => panic!("ERROR"), + } + } + fn ioctl(&mut self, ctrl: C) -> StatelessBackendResult<&mut Self> + where + C: Into>, + T: ExtControlTrait, + { + match self { + Self::Init(handle) => handle.ioctl(ctrl)?, + _ => { + return Err(StatelessBackendError::Other(anyhow::anyhow!( + "incorrect request state" + ))) + } + }; + Ok(self) + } + fn write(&mut self, data: &[u8]) -> &mut Self { + match self { + Self::Init(handle) => handle.write(data), + _ => panic!("ERROR"), + }; + self + } + + // This method can modify in-place instead of returning a new value. This removes the need for + // a RefCell in V4l2Request. + fn submit(&mut self) -> StatelessBackendResult<()> { + match std::mem::take(self) { + Self::Init(handle) => Ok(*self = Self::Pending(handle.submit()?)), + _ => Err(StatelessBackendError::Other(anyhow::anyhow!("incorrect request state"))), + } + } + fn sync(&mut self) { + match std::mem::take(self) { + Self::Pending(handle) => *self = Self::Done(handle.sync()), + s @ Self::Done(_) => *self = s, + _ => panic!("ERROR"), + } + } + fn result(&self) -> V4l2Result { + match self { + Self::Done(handle) => handle.result(), + _ => panic!("ERROR"), + } + } + fn set_picture_ref(&mut self, picture: Weak>>) { + match self { + Self::Init(handle) => handle.set_picture_ref(picture), + _ => panic!("ERROR"), + } + } + fn associate_dequeued_buffer(&mut self, capture_buffer: V4l2CaptureBuffer) { + match self { + Self::Pending(handle) => { + *self = Self::Done(handle.associate_dequeued_buffer(capture_buffer)) + } + _ => panic!("ERROR"), + } + } +} + +pub struct V4l2Request(RequestHandle); + +impl V4l2Request { + pub fn new( + device: V4l2Device, + timestamp: u64, + handle: ioctl::Request, + output_buffer: V4l2OutputBuffer, + frame: V, + ) -> Self { + Self(RequestHandle::new(device, timestamp, handle, output_buffer, frame)) + } + pub fn timestamp(&self) -> u64 { + self.0.timestamp() + } + pub fn which(&self) -> ioctl::CtrlWhich { + self.0.which() + } + pub fn ioctl(&mut self, ctrl: C) -> StatelessBackendResult<&mut Self> + where + C: Into>, + T: ExtControlTrait, + { + self.0.ioctl(ctrl)?; + Ok(self) + } + pub fn write(&mut self, data: &[u8]) -> &mut Self { + self.0.write(data); + self + } + pub fn submit(&mut self) -> StatelessBackendResult<()> { + self.0.submit() + } + pub fn sync(&mut self) { + self.0.sync(); + } + pub fn result(&self) -> V4l2Result { + self.0.result() + } + pub fn set_picture_ref(&mut self, picture: Weak>>) { + self.0.set_picture_ref(picture); + } + pub fn associate_dequeued_buffer(&mut self, capture_buffer: V4l2CaptureBuffer) { + self.0.associate_dequeued_buffer(capture_buffer) + } +} + +pub struct V4l2Result { + pub capture_buffer: Rc>>, +} diff --git a/vendor/cros-codecs/src/device/v4l2/utils.rs b/vendor/cros-codecs/src/device/v4l2/utils.rs new file mode 100644 index 0000000..d4232c1 --- /dev/null +++ b/vendor/cros-codecs/src/device/v4l2/utils.rs @@ -0,0 +1,130 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::ffi::c_char; +use std::path::PathBuf; +use std::sync::Arc; + +use v4l2r::device::queue::Queue; +use v4l2r::device::{Device as VideoDevice, DeviceConfig}; +use v4l2r::ioctl::Capability; +use v4l2r::nix::fcntl::{open, OFlag}; +use v4l2r::nix::sys::stat::Mode; +use zerocopy::FromZeros; + +const MAX_DEVICE_NO: usize = 128; + +/// Enumerate V4L2 (video and media) devices on the system. +pub fn enumerate_devices() -> Option<(PathBuf, PathBuf)> { + let decoder_device_prefix = "/dev/video"; + + for dev_no in 0..MAX_DEVICE_NO { + let video_device_path = PathBuf::from(format!("{}{}", decoder_device_prefix, dev_no)); + let video_device_config = DeviceConfig::new().non_blocking_dqbuf(); + + let device = match VideoDevice::open(&video_device_path, video_device_config) { + Ok(device) => Arc::new(device), + Err(_) => continue, + }; + + if Queue::get_output_mplane_queue(device.clone()).is_err() { + continue; + } + + let caps = device.caps(); + if let Some(media_device_path) = find_media_device(caps) { + log::info!( + "Using video device {:?} with media device {:?}", + video_device_path, + media_device_path + ); + return Some((video_device_path, media_device_path)); + } + } + None +} + +/// A struct that contains information about media device. +/// +/// See: https://docs.kernel.org/userspace-api/media/mediactl/media-ioc-device-info.html +#[repr(C)] +#[derive(FromZeros)] +pub struct MediaDeviceInfo { + driver: [c_char; 16], + model: [c_char; 32], + serial: [c_char; 40], + bus_info: [c_char; 32], + media_version: u32, + hw_revision: u32, + driver_version: u32, + reserved: [u32; 31], +} + +const IOCTL_MEDIA_COMMAND: u8 = b'|'; +pub const MEDIA_IOC_DEVICE_INFO: u8 = 0x00; +use nix::ioctl_readwrite; +ioctl_readwrite!( + media_ioc_device_info, + IOCTL_MEDIA_COMMAND, + MEDIA_IOC_DEVICE_INFO, + MediaDeviceInfo +); + +fn parse_c_str_from_array(arr: &[c_char]) -> String { + let bytes: Vec = arr.iter().map(|&c| c as u8).take_while(|&c| c != 0).collect(); + String::from_utf8_lossy(&bytes).trim().to_string() +} + +/// Find media device according to the decode device's capabilities. +pub fn find_media_device(cap: &Capability) -> Option { + let media_device_prefix = "/dev/media"; + + for dev_no in 0..MAX_DEVICE_NO { + let media_device_path = PathBuf::from(format!("{}{}", media_device_prefix, dev_no)); + let media_device = + match open(&media_device_path, OFlag::O_RDWR | OFlag::O_CLOEXEC, Mode::empty()) { + Ok(media_device) => media_device, + Err(_) => continue, + }; + + // MediaDeviceInfo is a struct which contains only fields for which 0 is a valid + // bit pattern. + let mut media_device_info = MediaDeviceInfo::new_zeroed(); + let media_device_info = unsafe { + // SAFETY: This should be safe, as the `media_ioc_device_info` ioctl is called with + // `media_device` - a valid file descriptor and `media_device_info` - a valid pointer + // to `MediaDeviceInfo` struct. + match media_ioc_device_info(media_device, &mut media_device_info) { + Ok(_) => Some(media_device_info), + Err(_) => None, + } + }; + + // Match the video device and the media controller by the |bus_info| + // field. This works better than |driver| field if there are multiple + // instances of the same decoder driver in the system + if let Some(media_bus_info) = + media_device_info.as_ref().map(|info| parse_c_str_from_array(&info.bus_info)) + { + if !cap.bus_info.is_empty() + && !media_bus_info.is_empty() + && cap.bus_info == *media_bus_info + { + return Some(media_device_path); + } + } + + // Fall back to matching the video device and the media controller by the + // driver field. The mtk-vcodec driver does not fill the card and bus fields + // properly, so those won't work. + if let Some(driver) = + media_device_info.as_ref().map(|info| parse_c_str_from_array(&info.driver)) + { + if !cap.bus_info.is_empty() && !driver.is_empty() && cap.driver == *driver { + return Some(media_device_path); + } + } + } + None +} diff --git a/vendor/cros-codecs/src/encoder.rs b/vendor/cros-codecs/src/encoder.rs new file mode 100644 index 0000000..43da14b --- /dev/null +++ b/vendor/cros-codecs/src/encoder.rs @@ -0,0 +1,418 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::fmt; + +pub mod av1; +pub mod h264; +pub mod h265; +pub mod vp8; +pub mod vp9; + +pub mod stateful; +pub mod stateless; + +use crate::codec::av1::synthesizer::SynthesizerError as AV1SynthesizerError; +use crate::codec::h264::synthesizer::SynthesizerError as H264SynthesizerError; +use crate::encoder::stateful::StatefulBackendError; +use crate::encoder::stateless::StatelessBackendError; +use crate::FrameLayout; + +/// Specifies the encoder operation +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RateControl { + /// The encoder shall maintain the constant bitrate + ConstantBitrate(u64), + + /// The encoder shall maintain codec specific quality parameter constant (eg. QP for H.264) + /// disregarding bitrate. + ConstantQuality(u32), +} + +impl RateControl { + #[allow(dead_code)] + pub(crate) fn is_same_variant(left: &Self, right: &Self) -> bool { + std::mem::discriminant(left) == std::mem::discriminant(right) + } + + pub(crate) fn bitrate_target(&self) -> Option { + match self { + RateControl::ConstantBitrate(target) => Some(*target), + RateControl::ConstantQuality(_) => None, + } + } +} + +#[derive(Clone)] +pub enum PredictionStructure { + /// Simplest prediction structure, suitable eg. for RTC. Interframe is produced at the start of + /// the stream and every time when `limit` frames are reached. Following interframe frames + /// are frames relying solely on the last frame. + LowDelay { limit: u16 }, +} + +/// Dynamic parameters of the encoded stream that client may choose to change during the encoding +/// session without recreating the entire encoder instance. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tunings { + /// The stream's [`RateControl`] + pub rate_control: RateControl, + /// Stream framerate in frames per second + pub framerate: u32, + /// Minimum value of codec specific quality parameter constant (eg. QP for H.264) + pub min_quality: u32, + /// Maximum value of codec specific quality parameter constant (eg. QP for H.264) + pub max_quality: u32, +} + +impl Default for Tunings { + fn default() -> Self { + Self { + rate_control: RateControl::ConstantBitrate(200_000), + framerate: 30, + min_quality: 0, + max_quality: u32::MAX, + } + } +} + +/// Encoder's input metadata +#[derive(Debug, Clone)] +pub struct FrameMetadata { + pub timestamp: u64, + pub layout: FrameLayout, + pub force_keyframe: bool, +} + +/// Encoder's coded output with contained frame. +pub struct CodedBitstreamBuffer { + /// [`FrameMetadata`] of the frame that is compressed in [`Self::bitstream`] + pub metadata: FrameMetadata, + + /// Bitstream with compressed frame together with optionally other compressed control messages + pub bitstream: Vec, +} + +impl CodedBitstreamBuffer { + pub fn new(metadata: FrameMetadata, bitstream: Vec) -> Self { + Self { metadata, bitstream } + } +} + +impl From for Vec { + fn from(value: CodedBitstreamBuffer) -> Self { + value.bitstream + } +} + +#[derive(Debug)] +pub enum EncodeError { + Unsupported, + InvalidInternalState, + StatelessBackendError(StatelessBackendError), + StatefulBackendError(StatefulBackendError), + H264SynthesizerError(H264SynthesizerError), + AV1SynthesizerError(AV1SynthesizerError), +} + +impl fmt::Display for EncodeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + EncodeError::Unsupported => write!(f, "unsupported"), + EncodeError::InvalidInternalState => { + write!(f, "invalid internal state. This is likely a bug.") + } + EncodeError::StatelessBackendError(x) => write!(f, "{}", x.to_string()), + EncodeError::StatefulBackendError(x) => write!(f, "{}", x.to_string()), + EncodeError::H264SynthesizerError(x) => write!(f, "{}", x.to_string()), + EncodeError::AV1SynthesizerError(x) => write!(f, "{}", x.to_string()), + } + } +} + +impl From for EncodeError { + fn from(err: StatelessBackendError) -> Self { + EncodeError::StatelessBackendError(err) + } +} + +impl From for EncodeError { + fn from(err: StatefulBackendError) -> Self { + EncodeError::StatefulBackendError(err) + } +} + +impl From for EncodeError { + fn from(err: H264SynthesizerError) -> Self { + EncodeError::H264SynthesizerError(err) + } +} + +impl From for EncodeError { + fn from(err: AV1SynthesizerError) -> Self { + EncodeError::AV1SynthesizerError(err) + } +} + +pub type EncodeResult = Result; + +/// Generic video encoder interface. +pub trait VideoEncoder { + /// Changes dynamic parameters (aka [`Tunings`]) of the encoded stream. The change may not be + /// effective right away. Depending on the used prediction structure, the `Predictor` may + /// choose to delay the change until entire or a some part of the structure had been encoded. + /// + /// Note: Currently changing the variant of [`RateControl`] is not supported. + fn tune(&mut self, tunings: Tunings) -> EncodeResult<()>; + + /// Enqueues the frame for encoding. The implementation will drop the handle after it is no + /// longer be needed. The encoder is not required to immediately start processing the frame + /// and yield output bitstream. It is allowed to hold frames until certain conditions are met + /// eg. for specified prediction structures or referencing in order to further optimize + /// the compression rate of the bitstream. + fn encode(&mut self, meta: FrameMetadata, handle: Handle) -> Result<(), EncodeError>; + + /// Drains the encoder. This means that encoder is required to finish processing of all the + /// frames in the internal queue and yield output bitstream by the end of the call. The output + /// bitstream then can be polled using [`Self::poll`] function. + /// + /// Drain does not enforce the flush of the internal state, ie. the enqueued frame handles + /// do not have to be returned to user (dropped) and key frame is not enforced on the next + /// frame. + fn drain(&mut self) -> EncodeResult<()>; + + /// Polls on the encoder for the available output bitstream with compressed frames that where + /// submitted with [`Self::encode`]. + /// + /// The call may also trigger a further processing aside of returning output. Therefore it + /// *recommended* that this function is called frequently. + fn poll(&mut self) -> EncodeResult>; +} + +pub fn simple_encode_loop( + encoder: &mut impl VideoEncoder, + frame_producer: &mut impl Iterator, + mut coded_consumer: impl FnMut(CodedBitstreamBuffer), +) -> EncodeResult<()> { + for (meta, handle) in frame_producer.by_ref() { + encoder.encode(meta, handle)?; + while let Some(coded) = encoder.poll()? { + coded_consumer(coded); + } + } + + encoder.drain()?; + while let Some(coded) = encoder.poll()? { + coded_consumer(coded); + } + + Ok(()) +} + +#[cfg(test)] +pub(crate) mod tests { + #[cfg(feature = "v4l2")] + use crate::encoder::FrameMetadata; + #[cfg(feature = "v4l2")] + use crate::utils::UserPtrFrame; + #[cfg(feature = "v4l2")] + use crate::Fourcc; + #[cfg(feature = "v4l2")] + use crate::FrameLayout; + + pub fn get_test_frame_t(ts: u64, max_ts: u64) -> f32 { + 2.0 * std::f32::consts::PI * (ts as f32) / (max_ts as f32) + } + + pub fn gen_test_frame(frame_width: usize, frame_height: usize, t: f32, mut set_pix: F) + where + F: FnMut(usize, usize, [f32; 3]), + { + let width = frame_width as f32; + let height = frame_height as f32; + let (sin, cos) = f32::sin_cos(t); + let (sin2, cos2) = (sin.powi(2), cos.powi(2)); + + // Pick the dot position + let dot_col = height * (1.1 + 2.0 * sin * cos) / 2.2; + let dot_row = width * (1.1 + sin) / 2.2; + let dot_size2 = (width.min(height) * 0.05).powi(2); + + // Luma + for frame_row in 0..frame_height { + #[allow(clippy::needless_range_loop)] + for frame_col in 0..frame_width { + let row = frame_row as f32; + let col = frame_col as f32; + + let dist = (dot_col - col).powi(2) + (dot_row - row).powi(2); + + let y = if dist < dot_size2 { 0.0 } else { (row + col) / (width + height) }; + + let (u, v) = if dist < dot_size2 { + (0.5, 0.5) + } else { + ((row / width) * sin2, (col / height) * cos2) + }; + + set_pix(frame_col, frame_row, [y, u, v]); + } + } + } + + pub fn fill_test_frame_nm12( + width: usize, + height: usize, + strides: [usize; 2], + t: f32, + y_plane: &mut [u8], + uv_plane: &mut [u8], + ) { + gen_test_frame(width, height, t, |col, row, yuv| { + /// Maximum value of color component for NV12 + const MAX_COMP_VAL: f32 = 0xff as f32; + + let (y, u, v) = ( + (yuv[0] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, + (yuv[1] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, + (yuv[2] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u8, + ); + let y_pos = row * strides[0] + col; + + y_plane[y_pos] = y; + + // Subsample with upper left pixel + if col % 2 == 0 && row % 2 == 0 { + let u_pos = (row / 2) * strides[1] + col; + let v_pos = u_pos + 1; + + uv_plane[u_pos] = u; + uv_plane[v_pos] = v; + } + }); + } + + pub fn fill_test_frame_nv12( + width: usize, + height: usize, + strides: [usize; 2], + offsets: [usize; 2], + t: f32, + raw: &mut [u8], + ) { + let (y_plane, uv_plane) = raw.split_at_mut(offsets[1]); + let y_plane = &mut y_plane[offsets[0]..]; + + fill_test_frame_nm12(width, height, strides, t, y_plane, uv_plane) + } + + pub fn fill_test_frame_p010( + width: usize, + height: usize, + strides: [usize; 2], + offsets: [usize; 2], + t: f32, + raw: &mut [u8], + ) { + gen_test_frame(width, height, t, |col, row, yuv| { + /// Maximum value of color component for P010 + const MAX_COMP_VAL: f32 = 0x3ff as f32; + + let (y, u, v) = ( + (yuv[0] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, + (yuv[1] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, + (yuv[2] * MAX_COMP_VAL).clamp(0.0, MAX_COMP_VAL) as u16, + ); + let y_pos = offsets[0] + row * strides[0] + 2 * col; + + raw[y_pos] = ((y << 6) & 0xa0) as u8; + raw[y_pos + 1] = (y >> 2) as u8; + + // Subsample with upper left pixel + if col % 2 == 0 && row % 2 == 0 { + let u_pos = offsets[1] + (row / 2) * strides[1] + 2 * col; + let v_pos = u_pos + 2; + + raw[u_pos] = ((u << 6) & 0xa0) as u8; + raw[u_pos + 1] = (u >> 2) as u8; + raw[v_pos] = ((v << 6) & 0xa0) as u8; + raw[v_pos + 1] = (v >> 2) as u8; + } + }); + } + + #[cfg(feature = "v4l2")] + pub fn userptr_test_frame_generator( + frame_count: u64, + layout: FrameLayout, + buffer_size: usize, + ) -> impl Iterator { + (0..frame_count).map(move |timestamp| { + let frame = UserPtrFrame::alloc(layout.clone(), buffer_size); + + let t = get_test_frame_t(timestamp, frame_count); + + if (frame.layout.format.0 == Fourcc::from(b"NM12") + || frame.layout.format.0 == Fourcc::from(b"NV12")) + && frame.layout.planes.len() == 2 + && frame.buffers.len() == 2 + { + // SAFETY: Slice matches the allocation + let y_plane = unsafe { + std::slice::from_raw_parts_mut( + frame.buffers[frame.layout.planes[0].buffer_index], + frame.mem_layout.size(), + ) + }; + // SAFETY: Slice matches the allocation + let uv_plane = unsafe { + std::slice::from_raw_parts_mut( + frame.buffers[frame.layout.planes[1].buffer_index], + frame.mem_layout.size(), + ) + }; + + fill_test_frame_nm12( + frame.layout.size.width as usize, + frame.layout.size.height as usize, + [frame.layout.planes[0].stride, frame.layout.planes[1].stride], + t, + y_plane, + uv_plane, + ); + } else if frame.layout.format.0 == Fourcc::from(b"NV12") + && frame.layout.planes.len() == 1 + && frame.buffers.len() == 1 + { + // SAFETY: Slice matches the allocation + let raw = unsafe { + std::slice::from_raw_parts_mut( + frame.buffers[frame.layout.planes[0].buffer_index] + .add(frame.layout.planes[0].offset), + frame.mem_layout.size(), + ) + }; + + let uv_stride = frame.layout.planes[0].stride; + let uv_offset = frame.layout.planes[0].stride * (frame.layout.size.height as usize); + + fill_test_frame_nv12( + frame.layout.size.width as usize, + frame.layout.size.height as usize, + [frame.layout.planes[0].stride, uv_stride], + [frame.layout.planes[0].offset, uv_offset], + t, + raw, + ); + } else { + panic!("Unrecognized frame layout used during test"); + } + + let meta = + FrameMetadata { timestamp, layout: frame.layout.clone(), force_keyframe: false }; + + (meta, frame) + }) + } +} diff --git a/vendor/cros-codecs/src/encoder/av1.rs b/vendor/cros-codecs/src/encoder/av1.rs new file mode 100644 index 0000000..8c402ae --- /dev/null +++ b/vendor/cros-codecs/src/encoder/av1.rs @@ -0,0 +1,34 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::av1::parser::BitDepth; +use crate::codec::av1::parser::Profile; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Resolution; + +pub struct AV1; + +#[derive(Clone)] +pub struct EncoderConfig { + pub profile: Profile, + pub bit_depth: BitDepth, + pub resolution: Resolution, + pub pred_structure: PredictionStructure, + /// Initial tunings values + pub initial_tunings: Tunings, +} + +impl Default for EncoderConfig { + fn default() -> Self { + // Artificially encoder configuration with intent to be widely supported. + Self { + profile: Profile::Profile0, + bit_depth: BitDepth::Depth8, + resolution: Resolution { width: 320, height: 240 }, + pred_structure: PredictionStructure::LowDelay { limit: 1024 }, + initial_tunings: Default::default(), + } + } +} diff --git a/vendor/cros-codecs/src/encoder/h264.rs b/vendor/cros-codecs/src/encoder/h264.rs new file mode 100644 index 0000000..ee7d6c2 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/h264.rs @@ -0,0 +1,34 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::h264::parser::Level; +use crate::codec::h264::parser::Profile; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Resolution; + +pub struct H264; + +#[derive(Clone)] +pub struct EncoderConfig { + pub resolution: Resolution, + pub profile: Profile, + pub level: Level, + pub pred_structure: PredictionStructure, + /// Initial tunings values + pub initial_tunings: Tunings, +} + +impl Default for EncoderConfig { + fn default() -> Self { + // Artificially encoder configuration with intent to be widely supported. + Self { + resolution: Resolution { width: 320, height: 240 }, + profile: Profile::Baseline, + level: Level::L4, + pred_structure: PredictionStructure::LowDelay { limit: 2048 }, + initial_tunings: Default::default(), + } + } +} diff --git a/vendor/cros-codecs/src/encoder/h265.rs b/vendor/cros-codecs/src/encoder/h265.rs new file mode 100644 index 0000000..512bd21 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/h265.rs @@ -0,0 +1,30 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::h265::parser::Level; +use crate::codec::h265::parser::Profile; +use crate::encoder::PredictionStructure; +use crate::Resolution; + +pub struct H265; + +#[derive(Clone)] +pub struct EncoderConfig { + pub resolution: Resolution, + pub profile: Profile, + pub level: Level, + pub pred_structure: PredictionStructure, +} + +impl Default for EncoderConfig { + fn default() -> Self { + // Artificially encoder configuration with intent to be widely supported. + Self { + resolution: Resolution { width: 320, height: 240 }, + profile: Profile::Main, + level: Level::L4, + pred_structure: PredictionStructure::LowDelay { limit: 2048 }, + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateful.rs b/vendor/cros-codecs/src/encoder/stateful.rs new file mode 100644 index 0000000..d156e55 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful.rs @@ -0,0 +1,257 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::collections::BTreeSet; +use std::collections::VecDeque; + +use thiserror::Error; + +use crate::encoder::CodedBitstreamBuffer; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::Tunings; +use crate::encoder::VideoEncoder; + +pub mod h264; +pub mod h265; +pub mod vp8; +pub mod vp9; + +#[derive(Debug, Error)] +pub enum StatefulBackendError { + #[error("invalid internal state. This is likely a bug.")] + InvalidInternalState, + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +pub type StatefulBackendResult = Result; + +/// Unique identifier of the [`BackendRequest`] +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct BackendRequestId(usize); + +/// Request package that is offered to [`StatefulVideoEncoderBackend`] for processing +pub struct BackendRequest { + /// Request's unique identifier + pub request_id: BackendRequestId, + /// Frame's metadata + pub meta: FrameMetadata, + /// Frame's handle + pub handle: Handle, + /// Tunings set for the request + pub tunings: Tunings, +} + +pub struct BackendOutput { + /// Request's unique identifier corresponding to [`BackendRequest`] + pub request_id: BackendRequestId, + /// Result of the request. [`CodedBitstreamBuffer`] containing encoded frame + pub buffer: CodedBitstreamBuffer, +} + +/// Generic trait for stateful encoder backends +pub trait StatefulVideoEncoderBackend { + /// Try to submit encode request to the backend. The backend may not be able to accept the + /// request eg. if there are not enough available resources or backend desires to finish + /// previous request first. The function shall not be blocking. + /// If backend accepts the request for processing it shall take the `request` (take ownership of + /// [`BackendRequest`] and set ref mut to [`None`]. + fn consume_request( + &mut self, + request: &mut Option>, + ) -> StatefulBackendResult<()>; + + /// Function shall block, until the backend can accept request with [`consume_request`] or + /// will finished processing of some [`BackendRequest`] and [`poll`] can be used to + /// fetch is result. + /// + /// [`consume_request`]: StatefulVideoEncoderBackend::consume_request + /// [`poll`]: StatefulVideoEncoderBackend::poll + fn sync(&mut self) -> StatefulBackendResult<()>; + + /// Blocking function, until the backend finishes processing all [`BackendRequest`], that the + /// backend has accepted and all outputs of those requests are returned. + fn drain(&mut self) -> StatefulBackendResult>; + + /// If the processing of any [`BackendRequest`] is finished then the function should yield it's + /// corresponding [`BackendOutput`]. + /// + /// [`consume_request`]: StatefulVideoEncoderBackend::consume_request + fn poll(&mut self) -> StatefulBackendResult>; +} + +pub struct StatefulEncoder +where + Backend: StatefulVideoEncoderBackend, +{ + /// Pending queue of frames to encoded by the backend + queue: VecDeque>, + + /// Unique request identifier continue + request_counter: usize, + + /// Latest [`Tunings`], that will be cloned in to request + tunings: Tunings, + + /// Processed encoded bitstream queue for client to poll + coded_queue: VecDeque, + + /// Currently processed requests by the backend + processing: BTreeSet, + + // [`StatefulVideoEncoderBackend`] instance to delegate [`BackendRequest`] to + backend: Backend, +} + +impl StatefulEncoder +where + Backend: StatefulVideoEncoderBackend, +{ + /// Utility function that creates an new [`StatefulEncoder`] with [`Tunings`] and + /// [`StatefulVideoEncoderBackend`] instance. + #[allow(dead_code)] + fn create(tunings: Tunings, backend: Backend) -> Self { + Self { + queue: Default::default(), + request_counter: 0, + tunings, + coded_queue: Default::default(), + processing: Default::default(), + backend, + } + } + + /// Handles the [`BackendOutput`] from the backend, ie add to the queue for client to poll. + fn handle_output(&mut self, output: BackendOutput) -> EncodeResult<()> { + log::debug!( + "Backend yieled output buffer for request id={:?} timestamp={} bytes={}", + output.request_id, + output.buffer.metadata.timestamp, + output.buffer.bitstream.len() + ); + if !self.processing.remove(&output.request_id) { + log::warn!("Coded buffer returned for non existing or already processed request id={:?} timestamp={}", + output.request_id, + output.buffer.metadata.timestamp, + ); + } + self.coded_queue.push_back(output.buffer); + Ok(()) + } + + /// Poll the backend for outputs and handles them + fn poll_backend(&mut self) -> EncodeResult<()> { + while let Some(output) = self.backend.poll()? { + self.handle_output(output)?; + } + + Ok(()) + } + + /// Performs essential processing. Poll the backend for outputs and tries to submit requests to + /// backends. + fn process(&mut self) -> EncodeResult<()> { + log::debug!( + "Pending requests: {}, currently processed: {:?}, pending coded buffer: {}", + self.queue.len(), + self.processing, + self.coded_queue.len() + ); + + if !self.processing.is_empty() { + self.poll_backend()?; + } + + while let Some(request) = self.queue.pop_front() { + let request_id = request.request_id; + let timestamp = request.meta.timestamp; + let mut request = Some(request); + + log::trace!("Passing request to backend id={request_id:?} timestamp={timestamp}"); + self.backend.consume_request(&mut request)?; + + if let Some(request) = request { + log::trace!("Backend stalled request id={request_id:?} timestamp={timestamp}"); + self.queue.push_front(request); + break; + } else { + log::debug!("Backend consumed request id={request_id:?} timestamp={timestamp}"); + self.processing.insert(request_id); + } + } + + Ok(()) + } + + /// [`StatefulVideoEncoderBackend`]'s instance + pub fn backend(&mut self) -> &Backend { + &self.backend + } +} + +impl VideoEncoder for StatefulEncoder +where + Backend: StatefulVideoEncoderBackend, +{ + fn tune(&mut self, tunings: Tunings) -> EncodeResult<()> { + self.tunings = tunings; + Ok(()) + } + + fn encode(&mut self, meta: FrameMetadata, handle: Handle) -> Result<(), EncodeError> { + let request_id = BackendRequestId(self.request_counter); + self.request_counter = self.request_counter.wrapping_add(1); + + log::trace!("Got new request id={request_id:?} timestamp={}", meta.timestamp); + + let request = BackendRequest { request_id, meta, handle, tunings: self.tunings.clone() }; + + self.queue.push_back(request); + self.process()?; + + Ok(()) + } + + fn poll(&mut self) -> EncodeResult> { + if !self.queue.is_empty() || !self.processing.is_empty() { + self.process()?; + } + + if let Some(buffer) = self.coded_queue.pop_front() { + log::debug!("Returning coded buffer timestamp={}", buffer.metadata.timestamp); + return Ok(Some(buffer)); + } + Ok(None) + } + + fn drain(&mut self) -> EncodeResult<()> { + log::debug!( + "Got drain request. Pending in queue: {}. Currently processed: {:?}", + self.queue.len(), + self.processing + ); + + while !self.queue.is_empty() { + self.process()?; + + if !self.queue.is_empty() { + self.backend.sync()?; + } + } + + if self.processing.is_empty() { + log::debug!("Skipping drain request to backend, everything is drained"); + } + + log::debug!("Sending drain request to backend"); + for output in self.backend.drain()? { + self.handle_output(output)?; + } + + Ok(()) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateful/h264.rs b/vendor/cros-codecs/src/encoder/stateful/h264.rs new file mode 100644 index 0000000..e82a330 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/h264.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +pub mod v4l2; diff --git a/vendor/cros-codecs/src/encoder/stateful/h264/v4l2.rs b/vendor/cros-codecs/src/encoder/stateful/h264/v4l2.rs new file mode 100644 index 0000000..0e9efd7 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/h264/v4l2.rs @@ -0,0 +1,313 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::sync::Arc; + +use v4l2r::controls::codec::VideoGopSize; +use v4l2r::controls::codec::VideoH264IPeriod; +use v4l2r::controls::codec::VideoH264Level; +use v4l2r::controls::codec::VideoH264MaxQp; +use v4l2r::controls::codec::VideoH264MinQp; +use v4l2r::controls::codec::VideoH264Profile; +use v4l2r::controls::codec::VideoPrependSpsPpsToIdr; +use v4l2r::device::Device; + +use crate::backend::v4l2::encoder::CaptureBuffers; +use crate::backend::v4l2::encoder::ControlError; +use crate::backend::v4l2::encoder::EncoderCodec; +use crate::backend::v4l2::encoder::InitializationError; +use crate::backend::v4l2::encoder::OutputBufferHandle; +use crate::backend::v4l2::encoder::V4L2Backend; +use crate::codec::h264::parser::Level; +use crate::codec::h264::parser::Profile; +use crate::encoder::h264::EncoderConfig; +use crate::encoder::h264::H264; +use crate::encoder::stateful::StatefulEncoder; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Fourcc; +use crate::Resolution; + +const PIXEL_FORMAT_H264: v4l2r::PixelFormat = v4l2r::PixelFormat::from_fourcc(b"H264"); + +pub type V4L2H264Backend = V4L2Backend; + +pub type V4L2StatefulH264Encoder = + StatefulEncoder>; + +impl From for VideoH264Level { + fn from(value: Level) -> Self { + match value { + Level::L1 => VideoH264Level::L1_0, + Level::L1B => VideoH264Level::L1B, + Level::L1_1 => VideoH264Level::L1_1, + Level::L1_2 => VideoH264Level::L1_2, + Level::L1_3 => VideoH264Level::L1_3, + Level::L2_0 => VideoH264Level::L2_0, + Level::L2_1 => VideoH264Level::L2_1, + Level::L2_2 => VideoH264Level::L2_2, + Level::L3 => VideoH264Level::L3_0, + Level::L3_1 => VideoH264Level::L3_1, + Level::L3_2 => VideoH264Level::L3_2, + Level::L4 => VideoH264Level::L4_0, + Level::L4_1 => VideoH264Level::L4_1, + Level::L4_2 => VideoH264Level::L4_2, + Level::L5 => VideoH264Level::L5_0, + Level::L5_1 => VideoH264Level::L5_1, + Level::L5_2 => VideoH264Level::L5_2, + Level::L6 => VideoH264Level::L6_0, + Level::L6_1 => VideoH264Level::L6_1, + Level::L6_2 => VideoH264Level::L6_2, + } + } +} + +impl From for VideoH264Profile { + fn from(value: Profile) -> Self { + match value { + Profile::Baseline => Self::Baseline, + Profile::Main => Self::Main, + Profile::Extended => Self::Extended, + Profile::High => Self::High, + Profile::High10 => Self::High10, + Profile::High422P => Self::High422, + } + } +} + +impl EncoderCodec for V4L2H264Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError> { + let min_qp = VideoH264MinQp(tunings.min_quality.clamp(1, 51) as i32); + Self::apply_ctrl(device, "h264 min qp", min_qp)?; + + let max_qp = VideoH264MaxQp(tunings.max_quality.clamp(1, 51) as i32); + Self::apply_ctrl(device, "h264 max qp", max_qp)?; + + Ok(()) + } +} + +impl V4L2H264Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + match config.pred_structure { + PredictionStructure::LowDelay { limit } => { + let limit = limit as i32; + + Self::apply_ctrl(&device, "gop size", VideoGopSize(limit))?; + Self::apply_ctrl(&device, "h264 i period", VideoH264IPeriod(limit))?; + } + } + + Self::apply_ctrl(&device, "prepend SPS PPS to IDR", VideoPrependSpsPpsToIdr(true))?; + Self::apply_ctrl(&device, "h264 profile", VideoH264Profile::from(config.profile))?; + Self::apply_ctrl(&device, "h264 level", VideoH264Level::from(config.level))?; + + Self::create( + device, + capture_buffers, + fourcc, + coded_size, + config.resolution, + PIXEL_FORMAT_H264, + tunings, + ) + } +} + +impl V4L2StatefulH264Encoder +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + Ok(Self::create( + tunings.clone(), + V4L2H264Backend::new(device, capture_buffers, config, fourcc, coded_size, tunings)?, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::path::PathBuf; + use std::sync::Arc; + + use v4l2r::device::Device; + use v4l2r::device::DeviceConfig; + + use crate::backend::v4l2::encoder::find_device_with_capture; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_dmabuf_test; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_mmap_test; + use crate::backend::v4l2::encoder::tests::BoPoolAllocator; + use crate::backend::v4l2::encoder::tests::GbmDevice; + use crate::backend::v4l2::encoder::v4l2_format_to_frame_layout; + use crate::backend::v4l2::encoder::MmapingCapture; + use crate::encoder::simple_encode_loop; + use crate::encoder::tests::userptr_test_frame_generator; + use crate::encoder::RateControl; + use crate::utils::DmabufFrame; + use crate::Resolution; + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_userptr() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_H264).expect("no H264 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let mut encoder = V4L2StatefulH264Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + let layout = v4l2_format_to_frame_layout(&format); + + let mut bitstream = Vec::new(); + let buffer_size = + format.plane_fmt.iter().map(|plane| plane.sizeimage).max().unwrap() as usize; + let mut frame_producer = userptr_test_frame_generator(FRAME_COUNT, layout, buffer_size); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + bitstream.extend(coded.bitstream) + }) + .expect("encode loop"); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_userptr.h264").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_mmap() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_H264).expect("no H264 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let encoder = V4L2StatefulH264Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + perform_v4l2_encoder_mmap_test(FRAME_COUNT, encoder, |coded| { + bitstream.extend(coded.bitstream) + }); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_mmap.h264").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_dmabuf() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_H264).expect("no H264 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let gbm = GbmDevice::open(PathBuf::from("/dev/dri/renderD128")) + .and_then(gbm::Device::new) + .expect("failed to create GBM device"); + + let gbm = Arc::new(gbm); + + let encoder = V4L2StatefulH264Encoder::::new( + device.clone(), + BoPoolAllocator::new(gbm.clone()), + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NV12"), + CODED_SIZE, + Tunings { + framerate: 30, + rate_control: RateControl::ConstantBitrate(400_000), + ..Default::default() + }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + perform_v4l2_encoder_dmabuf_test( + CODED_SIZE, + VISIBLE_SIZE, + FRAME_COUNT, + gbm, + encoder, + |coded| bitstream.extend(coded.bitstream), + ); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_dmabuf.h264").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateful/h265.rs b/vendor/cros-codecs/src/encoder/stateful/h265.rs new file mode 100644 index 0000000..e82a330 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/h265.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +pub mod v4l2; diff --git a/vendor/cros-codecs/src/encoder/stateful/h265/v4l2.rs b/vendor/cros-codecs/src/encoder/stateful/h265/v4l2.rs new file mode 100644 index 0000000..f905d85 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/h265/v4l2.rs @@ -0,0 +1,305 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::sync::Arc; + +use v4l2r::controls::codec::VideoGopSize; +use v4l2r::controls::codec::VideoHEVCLevel; +use v4l2r::controls::codec::VideoHEVCMaxQp; +use v4l2r::controls::codec::VideoHEVCMinQp; +use v4l2r::controls::codec::VideoHEVCProfile; +use v4l2r::controls::codec::VideoPrependSpsPpsToIdr; +use v4l2r::device::Device; + +use crate::backend::v4l2::encoder::CaptureBuffers; +use crate::backend::v4l2::encoder::ControlError; +use crate::backend::v4l2::encoder::EncoderCodec; +use crate::backend::v4l2::encoder::InitializationError; +use crate::backend::v4l2::encoder::OutputBufferHandle; +use crate::backend::v4l2::encoder::UnsupportedError; +use crate::backend::v4l2::encoder::V4L2Backend; +use crate::codec::h265::parser::Level; +use crate::codec::h265::parser::Profile; +use crate::encoder::h265::EncoderConfig; +use crate::encoder::h265::H265; +use crate::encoder::stateful::StatefulEncoder; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Fourcc; +use crate::Resolution; + +const PIXEL_FORMAT_HEVC: v4l2r::PixelFormat = v4l2r::PixelFormat::from_fourcc(b"HEVC"); + +pub type V4L2H265Backend = V4L2Backend; + +pub type V4L2StatefulH265Encoder = + StatefulEncoder>; + +impl From for VideoHEVCLevel { + fn from(value: Level) -> Self { + match value { + Level::L1 => VideoHEVCLevel::L1_0, + Level::L2 => VideoHEVCLevel::L2_0, + Level::L2_1 => VideoHEVCLevel::L2_1, + Level::L3 => VideoHEVCLevel::L3_0, + Level::L3_1 => VideoHEVCLevel::L3_1, + Level::L4 => VideoHEVCLevel::L4_0, + Level::L4_1 => VideoHEVCLevel::L4_1, + Level::L5 => VideoHEVCLevel::L5_0, + Level::L5_1 => VideoHEVCLevel::L5_1, + Level::L5_2 => VideoHEVCLevel::L5_2, + Level::L6 => VideoHEVCLevel::L6_0, + Level::L6_1 => VideoHEVCLevel::L6_1, + Level::L6_2 => VideoHEVCLevel::L6_2, + } + } +} + +impl EncoderCodec for V4L2H265Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError> { + let min_qp = VideoHEVCMinQp(tunings.min_quality.clamp(1, 51) as i32); + Self::apply_ctrl(device, "hevc min qp", min_qp)?; + + let max_qp = VideoHEVCMaxQp(tunings.max_quality.clamp(1, 51) as i32); + Self::apply_ctrl(device, "hevc max qp", max_qp)?; + + Ok(()) + } +} + +impl V4L2H265Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + match config.pred_structure { + PredictionStructure::LowDelay { limit } => { + let limit = limit as i32; + + Self::apply_ctrl(&device, "gop size", VideoGopSize(limit))?; + } + } + + Self::apply_ctrl(&device, "prepend SPS PPS to IDR", VideoPrependSpsPpsToIdr(true))?; + + let profile = match config.profile { + Profile::Main => VideoHEVCProfile::Main, + Profile::Main10 => VideoHEVCProfile::Main10, + Profile::MainStill => VideoHEVCProfile::MainStill, + + _ => { + log::error!("Unrecognized h265 profile for v4l2 backend: {:?}", config.profile); + return Err(InitializationError::Unsupported(UnsupportedError::Profile)); + } + }; + + Self::apply_ctrl(&device, "h265 profile", profile)?; + + Self::apply_ctrl(&device, "h265 level", VideoHEVCLevel::from(config.level))?; + + Self::create( + device, + capture_buffers, + fourcc, + coded_size, + config.resolution, + PIXEL_FORMAT_HEVC, + tunings, + ) + } +} + +impl V4L2StatefulH265Encoder +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + Ok(Self::create( + tunings.clone(), + V4L2H265Backend::new(device, capture_buffers, config, fourcc, coded_size, tunings)?, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::path::PathBuf; + use std::sync::Arc; + + use v4l2r::device::Device; + use v4l2r::device::DeviceConfig; + + use crate::backend::v4l2::encoder::find_device_with_capture; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_dmabuf_test; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_mmap_test; + use crate::backend::v4l2::encoder::tests::BoPoolAllocator; + use crate::backend::v4l2::encoder::tests::GbmDevice; + use crate::backend::v4l2::encoder::v4l2_format_to_frame_layout; + use crate::backend::v4l2::encoder::MmapingCapture; + use crate::encoder::simple_encode_loop; + use crate::encoder::tests::userptr_test_frame_generator; + use crate::encoder::RateControl; + use crate::utils::DmabufFrame; + use crate::Resolution; + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_userptr() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_HEVC).expect("no H265 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let mut encoder = V4L2StatefulH265Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + let layout = v4l2_format_to_frame_layout(&format); + + let mut bitstream = Vec::new(); + let buffer_size = + format.plane_fmt.iter().map(|plane| plane.sizeimage).max().unwrap() as usize; + let mut frame_producer = userptr_test_frame_generator(FRAME_COUNT, layout, buffer_size); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + bitstream.extend(coded.bitstream) + }) + .expect("encode loop"); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_userptr.h265").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_mmap() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_HEVC).expect("no H265 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let encoder = V4L2StatefulH265Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + perform_v4l2_encoder_mmap_test(FRAME_COUNT, encoder, |coded| { + bitstream.extend(coded.bitstream) + }); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_mmap.h265").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_dmabuf() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_HEVC).expect("no H265 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let gbm = GbmDevice::open(PathBuf::from("/dev/dri/renderD128")) + .and_then(gbm::Device::new) + .expect("failed to create GBM device"); + + let gbm = Arc::new(gbm); + + let encoder = V4L2StatefulH265Encoder::::new( + device.clone(), + BoPoolAllocator::new(gbm.clone()), + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NV12"), + CODED_SIZE, + Tunings { + framerate: 30, + rate_control: RateControl::ConstantBitrate(400_000), + ..Default::default() + }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + perform_v4l2_encoder_dmabuf_test( + CODED_SIZE, + VISIBLE_SIZE, + FRAME_COUNT, + gbm, + encoder, + |coded| bitstream.extend(coded.bitstream), + ); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_dmabuf.h265").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateful/vp8.rs b/vendor/cros-codecs/src/encoder/stateful/vp8.rs new file mode 100644 index 0000000..e82a330 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/vp8.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +pub mod v4l2; diff --git a/vendor/cros-codecs/src/encoder/stateful/vp8/v4l2.rs b/vendor/cros-codecs/src/encoder/stateful/vp8/v4l2.rs new file mode 100644 index 0000000..e451b75 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/vp8/v4l2.rs @@ -0,0 +1,332 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::sync::Arc; + +use v4l2r::controls::codec::VideoGopSize; +use v4l2r::controls::codec::VideoVP8Profile; +use v4l2r::controls::codec::VideoVPXMaxQp; +use v4l2r::controls::codec::VideoVPXMinQp; +use v4l2r::device::Device; + +use crate::backend::v4l2::encoder::CaptureBuffers; +use crate::backend::v4l2::encoder::ControlError; +use crate::backend::v4l2::encoder::EncoderCodec; +use crate::backend::v4l2::encoder::InitializationError; +use crate::backend::v4l2::encoder::OutputBufferHandle; +use crate::backend::v4l2::encoder::V4L2Backend; +use crate::encoder::stateful::StatefulEncoder; +use crate::encoder::vp8::EncoderConfig; +use crate::encoder::vp8::VP8; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Fourcc; +use crate::Resolution; + +const PIXEL_FORMAT_VP8: v4l2r::PixelFormat = v4l2r::PixelFormat::from_fourcc(b"VP80"); + +pub type V4L2VP8Backend = V4L2Backend; + +pub type V4L2StatefulVP8Encoder = + StatefulEncoder>; + +impl EncoderCodec for V4L2VP8Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError> { + let min_qp = VideoVPXMinQp(tunings.min_quality.clamp(0, 127) as i32); + Self::apply_ctrl(device, "vpx min qp", min_qp)?; + + let max_qp = VideoVPXMaxQp(tunings.max_quality.clamp(0, 127) as i32); + Self::apply_ctrl(device, "vpx max qp", max_qp)?; + + Ok(()) + } +} + +impl V4L2VP8Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + match config.pred_structure { + PredictionStructure::LowDelay { limit } => { + let limit = limit as i32; + + Self::apply_ctrl(&device, "gop size", VideoGopSize(limit))?; + } + } + + // TODO: allow picking profile + Self::apply_ctrl(&device, "vp8 profile", VideoVP8Profile::Profile0)?; + + Self::create( + device, + capture_buffers, + fourcc, + coded_size, + config.resolution, + PIXEL_FORMAT_VP8, + tunings, + ) + } +} + +impl V4L2StatefulVP8Encoder +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + Ok(Self::create( + tunings.clone(), + V4L2VP8Backend::new(device, capture_buffers, config, fourcc, coded_size, tunings)?, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::path::PathBuf; + use std::sync::Arc; + + use v4l2r::device::Device; + use v4l2r::device::DeviceConfig; + + use crate::backend::v4l2::encoder::find_device_with_capture; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_dmabuf_test; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_mmap_test; + use crate::backend::v4l2::encoder::tests::BoPoolAllocator; + use crate::backend::v4l2::encoder::tests::GbmDevice; + use crate::backend::v4l2::encoder::v4l2_format_to_frame_layout; + use crate::backend::v4l2::encoder::MmapingCapture; + use crate::bitstream_utils::IvfFileHeader; + use crate::bitstream_utils::IvfFrameHeader; + use crate::encoder::simple_encode_loop; + use crate::encoder::tests::userptr_test_frame_generator; + use crate::encoder::RateControl; + use crate::utils::DmabufFrame; + use crate::Resolution; + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_userptr() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP8).expect("no VP8 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let mut encoder = V4L2StatefulVP8Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + let layout = v4l2_format_to_frame_layout(&format); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP8, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + let buffer_size = + format.plane_fmt.iter().map(|plane| plane.sizeimage).max().unwrap() as usize; + let mut frame_producer = userptr_test_frame_generator(FRAME_COUNT, layout, buffer_size); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + // Skip Duck IVF frame header from v4l2 stream, and replace with ours with correct + // timestamp. + let frame_bitstream = &coded.bitstream[4 + 8..]; + + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: frame_bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(frame_bitstream); + }) + .expect("encode loop"); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_userptr.vp8.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_mmap() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP8).expect("no VP8 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let encoder = V4L2StatefulVP8Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(2_000_000), ..Default::default() }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP8, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + perform_v4l2_encoder_mmap_test(FRAME_COUNT, encoder, |coded| { + // Skip Duck IVF frame header from v4l2 stream, and replace with ours with correct + // timestamp. + let frame_bitstream = &coded.bitstream[4 + 8..]; + + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: frame_bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(frame_bitstream); + }); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_mmap.vp8.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_dmabuf() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP8).expect("no VP8 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let gbm = GbmDevice::open(PathBuf::from("/dev/dri/renderD128")) + .and_then(gbm::Device::new) + .expect("failed to create GBM device"); + + let gbm = Arc::new(gbm); + + let encoder = V4L2StatefulVP8Encoder::::new( + device.clone(), + BoPoolAllocator::new(gbm.clone()), + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NV12"), + CODED_SIZE, + Tunings { + framerate: 30, + rate_control: RateControl::ConstantBitrate(400_000), + ..Default::default() + }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP8, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + perform_v4l2_encoder_dmabuf_test( + CODED_SIZE, + VISIBLE_SIZE, + FRAME_COUNT, + gbm, + encoder, + |coded| { + // Skip Duck IVF frame header from v4l2 stream, and replace with ours with correct + // timestamp. + let frame_bitstream = &coded.bitstream[4 + 8..]; + + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: frame_bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(frame_bitstream); + }, + ); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_dmabuf.vp8.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateful/vp9.rs b/vendor/cros-codecs/src/encoder/stateful/vp9.rs new file mode 100644 index 0000000..e82a330 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/vp9.rs @@ -0,0 +1,6 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(feature = "v4l2")] +pub mod v4l2; diff --git a/vendor/cros-codecs/src/encoder/stateful/vp9/v4l2.rs b/vendor/cros-codecs/src/encoder/stateful/vp9/v4l2.rs new file mode 100644 index 0000000..5f1b024 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateful/vp9/v4l2.rs @@ -0,0 +1,337 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::sync::Arc; + +use v4l2r::controls::codec::VideoGopSize; +use v4l2r::controls::codec::VideoVP9Profile; +use v4l2r::controls::codec::VideoVPXMaxQp; +use v4l2r::controls::codec::VideoVPXMinQp; +use v4l2r::device::Device; + +use crate::backend::v4l2::encoder::CaptureBuffers; +use crate::backend::v4l2::encoder::ControlError; +use crate::backend::v4l2::encoder::EncoderCodec; +use crate::backend::v4l2::encoder::InitializationError; +use crate::backend::v4l2::encoder::OutputBufferHandle; +use crate::backend::v4l2::encoder::V4L2Backend; +use crate::codec::vp9::parser::BitDepth; +use crate::codec::vp9::parser::Profile; +use crate::encoder::stateful::StatefulEncoder; +use crate::encoder::vp9::EncoderConfig; +use crate::encoder::vp9::VP9; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Fourcc; +use crate::Resolution; + +const PIXEL_FORMAT_VP9: v4l2r::PixelFormat = v4l2r::PixelFormat::from_fourcc(b"VP90"); + +pub type V4L2VP9Backend = V4L2Backend; + +pub type V4L2StatefulVP9Encoder = + StatefulEncoder>; + +impl From for VideoVP9Profile { + fn from(value: Profile) -> Self { + match value { + Profile::Profile0 => Self::Profile0, + Profile::Profile1 => Self::Profile1, + Profile::Profile2 => Self::Profile2, + Profile::Profile3 => Self::Profile3, + } + } +} + +impl EncoderCodec for V4L2VP9Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError> { + let min_qp = VideoVPXMinQp(tunings.min_quality.clamp(0, 255) as i32); + Self::apply_ctrl(device, "vpx min qp", min_qp)?; + + let max_qp = VideoVPXMaxQp(tunings.max_quality.clamp(0, 255) as i32); + Self::apply_ctrl(device, "vpx max qp", max_qp)?; + + Ok(()) + } +} + +impl V4L2VP9Backend +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + match config.pred_structure { + PredictionStructure::LowDelay { limit } => { + let limit = limit as i32; + + Self::apply_ctrl(&device, "gop size", VideoGopSize(limit))?; + } + } + + let profile = match config.bit_depth { + BitDepth::Depth8 => Profile::Profile0, + BitDepth::Depth10 | BitDepth::Depth12 => Profile::Profile2, + }; + + Self::apply_ctrl(&device, "vp9 profile", VideoVP9Profile::from(profile))?; + + Self::create( + device, + capture_buffers, + fourcc, + coded_size, + config.resolution, + PIXEL_FORMAT_VP9, + tunings, + ) + } +} + +impl V4L2StatefulVP9Encoder +where + Handle: OutputBufferHandle, + CaptureBufferz: CaptureBuffers, +{ + pub fn new( + device: Arc, + capture_buffers: CaptureBufferz, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + tunings: Tunings, + ) -> Result { + Ok(Self::create( + tunings.clone(), + V4L2VP9Backend::new(device, capture_buffers, config, fourcc, coded_size, tunings)?, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::path::PathBuf; + use std::sync::Arc; + + use v4l2r::device::Device; + use v4l2r::device::DeviceConfig; + + use crate::backend::v4l2::encoder::find_device_with_capture; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_dmabuf_test; + use crate::backend::v4l2::encoder::tests::perform_v4l2_encoder_mmap_test; + use crate::backend::v4l2::encoder::tests::BoPoolAllocator; + use crate::backend::v4l2::encoder::tests::GbmDevice; + use crate::backend::v4l2::encoder::v4l2_format_to_frame_layout; + use crate::backend::v4l2::encoder::MmapingCapture; + use crate::bitstream_utils::IvfFileHeader; + use crate::bitstream_utils::IvfFrameHeader; + use crate::encoder::simple_encode_loop; + use crate::encoder::tests::userptr_test_frame_generator; + use crate::encoder::RateControl; + use crate::utils::DmabufFrame; + use crate::Resolution; + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_userptr() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP9).expect("no VP8 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let mut encoder = V4L2StatefulVP9Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let format: v4l2r::Format = encoder.backend().output_format().unwrap(); + let layout = v4l2_format_to_frame_layout(&format); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP9, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + let buffer_size = + format.plane_fmt.iter().map(|plane| plane.sizeimage).max().unwrap() as usize; + let mut frame_producer = userptr_test_frame_generator(FRAME_COUNT, layout, buffer_size); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }) + .expect("encode loop"); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_userptr.vp9.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_mmap() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP9).expect("no VP9 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let encoder = V4L2StatefulVP9Encoder::new( + device, + MmapingCapture, + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NM12"), + CODED_SIZE, + Tunings { rate_control: RateControl::ConstantBitrate(400_000), ..Default::default() }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP9, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + perform_v4l2_encoder_mmap_test(FRAME_COUNT, encoder, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_mmap.vp9.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires v4l2m2m-compatible hardware. + #[test] + fn test_v4l2_encoder_dmabuf() { + const VISIBLE_SIZE: Resolution = Resolution { width: 500, height: 500 }; + const CODED_SIZE: Resolution = Resolution { width: 512, height: 512 }; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let device = find_device_with_capture(PIXEL_FORMAT_VP9).expect("no VP9 encoder found"); + let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf()).expect("open"); + let device = Arc::new(device); + + let gbm = GbmDevice::open(PathBuf::from("/dev/dri/renderD128")) + .and_then(gbm::Device::new) + .expect("failed to create GBM device"); + + let gbm = Arc::new(gbm); + + let encoder = V4L2StatefulVP9Encoder::::new( + device.clone(), + BoPoolAllocator::new(gbm.clone()), + EncoderConfig { resolution: VISIBLE_SIZE, ..Default::default() }, + Fourcc::from(b"NV12"), + CODED_SIZE, + Tunings { + framerate: 30, + rate_control: RateControl::ConstantBitrate(400_000), + ..Default::default() + }, + ) + .unwrap(); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP9, + VISIBLE_SIZE.width as u16, + VISIBLE_SIZE.height as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + perform_v4l2_encoder_dmabuf_test( + CODED_SIZE, + VISIBLE_SIZE, + FRAME_COUNT, + gbm, + encoder, + |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }, + ); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_v4l2_encoder_dmabuf.vp9.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless.rs b/vendor/cros-codecs/src/encoder/stateless.rs new file mode 100644 index 0000000..be9e87a --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless.rs @@ -0,0 +1,398 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::collections::VecDeque; + +use thiserror::Error; + +use crate::encoder::CodedBitstreamBuffer; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::Tunings; +use crate::encoder::VideoEncoder; +use crate::BlockingMode; + +#[cfg(feature = "vaapi")] +pub mod av1; +#[cfg(feature = "vaapi")] +pub mod h264; +#[cfg(feature = "vaapi")] +pub(crate) mod predictor; +#[cfg(feature = "vaapi")] +pub mod vp9; + +#[derive(Error, Debug)] +pub enum StatelessBackendError { + #[error("unsupported profile")] + UnsupportedProfile, + #[error("unsupported format")] + UnsupportedFormat, + #[error("not enough resources to proceed with the operation now")] + OutOfResources, + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +pub type StatelessBackendResult = Result; + +/// Trait for representing pending encoder output. +pub trait BackendPromise { + type Output; + + /// Return coded result of the processing. Blocks if processing is not finished yet. + fn sync(self) -> StatelessBackendResult; + + /// Return true whenever the underlaying processing is done + fn is_ready(&self) -> bool; +} + +pub struct ReadyPromise(T); + +impl From for ReadyPromise { + fn from(value: T) -> Self { + ReadyPromise(value) + } +} + +impl BackendPromise for ReadyPromise { + type Output = T; + + fn sync(self) -> StatelessBackendResult { + Ok(self.0) + } + + fn is_ready(&self) -> bool { + true + } +} + +/// Wrapper type for [`BackendPromise>`], with additional +/// metadata. +pub struct BitstreamPromise

+where + P: BackendPromise>, +{ + /// Slice data and reconstructed surface promise + bitstream: P, + + /// Input frame metadata, for [`CodedBitstreamBuffer`] + meta: FrameMetadata, +} + +impl

BackendPromise for BitstreamPromise

+where + P: BackendPromise>, +{ + type Output = CodedBitstreamBuffer; + + fn is_ready(&self) -> bool { + self.bitstream.is_ready() + } + + fn sync(self) -> StatelessBackendResult { + let coded_data = self.bitstream.sync()?; + + log::trace!("synced bitstream size={}", coded_data.len()); + + Ok(CodedBitstreamBuffer::new(self.meta, coded_data)) + } +} + +/// Internal structure representing all current processing represented using promises and allowing +/// polling for finished promises. +pub(crate) struct OutputQueue +where + O: BackendPromise, +{ + /// True if the every single polling call shall be blocking + blocking: BlockingMode, + + /// Queue of currently pending [`BackendPromise`] + promises: VecDeque, +} + +impl OutputQueue +where + O: BackendPromise, +{ + #[allow(dead_code)] + pub(crate) fn new(blocking: BlockingMode) -> Self { + Self { blocking, promises: Default::default() } + } + + /// Add new pending job to the queue. Which will be returned to client if it is done. + #[allow(dead_code)] + pub(crate) fn add_promise(&mut self, pending: O) { + self.promises.push_back(pending); + } + + /// Returns the result of an oldest [`BackendPromise`] if it is done processing. If `force_block` + /// is true, then the function will block till processing of the oldest [`BackendPromise`] is + /// finished and return it's result. + pub(crate) fn poll(&mut self, mode: BlockingMode) -> StatelessBackendResult> { + let block = self.blocking == BlockingMode::Blocking || mode == BlockingMode::Blocking; + + match self.promises.pop_front() { + Some(o) if block || o.is_ready() => Ok(Some(o.sync()?)), + Some(o) => { + self.promises.push_front(o); + Ok(None) + } + None => Ok(None), + } + } + + /// Returns true if queue is empty ie. no [`BackendPromise`] is pending. + pub(crate) fn is_empty(&self) -> bool { + self.promises.is_empty() + } +} + +/// Predictor is responsible for yielding stream parameter sets and creating requests to backend. +/// It accepts the frames and reconstructed frames and returns [`Request`]s for execution. For +/// example [`Predictor`] may hold frames from processing until enough is supplied to create a +/// specific prediction structure. [`Predictor::drain`] may be called to force predictor to +/// yield requests. +pub(super) trait Predictor { + /// Called by encoder when there is new frame to encode. The predictor may return empty vector + /// to postpone processing or a set of requests to process frames (it does not have to be a frame + /// specified in parameters) + fn new_frame( + &mut self, + backend_pic: Picture, + meta: FrameMetadata, + ) -> EncodeResult>; + + /// This function is called by the encoder, with reconstructed frame when backend finished + /// processing the frame. the [`Predictor`] may choose to return [`Request`]s to submit to + /// backend, if reconstructed was required for creating that request. + fn reconstructed(&mut self, recon: Reference) -> EncodeResult>; + + /// Requests the change of dynamic parameters (aka [`Tunings`]) for the stream. The predictor + /// may choose to delay the change until entire or some part of the structure had been encoded. + /// However in such case the predictor is responsible for ensuring the change will be + /// successful. + fn tune(&mut self, tunings: Tunings) -> EncodeResult<()>; + + /// Force [`Predictor`] to pop at least one frame from internal queue and return a [`Request`]s + fn drain(&mut self) -> EncodeResult>; +} + +/// Generic trait for stateless encoder backends +pub trait StatelessVideoEncoderBackend: Sized +where + Codec: StatelessCodec, +{ + /// Backend's specific representation of the input frame, transformed with [`import_picture`]. + /// Might be a wrapper of the input handle with additional backend specific data or a copy of + /// an input frame in internal backend's representation. + /// + /// [`import_picture`]: StatelessEncoderBackendImport::import_picture + type Picture: 'static; + + /// Backend's reconstructed frame handle. + type Reconstructed: 'static; + + /// Backend's specific [`BackendPromise`] for bitstream, a result of + /// [`StatelessCodec::Request`] submission. + type CodedPromise: BackendPromise>; + + /// Backend's specific [`BackendPromise`] for [`StatelessVideoEncoderBackend::Reconstructed`], + /// a result of [`StatelessCodec::Request`] submission. + type ReconPromise: BackendPromise; +} + +pub trait StatelessEncoderBackendImport { + /// Imports the input `handle` from client and transforms into `Picture` + fn import_picture( + &mut self, + metadata: &FrameMetadata, + handle: Handle, + ) -> StatelessBackendResult; +} + +/// Trait helping contain all codec specific and backend specific types +pub trait StatelessCodec: Sized +where + Backend: StatelessVideoEncoderBackend, +{ + /// Codec specific representation of frame reference wrapping a backend reference type + /// containing a codec specific frame metadata + type Reference; + + /// A request type that will be delivered to codec specific stateless encoder backend + type Request; + + /// Codec specific [`BackendPromise`] for [`CodedBitstreamBuffer`] wrapping a backend specific + /// [`StatelessVideoEncoderBackend::CodedPromise`] + type CodedPromise: BackendPromise; + + /// Codec specific [`BackendPromise`] for [`StatelessCodec::Reference`] wrapping a + /// backend speficic [`StatelessVideoEncoderBackend::ReconPromise`] + type ReferencePromise: BackendPromise; +} + +/// Helper aliases for codec and backend specific types +type Picture = >::Picture; + +type Reference = >::Reference; + +type Request = >::Request; + +type CodedPromise = >::CodedPromise; + +type ReferencePromise = >::ReferencePromise; + +type BoxPredictor = Box, Reference, Request>>; + +pub struct StatelessEncoder +where + Backend: StatelessVideoEncoderBackend, + Codec: StatelessCodec, +{ + /// Pending frame output promise queue + output_queue: OutputQueue>, + + /// Pending reconstructed pictures promise queue + recon_queue: OutputQueue>, + + /// [`Predictor`] instance responsible for the encoder decision making + predictor: BoxPredictor, + + // predictor: Box>, + coded_queue: VecDeque, + + /// Number of the currently held frames by the predictor + predictor_frame_count: usize, + + /// [`StatelessVideoEncoderBackend`] instance to delegate work to + backend: Backend, + + _phantom: std::marker::PhantomData, +} + +/// A bridge trait between [`StatelessEncoder`] and codec specific backend trait (eg. +/// [`h264::StatelessH264EncoderBackend`] or [`vp9::StatelessVP9EncoderBackend`]). Accepts +/// `Request` and is responsible for adding resutling [`BackendPromise`] to [`StatelessEncoder`] +/// internal queues and decrementing the internal predictor frame counter if the backend moved the +/// frame outside predictor ownership. +pub trait StatelessEncoderExecute +where + Backend: StatelessVideoEncoderBackend, + Codec: StatelessCodec, +{ + fn execute(&mut self, request: Request) -> EncodeResult<()>; +} + +impl StatelessEncoder +where + Codec: StatelessCodec, + Backend: StatelessVideoEncoderBackend, + Self: StatelessEncoderExecute, +{ + #[allow(dead_code)] + fn new( + backend: Backend, + mode: BlockingMode, + predictor: BoxPredictor, + ) -> EncodeResult { + Ok(Self { + backend, + predictor, + predictor_frame_count: 0, + coded_queue: Default::default(), + output_queue: OutputQueue::new(mode), + recon_queue: OutputQueue::new(mode), + _phantom: Default::default(), + }) + } + + fn poll_pending(&mut self, mode: BlockingMode) -> EncodeResult<()> { + // Poll the output queue once and then continue polling while new promise is submitted + while let Some(coded) = self.output_queue.poll(mode)? { + self.coded_queue.push_back(coded); + } + + while let Some(recon) = self.recon_queue.poll(mode)? { + let requests = self.predictor.reconstructed(recon)?; + if requests.is_empty() { + // No promise was submitted, therefore break + break; + } + + for request in requests { + self.execute(request)?; + } + } + + Ok(()) + } +} + +impl VideoEncoder for StatelessEncoder +where + Codec: StatelessCodec, + Backend: StatelessVideoEncoderBackend, + Backend: StatelessEncoderBackendImport, + Self: StatelessEncoderExecute, +{ + fn tune(&mut self, tunings: Tunings) -> EncodeResult<()> { + self.predictor.tune(tunings) + } + + fn encode(&mut self, metadata: FrameMetadata, handle: Handle) -> EncodeResult<()> { + log::trace!("encode: timestamp={} layout={:?}", metadata.timestamp, metadata.layout); + + // Import `handle` to backends representation + let backend_pic = self.backend.import_picture(&metadata, handle)?; + + // Increase the number of frames that predictor holds, before handing one to it + self.predictor_frame_count += 1; + + // Ask predictor to decide on the next move and execute it + let requests = self.predictor.new_frame(backend_pic, metadata)?; + for request in requests { + self.execute(request)?; + } + + Ok(()) + } + + fn drain(&mut self) -> EncodeResult<()> { + log::trace!("currently predictor holds {}", self.predictor_frame_count); + + // Drain the predictor + while self.predictor_frame_count > 0 || !self.recon_queue.is_empty() { + if self.output_queue.is_empty() && self.recon_queue.is_empty() { + // The OutputQueue is empty and predictor holds frames, force it to yield a request + // to empty it's internal queue. + let requests = self.predictor.drain()?; + if requests.is_empty() { + log::error!("failed to drain predictor, no request was returned"); + return Err(EncodeError::InvalidInternalState); + } + + for request in requests { + self.execute(request)?; + } + } + + self.poll_pending(BlockingMode::Blocking)?; + } + + // There are still some requests being processed. Continue on polling them. + while !self.output_queue.is_empty() { + self.poll_pending(BlockingMode::Blocking)?; + } + + Ok(()) + } + + fn poll(&mut self) -> EncodeResult> { + // Poll on output queue without blocking and try to dueue from coded queue + self.poll_pending(BlockingMode::NonBlocking)?; + Ok(self.coded_queue.pop_front()) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/av1.rs b/vendor/cros-codecs/src/encoder/stateless/av1.rs new file mode 100644 index 0000000..34a295e --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/av1.rs @@ -0,0 +1,133 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::ReferenceFrameType; +use crate::codec::av1::parser::SequenceHeaderObu; +use crate::codec::av1::parser::REFS_PER_FRAME; +use crate::encoder::av1::EncoderConfig; +use crate::encoder::av1::AV1; +use crate::encoder::stateless::av1::predictor::LowDelayAV1; +use crate::encoder::stateless::BitstreamPromise; +use crate::encoder::stateless::Predictor; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessCodec; +use crate::encoder::stateless::StatelessEncoderExecute; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::BlockingMode; + +mod predictor; + +#[cfg(feature = "vaapi")] +pub mod vaapi; + +pub struct BackendRequest { + /// Current sequence's header OBU + sequence: SequenceHeaderObu, + + /// Current frame OBU contains + frame: FrameHeaderObu, + + /// Input frame to be encoded + input: P, + + /// Input frame metadata + input_meta: FrameMetadata, + + /// References for the frame to be encoded + /// Use `ReferenceFrameType::Golden - ReferenceFrameType::Last` for indexing + references: [Option>; REFS_PER_FRAME], + + /// The reference frame search priority list. From highest to lowest + /// Use [`ReferenceFrameType::Intra`] for invalid + ref_frame_ctrl_l0: [ReferenceFrameType; REFS_PER_FRAME], + ref_frame_ctrl_l1: [ReferenceFrameType; REFS_PER_FRAME], + + /// Period between intra frames + intra_period: u32, + + /// Period between intra frame and P frame + ip_period: u32, + + /// [`Tunings`] for the frame + tunings: Tunings, + + /// Container for the request output. [`StatelessAV1EncoderBackend`] impl shall move it and + /// append the slice data to it. This prevents unnecessary copying of bitstream around. + coded_output: Vec, +} + +impl StatelessCodec for AV1 +where + Backend: StatelessVideoEncoderBackend, +{ + type Reference = Backend::Reconstructed; + + type Request = BackendRequest; + + type CodedPromise = BitstreamPromise; + + type ReferencePromise = Backend::ReconPromise; +} + +/// Trait for stateless encoder backend for H.264 +pub trait StatelessAV1EncoderBackend: StatelessVideoEncoderBackend { + /// Submit a [`BackendRequest`] to the backend. This operation returns both a + /// [`StatelessVideoEncoderBackend::ReconPromise`] and a + /// [`StatelessVideoEncoderBackend::CodedPromise`] with resulting slice data. + fn encode_tile_group( + &mut self, + request: BackendRequest, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)>; +} + +pub type StatelessEncoder = + crate::encoder::stateless::StatelessEncoder; + +impl StatelessEncoderExecute + for StatelessEncoder +where + Backend: StatelessAV1EncoderBackend, +{ + fn execute( + &mut self, + request: BackendRequest, + ) -> EncodeResult<()> { + let meta = request.input_meta.clone(); + + // The [`BackendRequest`] has a frame from predictor. Decresing internal counter. + self.predictor_frame_count -= 1; + + log::trace!("submitting new request"); + let (recon, bitstream) = self.backend.encode_tile_group(request)?; + + // Wrap promise from backend with headers and metadata + let tilegroup_promise = BitstreamPromise { bitstream, meta }; + + self.output_queue.add_promise(tilegroup_promise); + + self.recon_queue.add_promise(recon); + + Ok(()) + } +} + +impl StatelessEncoder +where + Backend: StatelessAV1EncoderBackend, +{ + fn new_av1(backend: Backend, config: EncoderConfig, mode: BlockingMode) -> EncodeResult { + let predictor: Box> = match config.pred_structure { + PredictionStructure::LowDelay { limit } => Box::new(LowDelayAV1::new(config, limit)), + }; + + Self::new(backend, mode, predictor) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/av1/predictor.rs b/vendor/cros-codecs/src/encoder/stateless/av1/predictor.rs new file mode 100644 index 0000000..7ed2429 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/av1/predictor.rs @@ -0,0 +1,326 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::codec::av1::parser::BitDepth; +use crate::codec::av1::parser::CdefParams; +use crate::codec::av1::parser::ColorConfig; +use crate::codec::av1::parser::FrameHeaderObu; +use crate::codec::av1::parser::FrameType; +use crate::codec::av1::parser::ObuHeader; +use crate::codec::av1::parser::ObuType; +use crate::codec::av1::parser::OperatingPoint; +use crate::codec::av1::parser::Profile; +use crate::codec::av1::parser::QuantizationParams; +use crate::codec::av1::parser::ReferenceFrameType; +use crate::codec::av1::parser::SequenceHeaderObu; +use crate::codec::av1::parser::TemporalDelimiterObu; +use crate::codec::av1::parser::TileInfo; +use crate::codec::av1::parser::TxMode; +use crate::codec::av1::parser::MAX_NUM_OPERATING_POINTS; +use crate::codec::av1::parser::MAX_TILE_COLS; +use crate::codec::av1::parser::MAX_TILE_ROWS; +use crate::codec::av1::parser::PRIMARY_REF_NONE; +use crate::codec::av1::parser::REFS_PER_FRAME; +use crate::codec::av1::parser::SELECT_INTEGER_MV; +use crate::codec::av1::parser::SUPERRES_NUM; +use crate::codec::av1::synthesizer::Synthesizer; +use crate::encoder::stateless::av1::BackendRequest; +use crate::encoder::stateless::av1::EncoderConfig; +use crate::encoder::stateless::predictor::LowDelay; +use crate::encoder::stateless::predictor::LowDelayDelegate; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::Tunings; + +// AV1 Spec. Dc_Qlookup max indices +pub(crate) const MIN_BASE_QINDEX: u32 = 0; +pub(crate) const MAX_BASE_QINDEX: u32 = 255; + +pub(crate) struct LowDelayAV1Delegate { + /// Current sequence header obu + sequence: SequenceHeaderObu, + + /// Encoder config + config: EncoderConfig, +} + +pub(crate) type LowDelayAV1 = + LowDelay>; + +impl LowDelayAV1 { + pub fn new(config: EncoderConfig, limit: u16) -> Self { + Self { + queue: Default::default(), + references: Default::default(), + counter: 0, + limit, + tunings: config.initial_tunings.clone(), + delegate: LowDelayAV1Delegate { + sequence: Self::create_sequence_header(&config), + config, + }, + tunings_queue: Default::default(), + _phantom: Default::default(), + } + } + + fn create_sequence_header(config: &EncoderConfig) -> SequenceHeaderObu { + let width = config.resolution.width; + let height = config.resolution.height; + + SequenceHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::SequenceHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + seq_profile: Profile::Profile0, + num_planes: 3, + + enable_order_hint: true, + order_hint_bits: 8, + order_hint_bits_minus_1: 8 - 1, + + // Use maximum size (16 bits) + frame_width_bits_minus_1: (1 << 4) - 1, + frame_height_bits_minus_1: (1 << 4) - 1, + + // Current resolution is the maximum resolution + max_frame_width_minus_1: (width - 1) as u16, + max_frame_height_minus_1: (height - 1) as u16, + + seq_force_integer_mv: SELECT_INTEGER_MV as u32, + + operating_points: { + let mut ops: [OperatingPoint; MAX_NUM_OPERATING_POINTS] = Default::default(); + ops[0].idc = 0; + // Use highest level 23 for now. + // TODO(bgrzesik): approximate level base on resolution and framerate + ops[0].seq_level_idx = 23; + ops + }, + + bit_depth: config.bit_depth, + color_config: ColorConfig { + // YUV 4:2:0 8-bit or 10-bit + high_bitdepth: config.bit_depth == BitDepth::Depth10, + mono_chrome: false, + subsampling_x: true, + subsampling_y: true, + ..Default::default() + }, + + ..Default::default() + } + } + + fn create_temporal_delimiter() -> TemporalDelimiterObu { + TemporalDelimiterObu { + obu_header: ObuHeader { + obu_type: ObuType::TemporalDelimiter, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + } + } + + fn create_frame_header(&self, frame_type: FrameType) -> EncodeResult { + let width = self.delegate.config.resolution.width; + let height = self.delegate.config.resolution.height; + + // Superblock size + let sb_size = if self.delegate.sequence.use_128x128_superblock { 128 } else { 64 }; + + // Use frame counter for order hinting + let order_hint_mask = (1 << self.delegate.sequence.order_hint_bits) - 1; + let order_hint = (self.counter & order_hint_mask) as u32; + + let RateControl::ConstantQuality(base_q_idx) = self.tunings.rate_control else { + return Err(EncodeError::Unsupported); + }; + + // Clamp tunings's quaility range to correct range + let min_q_idx = self.tunings.min_quality.max(MIN_BASE_QINDEX); + let max_q_idx = self.tunings.max_quality.min(MAX_BASE_QINDEX); + + // Clamp Q index + let base_q_idx = base_q_idx.clamp(min_q_idx, max_q_idx); + + // Set the frame size in superblocks for the only tile + let mut width_in_sbs_minus_1 = [0u32; MAX_TILE_COLS]; + width_in_sbs_minus_1[0] = ((width + sb_size - 1) / sb_size) - 1; + + let mut height_in_sbs_minus_1 = [0u32; MAX_TILE_ROWS]; + height_in_sbs_minus_1[0] = ((height + sb_size - 1) / sb_size) - 1; + + Ok(FrameHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::FrameHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + show_frame: true, + showable_frame: !matches!(frame_type, FrameType::KeyFrame), + frame_type, + frame_is_intra: matches!(frame_type, FrameType::KeyFrame | FrameType::IntraOnlyFrame), + primary_ref_frame: PRIMARY_REF_NONE, + refresh_frame_flags: if matches!(frame_type, FrameType::KeyFrame) { + 0xff + } else { + 0x01 + }, + + // Use error resilient mode, and provide the order hints for referencing frame ie. just + // previous frame + error_resilient_mode: true, + order_hint, + ref_order_hint: [0, 0, 0, 0, 0, 0, 0, 0], + + reduced_tx_set: true, + tx_mode_select: 1, + tx_mode: TxMode::Select, + + // Provide the Q index from config + quantization_params: QuantizationParams { base_q_idx, ..Default::default() }, + + // Use single tile for now + tile_info: TileInfo { + uniform_tile_spacing_flag: true, + tile_cols: 1, + tile_rows: 1, + tile_cols_log2: 0, + tile_rows_log2: 0, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + ..Default::default() + }, + + // CDEF is not used currently, use default value to keep Synthesizer happy + cdef_params: CdefParams { cdef_damping: 3, ..Default::default() }, + + // No superres + superres_denom: SUPERRES_NUM as u32, + upscaled_width: width, + frame_width: width, + frame_height: height, + render_width: width, + render_height: height, + + ..Default::default() + }) + } +} + +impl LowDelayDelegate> + for LowDelayAV1 +{ + fn request_keyframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + idr: bool, + ) -> EncodeResult> { + log::trace!("Requested keyframe timestamp={}", input_meta.timestamp); + + let temporal_delim = Self::create_temporal_delimiter(); + let sequence = self.delegate.sequence.clone(); + let frame = self.create_frame_header(FrameType::KeyFrame)?; + + // This is intra frame, so there is no references + let references = [None, None, None, None, None, None, None]; + let ref_frame_ctrl_l0 = [ReferenceFrameType::Intra; REFS_PER_FRAME]; + let ref_frame_ctrl_l1 = [ReferenceFrameType::Intra; REFS_PER_FRAME]; + + let mut coded_output = Vec::new(); + + // Output Temporal Delimiter, Sequence Header and Frame Header OBUs to bitstream + Synthesizer::<'_, TemporalDelimiterObu, _>::synthesize(&temporal_delim, &mut coded_output)?; + if idr { + Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&sequence, &mut coded_output)?; + } + Synthesizer::<'_, FrameHeaderObu, _>::synthesize(&frame, &sequence, &mut coded_output)?; + + let request = BackendRequest { + sequence, + frame, + input, + input_meta, + references, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + intra_period: self.limit as u32, + ip_period: 1, + tunings: self.tunings.clone(), + coded_output, + }; + + Ok(request) + } + + fn request_interframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + ) -> EncodeResult> { + log::trace!("Requested interframe timestamp={}", input_meta.timestamp); + + let temporal_delim = Self::create_temporal_delimiter(); + let sequence = self.delegate.sequence.clone(); + let mut frame = self.create_frame_header(FrameType::InterFrame)?; + + // Use previous frame as last frame reference + let references = [self.references.front().cloned(), None, None, None, None, None, None]; + + let order_hint_mask = (1 << self.delegate.sequence.order_hint_bits) - 1; + let mut ref_frame_ctrl_l0 = [ReferenceFrameType::Intra; REFS_PER_FRAME]; + let ref_frame_ctrl_l1 = [ReferenceFrameType::Intra; REFS_PER_FRAME]; + + // Enable previous frame as reference + ref_frame_ctrl_l0[0] = ReferenceFrameType::Last; + frame.ref_frame_idx[0] = 0; + frame.last_frame_idx = 0; + frame.ref_order_hint[0] = ((self.counter - 1) & order_hint_mask) as u32; + + let mut coded_output = Vec::new(); + + // Output Temporal Delimiter and Frame Header OBUs to bitstream, marking next frame + Synthesizer::<'_, TemporalDelimiterObu, _>::synthesize(&temporal_delim, &mut coded_output)?; + Synthesizer::<'_, FrameHeaderObu, _>::synthesize(&frame, &sequence, &mut coded_output)?; + + let request = BackendRequest { + sequence, + frame, + input, + input_meta, + references, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + intra_period: self.limit as u32, + ip_period: 1, + tunings: self.tunings.clone(), + coded_output, + }; + + self.references.clear(); + + Ok(request) + } + + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } + + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/av1/vaapi.rs b/vendor/cros-codecs/src/encoder/stateless/av1/vaapi.rs new file mode 100644 index 0000000..9449fb7 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/av1/vaapi.rs @@ -0,0 +1,1009 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::num::TryFromIntError; +use std::rc::Rc; + +use libva::AV1EncLoopFilterFlags; +use libva::AV1EncLoopRestorationFlags; +use libva::AV1EncModeControlFlags; +use libva::AV1EncPictureFlags; +use libva::AV1EncQMatrixFlags; +use libva::AV1EncSeqFields; +use libva::AV1EncTileGroupObuHdrInfo; +use libva::EncCodedBuffer; +use libva::EncPictureParameterBufferAV1; +use libva::EncSegParamAV1; +use libva::EncSegParamFlagsAV1; +use libva::EncSequenceParameterBufferAV1; +use libva::EncTileGroupBufferAV1; +use libva::Picture; +use libva::RefFrameCtrlAV1; +use libva::Surface; +use libva::SurfaceMemoryDescriptor; +use libva::VAProfile::VAProfileAV1Profile0; +use libva::VAProfile::VAProfileAV1Profile1; +use libva::VaError; +use libva::VA_INVALID_ID; + +use crate::backend::vaapi::encoder::CodedOutputPromise; +use crate::backend::vaapi::encoder::Reconstructed; +use crate::backend::vaapi::encoder::VaapiBackend; +use crate::codec::av1::parser::Profile; +use crate::codec::av1::parser::ReferenceFrameType; +use crate::codec::av1::parser::CDEF_MAX; +use crate::codec::av1::parser::MAX_SEGMENTS; +use crate::codec::av1::parser::MAX_TILE_COLS; +use crate::codec::av1::parser::MAX_TILE_ROWS; +use crate::codec::av1::parser::REFS_PER_FRAME; +use crate::codec::av1::parser::SEG_LVL_MAX; +use crate::encoder::av1::EncoderConfig; +use crate::encoder::av1::AV1; +use crate::encoder::stateless::av1::predictor::MAX_BASE_QINDEX; +use crate::encoder::stateless::av1::predictor::MIN_BASE_QINDEX; +use crate::encoder::stateless::av1::BackendRequest; +use crate::encoder::stateless::av1::StatelessAV1EncoderBackend; +use crate::encoder::stateless::ReadyPromise; +use crate::encoder::stateless::StatelessBackendError; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessEncoder; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::RateControl; +use crate::video_frame::VideoFrame; +use crate::BlockingMode; +use crate::Fourcc; +use crate::Resolution; + +type Request = BackendRequest; + +#[derive(thiserror::Error, Debug)] +pub enum BackendError { + #[error(transparent)] + ConversionError(#[from] TryFromIntError), + + #[error("vaBeginPicture failed: {0}")] + BeginPictureError(VaError), + #[error("vaRenderPicture failed: {0}")] + RenderPictureError(VaError), + #[error("vaRenderPicture failed: {0}")] + EndPictureError(VaError), +} + +impl From for StatelessBackendError { + fn from(value: BackendError) -> Self { + StatelessBackendError::Other(anyhow::anyhow!(value)) + } +} + +type Result = std::result::Result; + +impl StatelessVideoEncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + Handle: std::borrow::Borrow>, +{ + type Picture = Handle; + type Reconstructed = Reconstructed; + type CodedPromise = CodedOutputPromise; + type ReconPromise = ReadyPromise; +} + +impl VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow> + 'static, +{ + fn build_seq_param(request: &Request) -> Result { + assert!( + request.sequence.operating_points_cnt_minus_1 == 0, + "Only a single operating point is supported for now" + ); + const OPERATING_POINT: usize = 0; + + let seq_profile = request.sequence.seq_profile as u8; + let seq_level_idx = request.sequence.operating_points[OPERATING_POINT].seq_level_idx; + let seq_tier = request.sequence.operating_points[OPERATING_POINT].seq_tier; + let hierarchical_flag = 0; + + // TODO: Enable bitrate control + let bits_per_second = 0; + + // AV1 5.5.2 + let bit_depth_minus8 = if request.sequence.seq_profile == Profile::Profile2 + && request.sequence.color_config.high_bitdepth + { + if request.sequence.color_config.twelve_bit { + 12 + } else { + 10 + } + } else if request.sequence.color_config.high_bitdepth { + 10 + } else { + 8 + }; + + let order_hint_bits_minus_1 = u8::try_from(request.sequence.order_hint_bits_minus_1)?; + + Ok(EncSequenceParameterBufferAV1::new( + seq_profile, + seq_level_idx, + seq_tier, + hierarchical_flag, + request.intra_period, + request.ip_period, + bits_per_second, + &AV1EncSeqFields::new( + request.sequence.still_picture, + request.sequence.use_128x128_superblock, + request.sequence.enable_filter_intra, + request.sequence.enable_intra_edge_filter, + request.sequence.enable_interintra_compound, + request.sequence.enable_masked_compound, + request.sequence.enable_warped_motion, + request.sequence.enable_dual_filter, + request.sequence.enable_order_hint, + request.sequence.enable_jnt_comp, + request.sequence.enable_ref_frame_mvs, + request.sequence.enable_superres, + request.sequence.enable_cdef, + request.sequence.enable_restoration, + bit_depth_minus8, + request.sequence.color_config.subsampling_x, + request.sequence.color_config.subsampling_y, + request.sequence.color_config.mono_chrome, + ), + order_hint_bits_minus_1, + )) + } + + fn build_ref_ctrl( + refs: &[Option>; REFS_PER_FRAME], + ctrl: &[ReferenceFrameType; REFS_PER_FRAME], + ) -> RefFrameCtrlAV1 { + let ctrl = ctrl.map(|type_| { + if type_ == ReferenceFrameType::Intra { + return 0; + } + + let idx = type_ as u32 - ReferenceFrameType::Last as u32; + if refs[idx as usize].is_none() { + return 0; + } + + type_ as u32 + }); + + RefFrameCtrlAV1::new(ctrl[0], ctrl[1], ctrl[2], ctrl[3], ctrl[4], ctrl[5], ctrl[6]) + } + + fn build_pic_param( + request: &Request, + recon: &Reconstructed, + coded: &EncCodedBuffer, + ) -> Result { + let coded_buf = coded.id(); + let reconstructed_frame = recon.surface_id(); + + let mut reference_frames = [VA_INVALID_ID; 8]; + + for (i, frame) in reference_frames.iter_mut().enumerate().take(REFS_PER_FRAME) { + let Some(ref_frame) = &request.references[i] else { + continue; + }; + + *frame = ref_frame.surface_id(); + } + + let mut ref_frame_idx = [0; 7]; + for (i, idx) in ref_frame_idx.iter_mut().enumerate() { + *idx = request.frame.ref_frame_idx[i]; + } + + let frame_width_minus_1 = u16::try_from(request.frame.frame_width - 1)?; + let frame_height_minus_1 = u16::try_from(request.frame.frame_height - 1)?; + + // Single temporal layer is used. + const HIERARCHICAL_LEVEL_PLUS1: u8 = 0; + + let primary_ref_frame = u8::try_from(request.frame.primary_ref_frame)?; + let order_hint = u8::try_from(request.frame.order_hint)?; + let refresh_frame_flags = u8::try_from(request.frame.refresh_frame_flags)?; + + let ref_frame_ctrl_l0 = + Self::build_ref_ctrl(&request.references, &request.ref_frame_ctrl_l0); + let ref_frame_ctrl_l1 = + Self::build_ref_ctrl(&request.references, &request.ref_frame_ctrl_l1); + + let frame_type = request.frame.frame_type as u32; + + // Export Frame Obu rather then TileGroup Obu + const ENABLE_FRAME_OBU: bool = false; + + // We don't use long term reference frames for now. + const LONG_TERM_REFERENCE: bool = false; + + // Current we always expect the reconstructed frame. + const DISABLE_FRAME_RECON: bool = false; + + // Palette mode is not used. This also implies force_integer_mv and + // allow_screen_content_tools should be false. + const PALETTE_MODE_ENABLE: bool = false; + const FORCE_INTEGER_MV: bool = false; + const ALLOW_SCREEN_CONTENT_TOOLS: bool = false; + + // Use 16x16 block size for now. + // TODO: Use maximum available + const SEG_ID_BLOCK_SIZE: u8 = 0; + + // Use single tile group; + const NUM_TILE_GROUPS_MINUS1: u8 = 0; + + let filter_level = [ + request.frame.loop_filter_params.loop_filter_level[0], + request.frame.loop_filter_params.loop_filter_level[1], + ]; + + let filter_level_u = request.frame.loop_filter_params.loop_filter_level[2]; + let filter_level_v = request.frame.loop_filter_params.loop_filter_level[3]; + + let superres_scale_denominator = u8::try_from(request.frame.superres_denom)?; + + let interpolation_filter = request.frame.interpolation_filter as u8; + + let mut loop_filter_ref_deltas = [0; 8]; + for (i, delta) in loop_filter_ref_deltas.iter_mut().enumerate() { + *delta = request.frame.loop_filter_params.loop_filter_ref_deltas[i]; + } + + let base_qindex = u8::try_from(request.frame.quantization_params.base_q_idx)?; + let y_dc_delta_q = i8::try_from(request.frame.quantization_params.delta_q_y_dc)?; + let u_dc_delta_q = i8::try_from(request.frame.quantization_params.delta_q_u_dc)?; + let u_ac_delta_q = i8::try_from(request.frame.quantization_params.delta_q_u_ac)?; + let v_dc_delta_q = i8::try_from(request.frame.quantization_params.delta_q_v_dc)?; + let v_ac_delta_q = i8::try_from(request.frame.quantization_params.delta_q_v_ac)?; + + // Clamp tunings's quaility range to correct range + let min_base_qindex = request.tunings.min_quality.max(MIN_BASE_QINDEX); + let min_base_qindex = u8::try_from(min_base_qindex)?; + let max_base_qindex = request.tunings.max_quality.min(MAX_BASE_QINDEX); + let max_base_qindex = u8::try_from(max_base_qindex)?; + + let qm_y = u16::try_from(request.frame.quantization_params.qm_y)?; + let qm_u = u16::try_from(request.frame.quantization_params.qm_u)?; + let qm_v = u16::try_from(request.frame.quantization_params.qm_v)?; + + let tx_mode = request.frame.tx_mode as u32; + + // Make driver make decision use single reference or compound reference. + const REFERENCE_MODE: u32 = 0 /* REFERENCE_MODE_SELECT */; + + let segmentation_temporal_update = + request.frame.segmentation_params.segmentation_temporal_update; + + const SEGMENT_NUMBER: u8 = 0; + assert!( + !request.frame.segmentation_params.segmentation_enabled, + "Unsupported segmentation_enabled=1" + ); + + // Segementation feature mask + let mut feature_mask = [0u8; MAX_SEGMENTS]; + for (seg, mask) in feature_mask.iter_mut().enumerate() { + for lvl in 0..u8::try_from(SEG_LVL_MAX)? { + if request.frame.segmentation_params.feature_enabled[seg][lvl as usize] { + *mask |= 1u8 << lvl; + } + } + } + + assert!( + request.frame.tile_info.tile_cols == 1 + && request.frame.tile_info.tile_cols_log2 == 0 + && request.frame.tile_info.tile_rows == 1 + && request.frame.tile_info.tile_rows_log2 == 0, + "Single tile is only supported for now" + ); + let tile_cols = u8::try_from(request.frame.tile_info.tile_cols)?; + let tile_rows = u8::try_from(request.frame.tile_info.tile_rows)?; + + let mut width_in_sbs_minus_1 = [0u16; MAX_TILE_COLS - 1]; + for (i, width) in width_in_sbs_minus_1.iter_mut().enumerate() { + *width = u16::try_from(request.frame.tile_info.width_in_sbs_minus_1[i])?; + } + + let mut height_in_sbs_minus_1 = [0u16; MAX_TILE_ROWS - 1]; + for (i, height) in height_in_sbs_minus_1.iter_mut().enumerate() { + *height = u16::try_from(request.frame.tile_info.height_in_sbs_minus_1[i])?; + } + + let context_update_tile_id = u16::try_from(request.frame.tile_info.context_update_tile_id)?; + + let cdef_damping_minus_3 = u8::try_from(request.frame.cdef_params.cdef_damping - 3)?; + + let cdef_bits = u8::try_from(request.frame.cdef_params.cdef_bits)?; + let mut cdef_y_strengths = [0u8; CDEF_MAX]; + for (i, strength) in cdef_y_strengths.iter_mut().enumerate() { + *strength = u8::try_from(request.frame.cdef_params.cdef_y_pri_strength[i])?; + } + + let mut cdef_uv_strengths = [0u8; CDEF_MAX]; + for (i, strength) in cdef_uv_strengths.iter_mut().enumerate() { + *strength = u8::try_from(request.frame.cdef_params.cdef_uv_pri_strength[i])?; + } + + let yframe_restoration_type = + request.frame.loop_restoration_params.frame_restoration_type[0] as u16; + let cbframe_restoration_type = + request.frame.loop_restoration_params.frame_restoration_type[1] as u16; + let crframe_restoration_type = + request.frame.loop_restoration_params.frame_restoration_type[2] as u16; + + let lr_unit_shift = u16::from(request.frame.loop_restoration_params.lr_unit_shift); + let lr_uv_shift = request.frame.loop_restoration_params.lr_uv_shift != 0; + + // Warped motion params + let wm = [Default::default(); REFS_PER_FRAME]; + + // Ignore by driver + const BIT_OFFSET_QINDEX: u32 = 0; + const BIT_OFFSET_SEGMENTATION: u32 = 0; + const BIT_OFFSET_LOOPFILTER_PARAMS: u32 = 0; + const BIT_OFFSET_CDEF_PARAMS: u32 = 0; + const SIZE_IN_BITS_CDEF_PARAMS: u32 = 0; + + // TODO: use packed header and fill for bitrate control + const BYTE_OFFSET_FRAME_HDR_OBU_SIZE: u32 = 0; + const SIZE_IN_BITS_FRAME_HDR_OBU: u32 = 0; + + let temporal_id = u8::try_from(request.frame.obu_header.temporal_id)?; + let spatial_id = u8::try_from(request.frame.obu_header.spatial_id)?; + + const NUMBER_SKIP_FRAMES: u8 = 0; + const SKIP_FRAMES_REDUCED_SIZE: i32 = 0; + + Ok(EncPictureParameterBufferAV1::new( + frame_width_minus_1, + frame_height_minus_1, + reconstructed_frame, + coded_buf, + reference_frames, + ref_frame_idx, + HIERARCHICAL_LEVEL_PLUS1, + primary_ref_frame, + order_hint, + refresh_frame_flags, + &ref_frame_ctrl_l0, + &ref_frame_ctrl_l1, + &AV1EncPictureFlags::new( + frame_type, + request.frame.error_resilient_mode, + request.frame.disable_cdf_update, + request.frame.use_superres, + request.frame.allow_high_precision_mv, + request.frame.use_ref_frame_mvs, + request.frame.disable_frame_end_update_cdf, + request.frame.reduced_tx_set, + ENABLE_FRAME_OBU, + LONG_TERM_REFERENCE, + DISABLE_FRAME_RECON, + request.frame.allow_intrabc, + PALETTE_MODE_ENABLE, + ALLOW_SCREEN_CONTENT_TOOLS, + FORCE_INTEGER_MV, + ), + SEG_ID_BLOCK_SIZE, + NUM_TILE_GROUPS_MINUS1, + temporal_id, + filter_level, + filter_level_u, + filter_level_v, + &AV1EncLoopFilterFlags::new( + request.frame.loop_filter_params.loop_filter_sharpness, + request.frame.loop_filter_params.loop_filter_delta_enabled, + request.frame.loop_filter_params.loop_filter_delta_update, + ), + superres_scale_denominator, + interpolation_filter, + loop_filter_ref_deltas, + request.frame.loop_filter_params.loop_filter_mode_deltas, + base_qindex, + y_dc_delta_q, + u_dc_delta_q, + u_ac_delta_q, + v_dc_delta_q, + v_ac_delta_q, + min_base_qindex, + max_base_qindex, + &AV1EncQMatrixFlags::new( + request.frame.quantization_params.using_qmatrix, + qm_y, + qm_u, + qm_v, + ), + &AV1EncModeControlFlags::new( + request.frame.quantization_params.delta_q_present, + request.frame.quantization_params.delta_q_res, + request.frame.loop_filter_params.delta_lf_present, + request.frame.loop_filter_params.delta_lf_res as u32, + request.frame.loop_filter_params.delta_lf_multi, + tx_mode, + REFERENCE_MODE, + request.frame.skip_mode_present, + ), + &EncSegParamAV1::new( + &EncSegParamFlagsAV1::new( + request.frame.segmentation_params.segmentation_enabled, + request.frame.segmentation_params.segmentation_update_map, + segmentation_temporal_update, + ), + SEGMENT_NUMBER, + request.frame.segmentation_params.feature_data, + feature_mask, + ), + tile_cols, + tile_rows, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + context_update_tile_id, + cdef_damping_minus_3, + cdef_bits, + cdef_y_strengths, + cdef_uv_strengths, + &AV1EncLoopRestorationFlags::new( + yframe_restoration_type, + cbframe_restoration_type, + crframe_restoration_type, + lr_unit_shift, + lr_uv_shift, + ), + wm, + BIT_OFFSET_QINDEX, + BIT_OFFSET_SEGMENTATION, + BIT_OFFSET_LOOPFILTER_PARAMS, + BIT_OFFSET_CDEF_PARAMS, + SIZE_IN_BITS_CDEF_PARAMS, + BYTE_OFFSET_FRAME_HDR_OBU_SIZE, + SIZE_IN_BITS_FRAME_HDR_OBU, + &AV1EncTileGroupObuHdrInfo::new( + request.frame.obu_header.extension_flag, + request.frame.obu_header.has_size_field, + temporal_id, + spatial_id, + ), + NUMBER_SKIP_FRAMES, + SKIP_FRAMES_REDUCED_SIZE, + )) + } + + fn build_tile_group_param() -> EncTileGroupBufferAV1 { + // Single tile is only supported for now. + EncTileGroupBufferAV1::new(0, 0) + } +} + +impl StatelessAV1EncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow> + 'static, +{ + fn encode_tile_group( + &mut self, + request: BackendRequest, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)> { + let coded_buf = self.new_coded_buffer(&request.tunings.rate_control)?; + let recon = self.new_scratch_picture()?; + + let seq_param = Self::build_seq_param(&request)?; + let seq_param = + libva::BufferType::EncSequenceParameter(libva::EncSequenceParameter::AV1(seq_param)); + + let pic_param = Self::build_pic_param(&request, &recon, &coded_buf)?; + let pic_param = + libva::BufferType::EncPictureParameter(libva::EncPictureParameter::AV1(pic_param)); + + let tg_param = Self::build_tile_group_param(); + let tg_param = + libva::BufferType::EncSliceParameter(libva::EncSliceParameter::AV1(tg_param)); + + let mut references = Vec::new(); + + for ref_frame in &request.references { + let Some(ref_frame) = ref_frame else { + continue; + }; + + references.push(ref_frame.clone() as Rc); + } + + let mut picture = + Picture::new(request.input_meta.timestamp, Rc::clone(self.context()), request.input); + + picture.add_buffer(self.context().create_buffer(seq_param)?); + picture.add_buffer(self.context().create_buffer(pic_param)?); + picture.add_buffer(self.context().create_buffer(tg_param)?); + + // Start processing the picture encoding + let picture = picture.begin().map_err(BackendError::BeginPictureError)?; + let picture = picture.render().map_err(BackendError::RenderPictureError)?; + let picture = picture.end().map_err(BackendError::EndPictureError)?; + + // libva will handle the synchronization of reconstructed surface with implicit fences. + // Therefore return the reconstructed frame immediately. + let reference_promise = ReadyPromise::from(recon); + + let bitstream_promise = + CodedOutputPromise::new(picture, references, coded_buf, request.coded_output); + + Ok((reference_promise, bitstream_promise)) + } +} + +impl + StatelessEncoder>> +{ + pub fn new_vaapi( + display: Rc, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + low_power: bool, + blocking_mode: BlockingMode, + ) -> EncodeResult { + let va_profile = match config.profile { + Profile::Profile0 => VAProfileAV1Profile0, + Profile::Profile1 => VAProfileAV1Profile1, + _ => return Err(StatelessBackendError::UnsupportedProfile.into()), + }; + + if !matches!(config.initial_tunings.rate_control, RateControl::ConstantQuality(_)) { + return Err(EncodeError::Unsupported); + } + + let backend = VaapiBackend::new( + display, + va_profile, + fourcc, + coded_size, + libva::VA_RC_CQP, + low_power, + )?; + + Self::new_av1(backend, config, blocking_mode) + } +} + +#[cfg(test)] +mod tests { + use libva::Display; + use libva::UsageHint; + use libva::VAEntrypoint::VAEntrypointEncSliceLP; + use libva::VAProfile::VAProfileAV1Profile0; + use libva::VA_RT_FORMAT_YUV420; + use libva::VA_RT_FORMAT_YUV420_10; + + use super::*; + use crate::backend::vaapi::encoder::tests::upload_test_frame_nv12; + use crate::backend::vaapi::encoder::tests::TestFrameGenerator; + use crate::backend::vaapi::surface_pool::PooledVaSurface; + use crate::backend::vaapi::surface_pool::VaSurfacePool; + use crate::bitstream_utils::IvfFileHeader; + use crate::bitstream_utils::IvfFrameHeader; + use crate::codec::av1::parser::BitDepth; + use crate::codec::av1::parser::CdefParams; + use crate::codec::av1::parser::ColorConfig; + use crate::codec::av1::parser::FrameHeaderObu; + use crate::codec::av1::parser::FrameType; + use crate::codec::av1::parser::ObuHeader; + use crate::codec::av1::parser::ObuType; + use crate::codec::av1::parser::OperatingPoint; + use crate::codec::av1::parser::QuantizationParams; + use crate::codec::av1::parser::SequenceHeaderObu; + use crate::codec::av1::parser::TemporalDelimiterObu; + use crate::codec::av1::parser::TileInfo; + use crate::codec::av1::parser::TxMode; + use crate::codec::av1::parser::MAX_NUM_OPERATING_POINTS; + use crate::codec::av1::parser::PRIMARY_REF_NONE; + use crate::codec::av1::parser::SELECT_INTEGER_MV; + use crate::codec::av1::parser::SUPERRES_NUM; + use crate::codec::av1::synthesizer::Synthesizer; + use crate::decoder::FramePool; + use crate::encoder::simple_encode_loop; + use crate::encoder::stateless::BackendPromise; + use crate::encoder::stateless::StatelessEncoderBackendImport; + use crate::encoder::FrameMetadata; + use crate::encoder::RateControl; + use crate::encoder::Tunings; + use crate::FrameLayout; + use crate::PlaneLayout; + use crate::Resolution; + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_single_frame() { + let _ = env_logger::try_init(); + + type Descriptor = (); + type Surface = libva::Surface; + const WIDTH: u32 = 512; + const HEIGHT: u32 = 512; + let fourcc = b"NV12".into(); + + let frame_layout = FrameLayout { + format: (fourcc, 0), + size: Resolution { width: WIDTH, height: HEIGHT }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH as usize }, + PlaneLayout { + buffer_index: 0, + offset: (WIDTH * HEIGHT) as usize, + stride: WIDTH as usize, + }, + ], + }; + + let display = Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileAV1Profile0).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let mut backend = VaapiBackend::::new( + Rc::clone(&display), + VAProfileAV1Profile0, + fourcc, + Resolution { width: WIDTH, height: HEIGHT }, + libva::VA_RC_CQP, + low_power, + ) + .unwrap(); + + let mut surfaces = display + .create_surfaces( + VA_RT_FORMAT_YUV420, + Some(frame_layout.format.0 .0), + WIDTH, + HEIGHT, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .unwrap(); + + let surface = surfaces.pop().unwrap(); + + upload_test_frame_nv12(&display, &surface, 0.0); + + let input_meta = + FrameMetadata { layout: frame_layout, force_keyframe: false, timestamp: 0 }; + + let input = backend.import_picture(&input_meta, surface).unwrap(); + + let seq = SequenceHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::SequenceHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + seq_profile: Profile::Profile0, + num_planes: 3, + + frame_width_bits_minus_1: 16 - 1, + frame_height_bits_minus_1: 16 - 1, + max_frame_width_minus_1: (WIDTH - 1) as u16, + max_frame_height_minus_1: (HEIGHT - 1) as u16, + + enable_order_hint: true, + order_hint_bits: 8, + order_hint_bits_minus_1: 7, + seq_force_integer_mv: SELECT_INTEGER_MV as u32, + + operating_points: { + let mut ops: [OperatingPoint; MAX_NUM_OPERATING_POINTS] = Default::default(); + ops[0].seq_level_idx = 7; + ops + }, + + color_config: ColorConfig { + subsampling_x: true, + subsampling_y: true, + ..Default::default() + }, + + ..Default::default() + }; + + let frame = FrameHeaderObu { + obu_header: ObuHeader { + obu_type: ObuType::FrameHeader, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + + frame_type: FrameType::KeyFrame, + frame_is_intra: true, + primary_ref_frame: PRIMARY_REF_NONE, + refresh_frame_flags: 0xff, + error_resilient_mode: true, + + reduced_tx_set: true, + tx_mode_select: 1, + tx_mode: TxMode::Select, + + quantization_params: QuantizationParams { base_q_idx: 128, ..Default::default() }, + tile_info: TileInfo { + uniform_tile_spacing_flag: true, + tile_cols: 1, + tile_rows: 1, + tile_cols_log2: 0, + tile_rows_log2: 0, + width_in_sbs_minus_1: { + let mut value = [0u32; MAX_TILE_COLS]; + value[0] = WIDTH / 64 - 1; + value + }, + height_in_sbs_minus_1: { + let mut value = [0u32; MAX_TILE_ROWS]; + value[0] = HEIGHT / 64 - 1; + value + }, + ..Default::default() + }, + cdef_params: CdefParams { cdef_damping: 3, ..Default::default() }, + superres_denom: SUPERRES_NUM as u32, + upscaled_width: WIDTH, + frame_width: WIDTH, + frame_height: HEIGHT, + render_width: WIDTH, + render_height: HEIGHT, + + ..Default::default() + }; + + let request = Request { + sequence: seq.clone(), + frame: frame.clone(), + input, + input_meta, + references: [None, None, None, None, None, None, None], + ref_frame_ctrl_l0: [ReferenceFrameType::Intra; REFS_PER_FRAME], + ref_frame_ctrl_l1: [ReferenceFrameType::Intra; REFS_PER_FRAME], + intra_period: 4, + ip_period: 1, + tunings: Default::default(), + coded_output: Vec::new(), + }; + + let (_, output) = backend.encode_tile_group(request).unwrap(); + let output = output.sync().unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + + let mut out = std::fs::File::create("test_single_frame.av1.ivf").unwrap(); + + let td = TemporalDelimiterObu { + obu_header: ObuHeader { + obu_type: ObuType::TemporalDelimiter, + extension_flag: false, + has_size_field: true, + temporal_id: 0, + spatial_id: 0, + }, + }; + + let file_header = + IvfFileHeader::new(IvfFileHeader::CODEC_AV1, WIDTH as u16, HEIGHT as u16, 30, 10); + + file_header.writo_into(&mut out).unwrap(); + + { + let mut hdr_buf = Vec::new(); + + Synthesizer::<'_, TemporalDelimiterObu, _>::synthesize(&td, &mut hdr_buf).unwrap(); + Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq, &mut hdr_buf).unwrap(); + Synthesizer::<'_, FrameHeaderObu, _>::synthesize(&frame, &seq, &mut hdr_buf) + .unwrap(); + + let frame_header = IvfFrameHeader { + frame_size: hdr_buf.len() as u32 + output.len() as u32, + timestamp: 0, + }; + + frame_header.writo_into(&mut out).unwrap(); + out.write_all(&hdr_buf).unwrap(); + out.write_all(&output).unwrap(); + } + + out.flush().unwrap(); + } + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_vaapi_encoder() { + type VaapiAv1Encoder<'l> = + StatelessEncoder, VaapiBackend<(), PooledVaSurface<()>>>; + + const WIDTH: usize = 512; + const HEIGHT: usize = 512; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let display = libva::Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileAV1Profile0).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let config = EncoderConfig { + profile: Profile::Profile0, + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantQuality(128), + framerate: 30, + ..Default::default() + }, + ..Default::default() + }; + + let frame_layout = FrameLayout { + format: (b"NV12".into(), 0), + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, + ], + }; + + let mut encoder = VaapiAv1Encoder::new_vaapi( + Rc::clone(&display), + config, + frame_layout.format.0, + frame_layout.size, + low_power, + BlockingMode::Blocking, + ) + .unwrap(); + + let mut pool = VaSurfacePool::new( + Rc::clone(&display), + VA_RT_FORMAT_YUV420, + Some(UsageHint::USAGE_HINT_ENCODER), + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + ); + + pool.add_frames(vec![(); 16]).unwrap(); + + let mut frame_producer = TestFrameGenerator::new(FRAME_COUNT, display, pool, frame_layout); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_AV1, + WIDTH as u16, + HEIGHT as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }) + .unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_vaapi_encoder.av1.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[ignore] + // Ignore this test by default as it requires libva-compatible hardware. + #[test] + fn test_vaapi_encoder_p010() { + type VaapiAv1Encoder<'l> = + StatelessEncoder, VaapiBackend<(), PooledVaSurface<()>>>; + + const WIDTH: usize = 512; + const HEIGHT: usize = 512; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let display = libva::Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileAV1Profile0).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let config = EncoderConfig { + profile: Profile::Profile0, + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + bit_depth: BitDepth::Depth10, + initial_tunings: Tunings { + rate_control: RateControl::ConstantQuality(128), + framerate: 30, + ..Default::default() + }, + ..Default::default() + }; + + let frame_layout = FrameLayout { + format: (b"P010".into(), 0), + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, + ], + }; + + let mut encoder = VaapiAv1Encoder::new_vaapi( + Rc::clone(&display), + config, + frame_layout.format.0, + frame_layout.size, + low_power, + BlockingMode::Blocking, + ) + .unwrap(); + + let mut pool = VaSurfacePool::new( + Rc::clone(&display), + VA_RT_FORMAT_YUV420_10, + Some(UsageHint::USAGE_HINT_ENCODER), + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + ); + + pool.add_frames(vec![(); 16]).unwrap(); + + let mut frame_producer = TestFrameGenerator::new(FRAME_COUNT, display, pool, frame_layout); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_AV1, + WIDTH as u16, + HEIGHT as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }) + .unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_vaapi_encoder_p010.av1.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/h264.rs b/vendor/cros-codecs/src/encoder/stateless/h264.rs new file mode 100644 index 0000000..d038091 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/h264.rs @@ -0,0 +1,197 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::encoder::h264::EncoderConfig; +use crate::encoder::h264::H264; +use crate::encoder::stateless::h264::predictor::LowDelayH264; +use crate::encoder::stateless::BackendPromise; +use crate::encoder::stateless::BitstreamPromise; +use crate::encoder::stateless::FrameMetadata; +use crate::encoder::stateless::Predictor; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessCodec; +use crate::encoder::stateless::StatelessEncoderBackendImport; +use crate::encoder::stateless::StatelessEncoderExecute; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::EncodeResult; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::BlockingMode; + +mod predictor; + +#[cfg(feature = "vaapi")] +pub mod vaapi; + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum IsReference { + No, + ShortTerm, + LongTerm, +} + +#[derive(Clone, Debug)] +pub struct DpbEntryMeta { + /// Picture order count + poc: u16, + frame_num: u32, + is_reference: IsReference, +} + +/// Frame structure used in the backend representing currently encoded frame or references used +/// for its encoding. +pub struct DpbEntry { + /// Reconstructed picture + recon_pic: R, + /// Decoded picture buffer entry metadata + meta: DpbEntryMeta, +} + +/// Stateless H.264 encoder backend input. +pub struct BackendRequest { + sps: Rc, + pps: Rc, + header: SliceHeader, + + /// Input frame to be encoded + input: P, + + /// Input frame metadata + input_meta: FrameMetadata, + + /// DPB entry metadata + dpb_meta: DpbEntryMeta, + + /// Reference lists + ref_list_0: Vec>>, + ref_list_1: Vec>>, + + /// Period between intra frames + intra_period: u32, + + /// Period between intra frame and P frame + ip_period: u32, + + /// Number of macroblock to be encoded in slice + num_macroblocks: usize, + + /// True whenever the result is IDR + is_idr: bool, + + /// [`Tunings`] for the frame + tunings: Tunings, + + /// Container for the request output. [`StatelessH264EncoderBackend`] impl shall move it and + /// append the slice data to it. This prevents unnecessary copying of bitstream around. + coded_output: Vec, +} + +/// Wrapper type for [`BackendPromise`], with additional +/// metadata. +pub struct ReferencePromise

+where + P: BackendPromise, +{ + /// Slice data and reconstructed surface promise + recon: P, + + /// [`DpbEntryMeta`] of reconstructed surface + dpb_meta: DpbEntryMeta, +} + +impl

BackendPromise for ReferencePromise

+where + P: BackendPromise, +{ + type Output = DpbEntry; + + fn is_ready(&self) -> bool { + self.recon.is_ready() + } + + fn sync(self) -> StatelessBackendResult { + let recon_pic = self.recon.sync()?; + + log::trace!("synced recon picture frame_num={}", self.dpb_meta.frame_num); + + Ok(DpbEntry { recon_pic, meta: self.dpb_meta }) + } +} + +impl StatelessCodec for H264 +where + Backend: StatelessVideoEncoderBackend, +{ + type Reference = DpbEntry; + + type Request = BackendRequest; + + type CodedPromise = BitstreamPromise; + + type ReferencePromise = ReferencePromise; +} + +/// Trait for stateless encoder backend for H.264 +pub trait StatelessH264EncoderBackend: StatelessVideoEncoderBackend { + /// Submit a [`BackendRequest`] to the backend. This operation returns both a + /// [`StatelessVideoEncoderBackend::CodedPromise`] and a + /// [`StatelessVideoEncoderBackend::ReconPromise`] with resulting slice data. + fn encode_slice( + &mut self, + request: BackendRequest, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)>; +} + +pub type StatelessEncoder = + crate::encoder::stateless::StatelessEncoder; + +impl StatelessEncoderExecute + for StatelessEncoder +where + Backend: StatelessH264EncoderBackend, +{ + fn execute( + &mut self, + request: BackendRequest, + ) -> EncodeResult<()> { + let meta = request.input_meta.clone(); + let dpb_meta = request.dpb_meta.clone(); + + // The [`BackendRequest`] has a frame from predictor. Decreasing internal counter. + self.predictor_frame_count -= 1; + + log::trace!("submitting new request"); + let (recon, bitstream) = self.backend.encode_slice(request)?; + + // Wrap promise from backend with headers and metadata + let slice_promise = BitstreamPromise { bitstream, meta }; + + self.output_queue.add_promise(slice_promise); + + let ref_promise = ReferencePromise { recon, dpb_meta }; + + self.recon_queue.add_promise(ref_promise); + + Ok(()) + } +} + +impl StatelessEncoder +where + Backend: StatelessH264EncoderBackend, + Backend: StatelessEncoderBackendImport, +{ + fn new_h264(backend: Backend, config: EncoderConfig, mode: BlockingMode) -> EncodeResult { + let predictor: Box> = match config.pred_structure { + PredictionStructure::LowDelay { limit } => Box::new(LowDelayH264::new(config, limit)), + }; + + Self::new(backend, mode, predictor) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/h264/predictor.rs b/vendor/cros-codecs/src/encoder/stateless/h264/predictor.rs new file mode 100644 index 0000000..9141e6d --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/h264/predictor.rs @@ -0,0 +1,269 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use log::trace; + +use crate::codec::h264::parser::Level; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::PpsBuilder; +use crate::codec::h264::parser::Profile; +use crate::codec::h264::parser::SliceHeaderBuilder; +use crate::codec::h264::parser::SliceType; +use crate::codec::h264::parser::Sps; +use crate::codec::h264::parser::SpsBuilder; +use crate::codec::h264::synthesizer::Synthesizer; +use crate::encoder::stateless::h264::BackendRequest; +use crate::encoder::stateless::h264::DpbEntry; +use crate::encoder::stateless::h264::DpbEntryMeta; +use crate::encoder::stateless::h264::EncoderConfig; +use crate::encoder::stateless::h264::IsReference; +use crate::encoder::stateless::predictor::LowDelay; +use crate::encoder::stateless::predictor::LowDelayDelegate; +use crate::encoder::stateless::FrameMetadata; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::RateControl; +use crate::encoder::Tunings; + +pub(crate) const MIN_QP: u8 = 1; +pub(crate) const MAX_QP: u8 = 51; + +pub(crate) struct LowDelayH264Delegate { + /// Current sequence SPS + sps: Option>, + /// Current sequence PPS + pps: Option>, + + // True if SPS or PPS changed and should reappear in the bitstream + update_params_sets: bool, + + /// Encoder config + config: EncoderConfig, +} + +pub(crate) type LowDelayH264 = LowDelay< + Picture, + DpbEntry, + LowDelayH264Delegate, + BackendRequest, +>; + +impl LowDelayH264 { + pub(super) fn new(config: EncoderConfig, limit: u16) -> Self { + Self { + queue: Default::default(), + references: Default::default(), + counter: 0, + limit, + tunings: config.initial_tunings.clone(), + delegate: LowDelayH264Delegate { + config, + update_params_sets: false, + sps: None, + pps: None, + }, + tunings_queue: Default::default(), + _phantom: Default::default(), + } + } + + fn new_sequence(&mut self) { + trace!("beginning new sequence"); + let config = &self.delegate.config; + + let mut sps = SpsBuilder::new().seq_parameter_set_id(0).profile_idc(config.profile); + + // H.264 Table 6-1 + sps = match config.profile { + // 4:2:2 subsampling + Profile::High422P => sps.chroma_format_idc(2), + // 4:2:0 subsampling + _ => sps.chroma_format_idc(1), + }; + + let sps = sps + .level_idc(config.level) + .max_frame_num(self.limit as u32) + .pic_order_cnt_type(0) + .max_pic_order_cnt_lsb(self.limit as u32 * 2) + .max_num_ref_frames(1) + .frame_mbs_only_flag(true) + // H264 spec Table A-4 + .direct_8x8_inference_flag(config.level >= Level::L3) + .resolution(config.resolution.width, config.resolution.height) + .bit_depth_luma(8) + .bit_depth_chroma(8) + .aspect_ratio(1, 1) + .timing_info(1, self.tunings.framerate * 2, false) + .build(); + + let min_qp = self.tunings.min_quality.max(MIN_QP as u32); + let max_qp = self.tunings.max_quality.min(MAX_QP as u32); + + let init_qp = if let RateControl::ConstantQuality(init_qp) = self.tunings.rate_control { + // Limit QP to valid values + init_qp.clamp(min_qp, max_qp) as u8 + } else { + // Pick middle QP for default qp + ((min_qp + max_qp) / 2) as u8 + }; + + let pps = PpsBuilder::new(Rc::clone(&sps)) + .pic_parameter_set_id(0) + .pic_init_qp(init_qp) + .deblocking_filter_control_present_flag(true) + .num_ref_idx_l0_default_active(1) + // Unused, P frame relies only on list0 + .num_ref_idx_l1_default_active_minus1(0) + .build(); + + self.delegate.sps = Some(sps); + self.delegate.pps = Some(pps); + self.delegate.update_params_sets = true; + } +} + +impl + LowDelayDelegate, BackendRequest> + for LowDelayH264 +{ + fn request_keyframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + idr: bool, + ) -> EncodeResult> { + if idr { + // Begin new sequence and start with I frame and no references. + self.new_sequence(); + } + + let sps = self.delegate.sps.clone().ok_or(EncodeError::InvalidInternalState)?; + let pps = self.delegate.pps.clone().ok_or(EncodeError::InvalidInternalState)?; + + let dpb_meta = DpbEntryMeta { + poc: ((self.counter * 2) & 0xffff) as u16, + frame_num: self.counter as u32, + is_reference: IsReference::ShortTerm, + }; + + let header = SliceHeaderBuilder::new(&pps) + .slice_type(SliceType::I) + .first_mb_in_slice(0) + .pic_order_cnt_lsb(dpb_meta.poc) + .build(); + + let mut headers = vec![]; + if idr || self.delegate.update_params_sets { + Synthesizer::>::synthesize(3, &sps, &mut headers, true)?; + Synthesizer::>::synthesize(3, &pps, &mut headers, true)?; + self.delegate.update_params_sets = false; + } + + let num_macroblocks = (sps.pic_width_in_mbs_minus1 as usize + 1) + * (sps.pic_height_in_map_units_minus1 as usize + 1); + + let request = BackendRequest { + sps, + pps, + header, + input, + input_meta, + dpb_meta, + // This frame is IDR, therefore it has no references + ref_list_0: vec![], + ref_list_1: vec![], + + // I frame is every `self.limit` is requested + intra_period: self.limit as u32, + // There is no B frames between I and P frames + ip_period: 0, + + num_macroblocks, + + is_idr: idr, + tunings: self.tunings.clone(), + + coded_output: headers, + }; + + Ok(request) + } + + fn request_interframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + ) -> EncodeResult> { + let mut ref_list_0 = vec![]; + + // Use all avaiable reference frames in DPB. Their number is limited by the parameter + for reference in self.references.iter().rev() { + ref_list_0.push(Rc::clone(reference)); + } + + let sps = self.delegate.sps.clone().ok_or(EncodeError::InvalidInternalState)?; + let pps = self.delegate.pps.clone().ok_or(EncodeError::InvalidInternalState)?; + + let dpb_meta = DpbEntryMeta { + poc: ((self.counter * 2) & 0xffff) as u16, + frame_num: self.counter as u32, + is_reference: IsReference::ShortTerm, + }; + + let header = SliceHeaderBuilder::new(&pps) + .slice_type(SliceType::P) + .first_mb_in_slice(0) + .pic_order_cnt_lsb(dpb_meta.poc) + .build(); + + let mut headers = Vec::new(); + if self.delegate.update_params_sets { + Synthesizer::>::synthesize(3, &sps, &mut headers, true)?; + Synthesizer::>::synthesize(3, &pps, &mut headers, true)?; + self.delegate.update_params_sets = false; + } + + let num_macroblocks = (sps.pic_width_in_mbs_minus1 as usize + 1) + * (sps.pic_height_in_map_units_minus1 as usize + 1); + + let request = BackendRequest { + sps, + pps, + header, + input, + input_meta, + dpb_meta, + ref_list_0, + ref_list_1: vec![], // No future references + + // I frame is every `self.limit` is requested + intra_period: self.limit as u32, + // There is no B frames between I and P frames + ip_period: 0, + + num_macroblocks, + + is_idr: false, + tunings: self.tunings.clone(), + + coded_output: headers, + }; + + self.references.clear(); + + Ok(request) + } + + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } + + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { + self.new_sequence(); + Ok(()) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/h264/vaapi.rs b/vendor/cros-codecs/src/encoder/stateless/h264/vaapi.rs new file mode 100644 index 0000000..39e1122 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/h264/vaapi.rs @@ -0,0 +1,695 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::any::Any; +use std::borrow::Borrow; +use std::rc::Rc; + +use anyhow::Context; +use libva::BufferType; +use libva::Display; +use libva::EncCodedBuffer; +use libva::EncPictureParameter; +use libva::EncPictureParameterBufferH264; +use libva::EncSequenceParameter; +use libva::EncSequenceParameterBufferH264; +use libva::EncSliceParameter; +use libva::EncSliceParameterBufferH264; +use libva::H264EncFrameCropOffsets; +use libva::H264EncPicFields; +use libva::H264EncSeqFields; +use libva::H264VuiFields; +use libva::Picture; +use libva::PictureH264; +use libva::Surface; +use libva::SurfaceMemoryDescriptor; +use libva::VAProfile; +use libva::VA_INVALID_ID; +use libva::VA_PICTURE_H264_LONG_TERM_REFERENCE; +use libva::VA_PICTURE_H264_SHORT_TERM_REFERENCE; + +use crate::backend::vaapi::encoder::tunings_to_libva_rc; +use crate::backend::vaapi::encoder::CodedOutputPromise; +use crate::backend::vaapi::encoder::Reconstructed; +use crate::backend::vaapi::encoder::VaapiBackend; +use crate::codec::h264::parser::Pps; +use crate::codec::h264::parser::Profile; +use crate::codec::h264::parser::SliceHeader; +use crate::codec::h264::parser::Sps; +use crate::encoder::h264::EncoderConfig; +use crate::encoder::h264::H264; +use crate::encoder::stateless::h264::predictor::MAX_QP; +use crate::encoder::stateless::h264::predictor::MIN_QP; +use crate::encoder::stateless::h264::BackendRequest; +use crate::encoder::stateless::h264::DpbEntry; +use crate::encoder::stateless::h264::DpbEntryMeta; +use crate::encoder::stateless::h264::IsReference; +use crate::encoder::stateless::h264::StatelessEncoder; +use crate::encoder::stateless::h264::StatelessH264EncoderBackend; +use crate::encoder::stateless::ReadyPromise; +use crate::encoder::stateless::StatelessBackendError; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::EncodeResult; +use crate::encoder::RateControl; +use crate::video_frame::VideoFrame; +use crate::BlockingMode; +use crate::Fourcc; +use crate::Resolution; + +type Request<'l, H> = BackendRequest; + +impl StatelessVideoEncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow> + 'static, +{ + type Picture = H; + type Reconstructed = Reconstructed; + type CodedPromise = CodedOutputPromise; + type ReconPromise = ReadyPromise; +} + +impl VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: std::borrow::Borrow> + 'static, +{ + /// Builds an invalid [`libva::PictureH264`]. This is usually a place + /// holder to fill staticly sized array. + fn build_invalid_va_h264_pic_enc() -> libva::PictureH264 { + libva::PictureH264::new(libva::VA_INVALID_ID, 0, libva::VA_PICTURE_H264_INVALID, 0, 0) + } + + /// Builds [`libva::PictureH264`] from `frame` + fn build_h264_pic(surface: &Reconstructed, meta: &DpbEntryMeta) -> PictureH264 { + let flags = match meta.is_reference { + IsReference::No => 0, + IsReference::LongTerm => VA_PICTURE_H264_LONG_TERM_REFERENCE, + IsReference::ShortTerm => VA_PICTURE_H264_SHORT_TERM_REFERENCE, + }; + + PictureH264::new( + surface.surface_id(), + meta.frame_num, + flags, + meta.poc as i32, + meta.poc as i32, + ) + } + + /// Builds [`BufferType::EncSequenceParameter`] from `sps` + fn build_enc_seq_param( + sps: &Sps, + bits_per_second: u32, + intra_period: u32, + ip_period: u32, + ) -> BufferType { + let intra_idr_period = intra_period; + + let seq_fields = H264EncSeqFields::new( + sps.chroma_format_idc as u32, + sps.frame_mbs_only_flag as u32, + sps.mb_adaptive_frame_field_flag as u32, + sps.seq_scaling_matrix_present_flag as u32, + sps.direct_8x8_inference_flag as u32, + sps.log2_max_frame_num_minus4 as u32, + sps.pic_order_cnt_type as u32, + sps.log2_max_pic_order_cnt_lsb_minus4 as u32, + sps.delta_pic_order_always_zero_flag as u32, + ); + + let frame_crop = if sps.frame_cropping_flag { + Some(H264EncFrameCropOffsets::new( + sps.frame_crop_left_offset, + sps.frame_crop_right_offset, + sps.frame_crop_top_offset, + sps.frame_crop_bottom_offset, + )) + } else { + None + }; + + let vui_fields = if sps.vui_parameters_present_flag { + Some(H264VuiFields::new( + sps.vui_parameters.aspect_ratio_idc as u32, + sps.vui_parameters.timing_info_present_flag as u32, + sps.vui_parameters.bitstream_restriction_flag as u32, + sps.vui_parameters.log2_max_mv_length_horizontal, + sps.vui_parameters.log2_max_mv_length_vertical, + sps.vui_parameters.fixed_frame_rate_flag as u32, + sps.vui_parameters.low_delay_hrd_flag as u32, + sps.vui_parameters.motion_vectors_over_pic_boundaries_flag as u32, + )) + } else { + None + }; + + let mut offset_for_ref_frame = [0i32; 256]; + offset_for_ref_frame[..255].copy_from_slice(&sps.offset_for_ref_frame[..]); + + BufferType::EncSequenceParameter(EncSequenceParameter::H264( + EncSequenceParameterBufferH264::new( + sps.seq_parameter_set_id, + sps.level_idc as u8, + intra_period, + intra_idr_period, + ip_period, + bits_per_second, + sps.max_num_ref_frames as u32, + sps.pic_width_in_mbs_minus1 + 1, + sps.pic_height_in_map_units_minus1 + 1, + &seq_fields, + sps.bit_depth_luma_minus8, + sps.bit_depth_chroma_minus8, + sps.num_ref_frames_in_pic_order_cnt_cycle, + sps.offset_for_non_ref_pic, + sps.offset_for_top_to_bottom_field, + offset_for_ref_frame, + frame_crop, + vui_fields, + sps.vui_parameters.aspect_ratio_idc, + sps.vui_parameters.sar_width as u32, + sps.vui_parameters.sar_height as u32, + sps.vui_parameters.num_units_in_tick, + sps.vui_parameters.time_scale, + ), + )) + } + + /// Builds [`BufferType::EncPictureParameter`] from [`Request`] and sets bitstream + /// output to `coded_buf`. + fn build_enc_pic_param( + request: &Request<'_, H>, + coded_buf: &EncCodedBuffer, + recon: &Reconstructed, + ) -> BufferType { + let pic_fields = H264EncPicFields::new( + request.is_idr as u32, + (request.dpb_meta.is_reference != IsReference::No) as u32, + request.pps.entropy_coding_mode_flag as u32, + request.pps.weighted_pred_flag as u32, + request.pps.weighted_bipred_idc as u32, + request.pps.constrained_intra_pred_flag as u32, + request.pps.transform_8x8_mode_flag as u32, + request.pps.deblocking_filter_control_present_flag as u32, + request.pps.redundant_pic_cnt_present_flag as u32, + 0, + request.pps.pic_scaling_matrix_present_flag as u32, + ); + + let curr_pic = Self::build_h264_pic(recon, &request.dpb_meta); + + assert!(request.ref_list_0.len() + request.ref_list_1.len() <= 16); + + let mut reference_frames: [PictureH264; 16] = (0..16) + .map(|_| Self::build_invalid_va_h264_pic_enc()) + .collect::>() + .try_into() + .unwrap_or_else(|_| panic!()); + + for (idx, ref_frame) in + request.ref_list_0.iter().chain(request.ref_list_1.iter()).enumerate().take(16) + { + reference_frames[idx] = Self::build_h264_pic(&ref_frame.recon_pic, &ref_frame.meta); + } + + BufferType::EncPictureParameter(EncPictureParameter::H264( + EncPictureParameterBufferH264::new( + curr_pic, + reference_frames, + coded_buf.id(), + request.pps.pic_parameter_set_id, + request.pps.seq_parameter_set_id, + 0, // last_pic, don't appned EOS + request.dpb_meta.frame_num as u16, + (request.pps.pic_init_qp_minus26 + 26) as u8, + request.pps.num_ref_idx_l0_default_active_minus1, + request.pps.num_ref_idx_l1_default_active_minus1, + request.pps.chroma_qp_index_offset, + request.pps.second_chroma_qp_index_offset, + &pic_fields, + ), + )) + } + + /// Builds [`BufferType::EncSliceParameter`] + fn build_enc_slice_param( + pps: &Pps, + header: &SliceHeader, + ref_list_0: &[Rc>], + ref_list_1: &[Rc>], + num_macroblocks: u32, + ) -> BufferType { + let mut ref_pic_list_0: [PictureH264; 32] = (0..32) + .map(|_| Self::build_invalid_va_h264_pic_enc()) + .collect::>() + .try_into() + .unwrap_or_else(|_| panic!()); + + for (idx, ref_frame) in ref_list_0.iter().enumerate().take(16) { + ref_pic_list_0[idx] = Self::build_h264_pic(&ref_frame.recon_pic, &ref_frame.meta); + } + + let mut ref_pic_list_1: [PictureH264; 32] = (0..32) + .map(|_| Self::build_invalid_va_h264_pic_enc()) + .collect::>() + .try_into() + .unwrap_or_else(|_| panic!()); + + for (idx, ref_frame) in ref_list_1.iter().enumerate().take(16) { + ref_pic_list_1[idx] = Self::build_h264_pic(&ref_frame.recon_pic, &ref_frame.meta); + } + + let mut luma_weight_l0_flag = false; + let mut luma_offset_l0 = [0i16; 32]; + + if header.pred_weight_table.luma_weight_l0 != [0i16; 32] { + luma_weight_l0_flag = true; + for (i, val) in header.pred_weight_table.luma_offset_l0.iter().enumerate() { + luma_offset_l0[i] = (*val).into(); + } + } + + let mut chroma_weight_l0_flag = false; + let mut chroma_offset_l0 = [[0i16; 2]; 32]; + + if header.pred_weight_table.chroma_weight_l0 != [[0i16; 2]; 32] { + chroma_weight_l0_flag = true; + for (i, val) in header.pred_weight_table.chroma_offset_l0.iter().enumerate() { + chroma_offset_l0[i] = [val[0].into(), val[1].into()]; + } + } + + let mut luma_weight_l1_flag = false; + let mut luma_offset_l1 = [0i16; 32]; + + if header.pred_weight_table.luma_weight_l1 != [0i16; 32] { + luma_weight_l1_flag = true; + for (i, val) in header.pred_weight_table.luma_offset_l1.iter().enumerate() { + luma_offset_l1[i] = *val; + } + } + + let mut chroma_weight_l1_flag = false; + let mut chroma_offset_l1 = [[0i16; 2]; 32]; + + if header.pred_weight_table.chroma_weight_l1 != [[0i16; 2]; 32] { + chroma_weight_l1_flag = true; + for (i, val) in header.pred_weight_table.chroma_offset_l1.iter().enumerate() { + chroma_offset_l1[i] = [val[0].into(), val[1].into()]; + } + } + + let (num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1) = + if header.num_ref_idx_active_override_flag { + (header.num_ref_idx_l0_active_minus1, header.num_ref_idx_l1_active_minus1) + } else { + (pps.num_ref_idx_l0_default_active_minus1, pps.num_ref_idx_l1_default_active_minus1) + }; + BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new( + header.first_mb_in_slice, + num_macroblocks, + VA_INVALID_ID, + header.slice_type as u8, + pps.pic_parameter_set_id, + header.idr_pic_id, + header.pic_order_cnt_lsb, + header.delta_pic_order_cnt_bottom, + header.delta_pic_order_cnt, + header.direct_spatial_mv_pred_flag as u8, + header.num_ref_idx_active_override_flag as u8, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + ref_pic_list_0, + ref_pic_list_1, + header.pred_weight_table.luma_log2_weight_denom, + header.pred_weight_table.chroma_log2_weight_denom, + luma_weight_l0_flag as u8, + header.pred_weight_table.luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag as u8, + header.pred_weight_table.chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag as u8, + header.pred_weight_table.luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag as u8, + header.pred_weight_table.chroma_weight_l1, + chroma_offset_l1, + header.cabac_init_idc, + header.slice_qp_delta, + header.disable_deblocking_filter_idc, + header.slice_alpha_c0_offset_div2, + header.slice_beta_offset_div2, + ))) + } +} + +impl StatelessH264EncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + H: Borrow> + 'static, +{ + fn encode_slice( + &mut self, + request: Request<'_, H>, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)> { + let coded_buf = self.new_coded_buffer(&request.tunings.rate_control)?; + let recon = self.new_scratch_picture()?; + + // Use bitrate from RateControl or ask driver to ignore + let bits_per_second = request.tunings.rate_control.bitrate_target().unwrap_or(0) as u32; + let seq_param = Self::build_enc_seq_param( + &request.sps, + bits_per_second, + request.intra_period, + request.ip_period, + ); + + let pic_param = Self::build_enc_pic_param(&request, &coded_buf, &recon); + let slice_param = Self::build_enc_slice_param( + &request.pps, + &request.header, + &request.ref_list_0, + &request.ref_list_1, + request.num_macroblocks as u32, + ); + + // Clone reference frames + let references: Vec> = request + .ref_list_0 + .iter() + .cloned() + .chain(request.ref_list_1.iter().cloned()) + .map(|entry| entry as Rc) + .collect(); + + // Clone picture using [`Picture::new_from_same_surface`] to avoid + // creatig a shared cell picture between its references and processed + // picture. + let mut picture = Picture::new( + request.dpb_meta.frame_num as u64, + Rc::clone(self.context()), + request.input, + ); + + let rc_param = + tunings_to_libva_rc::<{ MIN_QP as u32 }, { MAX_QP as u32 }>(&request.tunings)?; + let rc_param = BufferType::EncMiscParameter(libva::EncMiscParameter::RateControl(rc_param)); + + let framerate_param = BufferType::EncMiscParameter(libva::EncMiscParameter::FrameRate( + libva::EncMiscParameterFrameRate::new(request.tunings.framerate, 0), + )); + + picture.add_buffer(self.context().create_buffer(seq_param)?); + picture.add_buffer(self.context().create_buffer(pic_param)?); + picture.add_buffer(self.context().create_buffer(slice_param)?); + picture.add_buffer(self.context().create_buffer(rc_param)?); + picture.add_buffer(self.context().create_buffer(framerate_param)?); + + // Start processing the picture encoding + let picture = picture.begin().context("picture begin")?; + let picture = picture.render().context("picture render")?; + let picture = picture.end().context("picture end")?; + + // HACK: Make sure that slice nalu start code is at least 4 bytes. + // TODO: Use packed headers to supply slice header with nalu start code of size 4 and get + // rid of this hack. + let mut coded_output = request.coded_output; + coded_output.push(0); + + // libva will handle the synchronization of reconstructed surface with implicit fences. + // Therefore return the reconstructed frame immediately. + let reference_promise = ReadyPromise::from(recon); + + let bitstream_promise = + CodedOutputPromise::new(picture, references, coded_buf, coded_output); + + Ok((reference_promise, bitstream_promise)) + } +} + +impl StatelessEncoder>> { + pub fn new_vaapi( + display: Rc, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + low_power: bool, + blocking_mode: BlockingMode, + ) -> EncodeResult { + let va_profile = match config.profile { + Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline, + Profile::Main => VAProfile::VAProfileH264Main, + Profile::High => VAProfile::VAProfileH264High, + _ => return Err(StatelessBackendError::UnsupportedProfile.into()), + }; + + let bitrate_control = match config.initial_tunings.rate_control { + RateControl::ConstantBitrate(_) => libva::VA_RC_CBR, + RateControl::ConstantQuality(_) => libva::VA_RC_CQP, + }; + + let backend = + VaapiBackend::new(display, va_profile, fourcc, coded_size, bitrate_control, low_power)?; + + Self::new_h264(backend, config, blocking_mode) + } +} + +#[cfg(test)] +pub(super) mod tests { + use libva::Display; + use libva::UsageHint; + use libva::VAEntrypoint::VAEntrypointEncSliceLP; + use libva::VAProfile::VAProfileH264Main; + use libva::VA_RT_FORMAT_YUV420; + + use super::*; + use crate::backend::vaapi::encoder::tests::upload_test_frame_nv12; + use crate::backend::vaapi::encoder::tests::TestFrameGenerator; + use crate::backend::vaapi::surface_pool::PooledVaSurface; + use crate::backend::vaapi::surface_pool::VaSurfacePool; + use crate::codec::h264::parser::Level; + use crate::codec::h264::parser::PpsBuilder; + use crate::codec::h264::parser::Profile; + use crate::codec::h264::parser::SliceHeaderBuilder; + use crate::codec::h264::parser::SliceType; + use crate::codec::h264::parser::SpsBuilder; + use crate::decoder::FramePool; + use crate::encoder::simple_encode_loop; + use crate::encoder::stateless::h264::BackendRequest; + use crate::encoder::stateless::h264::EncoderConfig; + use crate::encoder::stateless::h264::StatelessEncoder; + use crate::encoder::stateless::BackendPromise; + use crate::encoder::stateless::StatelessEncoderBackendImport; + use crate::encoder::FrameMetadata; + use crate::encoder::Tunings; + use crate::FrameLayout; + use crate::PlaneLayout; + use crate::Resolution; + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_simple_encode_slice() { + type Descriptor = (); + type Surface = libva::Surface; + const WIDTH: u32 = 256; + const HEIGHT: u32 = 256; + let fourcc = b"NV12".into(); + + let frame_layout = FrameLayout { + format: (fourcc, 0), + size: Resolution { width: WIDTH, height: HEIGHT }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH as usize }, + PlaneLayout { + buffer_index: 0, + offset: (WIDTH * HEIGHT) as usize, + stride: WIDTH as usize, + }, + ], + }; + + let display = Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileH264Main).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let mut backend = VaapiBackend::::new( + Rc::clone(&display), + VAProfileH264Main, + fourcc, + Resolution { width: WIDTH, height: HEIGHT }, + libva::VA_RC_CBR, + low_power, + ) + .unwrap(); + + let mut surfaces = display + .create_surfaces( + VA_RT_FORMAT_YUV420, + Some(frame_layout.format.0 .0), + WIDTH, + HEIGHT, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .unwrap(); + + let surface = surfaces.pop().unwrap(); + + upload_test_frame_nv12(&display, &surface, 0.0); + + let input_meta = + FrameMetadata { layout: frame_layout, force_keyframe: false, timestamp: 0 }; + + let pic = backend.import_picture(&input_meta, surface).unwrap(); + + let sps = SpsBuilder::new() + .seq_parameter_set_id(0) + .profile_idc(Profile::Main) + .level_idc(Level::L4) + .resolution(WIDTH, HEIGHT) + .chroma_format_idc(3) + .frame_mbs_only_flag(true) + .direct_8x8_inference_flag(true) + .max_num_ref_frames(1) + .max_frame_num(32) + .pic_order_cnt_type(0) + .max_pic_order_cnt_lsb(128) + .delta_pic_order_always_zero_flag(false) + .bit_depth_chroma(8) + .bit_depth_luma(8) + .sar_resolution(1, 1) + .build(); + + let pps = PpsBuilder::new(Rc::clone(&sps)) + .pic_parameter_set_id(0) + .pic_init_qp_minus26(0) + .deblocking_filter_control_present_flag(true) + .build(); + + let header = SliceHeaderBuilder::new(&pps) + .slice_type(SliceType::I) + .first_mb_in_slice(0) + .idr_pic_id(0) + .build(); + + let dpb_entry_meta = + DpbEntryMeta { poc: 0, frame_num: 0, is_reference: IsReference::ShortTerm }; + + let request = BackendRequest { + sps: Rc::clone(&sps), + pps: Rc::clone(&pps), + header, + dpb_meta: dpb_entry_meta, + input: pic, + input_meta, + ref_list_0: vec![], + ref_list_1: vec![], + intra_period: 1, + ip_period: 0, + num_macroblocks: (WIDTH * HEIGHT) as usize / (16 * 16), + is_idr: true, + tunings: Tunings { + rate_control: RateControl::ConstantBitrate(30_000), + ..Default::default() + }, + coded_output: vec![], + }; + + let (_, output) = backend.encode_slice(request).unwrap(); + let output = output.sync().unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + + use crate::codec::h264::synthesizer::Synthesizer; + let mut out = std::fs::File::create("test_simple_encode_slice.h264").unwrap(); + + Synthesizer::<'_, Sps, &mut std::fs::File>::synthesize(3, &sps, &mut out, true) + .unwrap(); + Synthesizer::<'_, Pps, &mut std::fs::File>::synthesize(3, &pps, &mut out, true) + .unwrap(); + out.write_all(&output).unwrap(); + out.flush().unwrap(); + } + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_vaapi_encoder() { + type VaapiH264Encoder<'l> = + StatelessEncoder, VaapiBackend<(), PooledVaSurface<()>>>; + + const WIDTH: usize = 512; + const HEIGHT: usize = 512; + + let _ = env_logger::try_init(); + + let display = libva::Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileH264Main).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let config = EncoderConfig { + profile: Profile::Main, + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(1_200_000), + framerate: 30, + ..Default::default() + }, + ..Default::default() + }; + + let frame_layout = FrameLayout { + format: (b"NV12".into(), 0), + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, + ], + }; + + let mut encoder = VaapiH264Encoder::new_vaapi( + Rc::clone(&display), + config, + frame_layout.format.0, + frame_layout.size, + low_power, + BlockingMode::Blocking, + ) + .unwrap(); + + let mut pool = VaSurfacePool::new( + Rc::clone(&display), + VA_RT_FORMAT_YUV420, + Some(UsageHint::USAGE_HINT_ENCODER), + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + ); + + pool.add_frames(vec![(); 16]).unwrap(); + + let mut frame_producer = TestFrameGenerator::new(100, display, pool, frame_layout); + + let mut bitstream = Vec::new(); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + bitstream.extend(coded.bitstream) + }) + .unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_vaapi_encoder.h264").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/predictor.rs b/vendor/cros-codecs/src/encoder/stateless/predictor.rs new file mode 100644 index 0000000..1dddf18 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/predictor.rs @@ -0,0 +1,346 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::collections::VecDeque; +use std::rc::Rc; + +use crate::encoder::stateless::Predictor; +use crate::encoder::EncodeError; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::Tunings; + +/// Implementation of [`LowDelay`] prediction structure. See [`LowDelay`] for details. +/// +/// [`LowDelay`]: crate::encoder::PredictionStructure::LowDelay +pub(crate) struct LowDelay { + /// Pending frames for encoding + pub(super) queue: VecDeque<(Picture, FrameMetadata)>, + + /// Availabe frames for references + pub(super) references: VecDeque>, + + /// Current frame counter + pub(super) counter: usize, + + /// The number of frames between intra frames + pub(super) limit: u16, + + /// Codec specific delegate. Holds codec specific state. Is also used to differentiate + /// [`LowDelay`] implementations between codecs. + pub(super) delegate: Delegate, + + /// Currently set tunings for the stream + pub(super) tunings: Tunings, + + /// Pending [`Tunings`] to be applied with `counter` value when to set them. + /// In this way we ensure that the requested frames prior tuning request are encoded using + /// previous tunings. This is especially important for bitrate, this way we ensure the bitrate + /// changes when requested. + pub(super) tunings_queue: VecDeque<(usize, Tunings)>, + + pub(super) _phantom: std::marker::PhantomData, +} + +/// Helper trait enabling forcing [`LowDelay`] to implement codec specific functions. +pub(crate) trait LowDelayDelegate { + /// Creates keyframe or IDR request for the codec backend + fn request_keyframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + idr: bool, + ) -> EncodeResult; + + /// Creates interframe request for the codec backend + fn request_interframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + ) -> EncodeResult; + + /// Checks if the `_tunings` can be applied + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { + Err(EncodeError::Unsupported) + } + + /// Applies `_tunings` + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { + Err(EncodeError::Unsupported) + } +} + +impl LowDelay +where + Self: LowDelayDelegate, +{ + fn pop_tunings(&mut self) -> EncodeResult<()> { + while let Some((when_counter, _)) = self.tunings_queue.front() { + if self.counter < *when_counter { + log::trace!( + "Pending tuning skipped counter={} scheduled={}", + self.counter, + when_counter + ); + break; + } + + // SAFETY: checked in loop condition + let (_, tunings) = self.tunings_queue.pop_front().unwrap(); + log::info!("Applying tuning {tunings:?}"); + self.apply_tunings(&tunings)?; + self.tunings = tunings; + } + + Ok(()) + } + + fn next_request(&mut self) -> EncodeResult> { + log::trace!("Pending frames in the queue: {}", self.queue.len()); + + let mut requests = Vec::new(); + while let Some((input, meta)) = self.queue.pop_front() { + self.pop_tunings()?; + + if self.counter == 0 || meta.force_keyframe { + log::trace!("Requesting keyframe/IDR for timestamp={}", meta.timestamp); + // If first frame in the sequence or forced IDR then clear references and create + // keyframe request. + // TODO: Maybe don't clear references on just keyframe (!= IDR) + self.references.clear(); + + let request = self.request_keyframe(input, meta, self.counter == 0)?; + + requests.push(request); + self.counter = self.counter.wrapping_add(1) % (self.limit as usize); + } else if self.references.is_empty() { + log::trace!("Awaiting more reconstructed frames"); + // There is no enough frames reconstructed + self.queue.push_front((input, meta)); + break; + } else { + log::trace!("Requesting interframe for timestamp={}", meta.timestamp); + let request = self.request_interframe(input, meta)?; + + requests.push(request); + self.counter = self.counter.wrapping_add(1) % (self.limit as usize); + + break; + } + } + + Ok(requests) + } +} + +impl Predictor + for LowDelay +where + Self: LowDelayDelegate, +{ + fn new_frame( + &mut self, + input: Picture, + frame_metadata: FrameMetadata, + ) -> EncodeResult> { + log::trace!("New frame added to queue timestamp={}", frame_metadata.timestamp); + // Add new frame in the request queue and request new encoding if possible + self.queue.push_back((input, frame_metadata)); + self.next_request() + } + + fn reconstructed(&mut self, reference: Reference) -> EncodeResult> { + log::trace!("A frame was reconstructed"); + // Add new reconstructed surface and request next encoding if possible + self.references.push_back(Rc::new(reference)); + self.next_request() + } + + fn tune(&mut self, tunings: Tunings) -> EncodeResult<()> { + log::trace!("Tuning requested with {tunings:?}"); + if !RateControl::is_same_variant(&self.tunings.rate_control, &tunings.rate_control) { + // TODO(bgrzesik): consider enabling switching between RateControl variants + log::error!("Changing RateControl variant is not supported at the moment"); + return Err(EncodeError::Unsupported); + } + + // Check if the tunings are or will be the same, in such case we skip. + let skip = match self.tunings_queue.front() { + Some((_, preceeding_tunnings)) if preceeding_tunnings == &tunings => true, + None if self.tunings == tunings => true, + _ => false, + }; + + if skip { + log::debug!("Tuning skipped, the requested values are the same."); + return Ok(()); + } + + // Check if applying tunings will succeed. + self.try_tunings(&tunings)?; + + let when_counter = self.counter + self.queue.len(); + self.tunings_queue.push_back((when_counter, tunings)); + + Ok(()) + } + + fn drain(&mut self) -> EncodeResult> { + // [`LowDelay`] will not hold any frames, therefore the drain function shall never be called. + Err(EncodeError::InvalidInternalState) + } +} + +#[cfg(test)] +mod tests { + use crate::Fourcc; + + use super::*; + + #[derive(Debug, PartialEq, Eq)] + enum MockRequest { + KeyFrameRequest(u32, Tunings), + InterframerRequest(u32, Tunings), + } + + struct MockDelegate; + + impl LowDelayDelegate for LowDelay { + fn request_interframe( + &mut self, + input: u32, + _input_meta: FrameMetadata, + ) -> EncodeResult { + Ok(MockRequest::InterframerRequest(input, self.tunings.clone())) + } + + fn request_keyframe( + &mut self, + input: u32, + _input_meta: FrameMetadata, + _idr: bool, + ) -> EncodeResult { + Ok(MockRequest::KeyFrameRequest(input, self.tunings.clone())) + } + + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } + + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } + } + + fn dummy_frame_meta(timestamp: u64, force_keyframe: bool) -> FrameMetadata { + FrameMetadata { + timestamp, + layout: crate::FrameLayout { + format: (Fourcc::from(b"NV12"), 0), + size: crate::Resolution { width: 0, height: 0 }, + planes: vec![], + }, + force_keyframe, + } + } + + /// This test ensures that Tunings change applies to only frames following the change + #[test] + fn test_tuning_delay() { + let _ = env_logger::try_init(); + + let tunings_prev = Tunings { framerate: 1, ..Default::default() }; + + let mut predictor: LowDelay = LowDelay { + queue: Default::default(), + references: Default::default(), + counter: 0, + limit: 1028, + delegate: MockDelegate, + tunings: tunings_prev.clone(), + tunings_queue: Default::default(), + _phantom: Default::default(), + }; + + let mut requests = Vec::new(); + + requests.extend(predictor.new_frame(0, dummy_frame_meta(0, false)).unwrap()); + requests.extend(predictor.new_frame(1, dummy_frame_meta(1, false)).unwrap()); + requests.extend(predictor.new_frame(2, dummy_frame_meta(2, false)).unwrap()); + requests.extend(predictor.new_frame(3, dummy_frame_meta(3, false)).unwrap()); + + let tunings_next = Tunings { framerate: 2, ..Default::default() }; + + predictor.tune(tunings_next.clone()).unwrap(); + + assert_eq!(predictor.tunings, tunings_prev); + + requests.extend(predictor.new_frame(4, dummy_frame_meta(4, false)).unwrap()); + + requests.extend(predictor.reconstructed(0).unwrap()); + requests.extend(predictor.reconstructed(1).unwrap()); + requests.extend(predictor.reconstructed(2).unwrap()); + + assert_eq!(predictor.tunings, tunings_prev); + requests.extend(predictor.reconstructed(3).unwrap()); + + assert_eq!(predictor.tunings, tunings_next); + requests.extend(predictor.reconstructed(4).unwrap()); + + assert_eq!( + requests, + vec![ + MockRequest::KeyFrameRequest(0, tunings_prev.clone()), + MockRequest::InterframerRequest(1, tunings_prev.clone()), + MockRequest::InterframerRequest(2, tunings_prev.clone()), + MockRequest::InterframerRequest(3, tunings_prev.clone()), + MockRequest::InterframerRequest(4, tunings_next.clone()), + ] + ); + } + + #[test] + fn test_keyframes() { + const FRAME_COUNT: u32 = 1028; + const IDR_PERIOD: u16 = 37; + const KEYFRAME_REQUEST_PERIOD: u32 = 31; + + let _ = env_logger::try_init(); + + let tunings = Tunings::default(); + let mut predictor: LowDelay = LowDelay { + queue: Default::default(), + references: Default::default(), + counter: 0, + limit: IDR_PERIOD, + delegate: MockDelegate, + tunings: tunings.clone(), + tunings_queue: Default::default(), + _phantom: Default::default(), + }; + + let mut requests = Vec::new(); + + for i in 0..FRAME_COUNT { + let keyframe = i % KEYFRAME_REQUEST_PERIOD == 0; + requests.extend(predictor.new_frame(i, dummy_frame_meta(i as u64, keyframe)).unwrap()); + } + + for i in 0..FRAME_COUNT { + requests.extend(predictor.reconstructed(i).unwrap()); + } + + let mut expected = Vec::new(); + for i in 0..FRAME_COUNT { + if (i % IDR_PERIOD as u32 == 0) || (i % KEYFRAME_REQUEST_PERIOD) == 0 { + expected.push(MockRequest::KeyFrameRequest(i, tunings.clone())); + } else { + expected.push(MockRequest::InterframerRequest(i, tunings.clone())); + } + } + + assert_eq!(requests, expected); + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/vp9.rs b/vendor/cros-codecs/src/encoder/stateless/vp9.rs new file mode 100644 index 0000000..ae5309f --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/vp9.rs @@ -0,0 +1,122 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::codec::vp9::parser::Header; +use crate::encoder::stateless::vp9::predictor::LowDelayVP9; +use crate::encoder::stateless::BitstreamPromise; +use crate::encoder::stateless::Predictor; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessCodec; +use crate::encoder::stateless::StatelessEncoderExecute; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::vp9::EncoderConfig; +use crate::encoder::vp9::VP9; +use crate::encoder::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::BlockingMode; + +mod predictor; + +#[cfg(feature = "vaapi")] +pub mod vaapi; + +/// Determines how reference frame shall be used +pub enum ReferenceUse { + /// The frame will be used for single prediction + Single, + /// The frame will be used for compound prediction + Compound, + /// The frame will be used for both single and compound prediction + Hybrid, +} + +pub struct BackendRequest { + header: Header, + + /// Input frame to be encoded + input: P, + + /// Input frame metadata + input_meta: FrameMetadata, + + /// Reference frames + last_frame_ref: Option<(Rc, ReferenceUse)>, + golden_frame_ref: Option<(Rc, ReferenceUse)>, + altref_frame_ref: Option<(Rc, ReferenceUse)>, + + /// [`Tunings`] for the frame + tunings: Tunings, + + /// Container for the request output. [`StatelessVP9EncoderBackend`] impl shall move it and + /// append the slice data to it. This prevents unnecessary copying of bitstream around. + coded_output: Vec, +} + +impl StatelessCodec for VP9 +where + Backend: StatelessVideoEncoderBackend, +{ + type Reference = Backend::Reconstructed; + + type Request = BackendRequest; + + type CodedPromise = BitstreamPromise; + + type ReferencePromise = Backend::ReconPromise; +} + +pub trait StatelessVP9EncoderBackend: StatelessVideoEncoderBackend { + fn encode_frame( + &mut self, + request: BackendRequest, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)>; +} + +pub type StatelessEncoder = + crate::encoder::stateless::StatelessEncoder; + +impl StatelessEncoderExecute + for StatelessEncoder +where + Backend: StatelessVP9EncoderBackend, +{ + fn execute( + &mut self, + request: BackendRequest, + ) -> EncodeResult<()> { + let meta = request.input_meta.clone(); + + // The [`BackendRequest`] has a frame from predictor. Decresing internal counter. + self.predictor_frame_count -= 1; + + log::trace!("submitting new request"); + let (recon, bitstream) = self.backend.encode_frame(request)?; + + // Wrap promise from backend with headers and metadata + let slice_promise = BitstreamPromise { bitstream, meta }; + + self.output_queue.add_promise(slice_promise); + + self.recon_queue.add_promise(recon); + + Ok(()) + } +} + +impl StatelessEncoder +where + Backend: StatelessVP9EncoderBackend, +{ + fn new_vp9(backend: Backend, config: EncoderConfig, mode: BlockingMode) -> EncodeResult { + let predictor: Box> = match config.pred_structure { + PredictionStructure::LowDelay { limit } => Box::new(LowDelayVP9::new(config, limit)), + }; + + Self::new(backend, mode, predictor) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/vp9/predictor.rs b/vendor/cros-codecs/src/encoder/stateless/vp9/predictor.rs new file mode 100644 index 0000000..a051ac5 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/vp9/predictor.rs @@ -0,0 +1,138 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use super::BackendRequest; +use super::EncoderConfig; +use crate::codec::vp9::parser::BitDepth; +use crate::codec::vp9::parser::FrameType; +use crate::codec::vp9::parser::Header; +use crate::codec::vp9::parser::Profile; +use crate::codec::vp9::parser::QuantizationParams; +use crate::encoder::stateless::predictor::LowDelay; +use crate::encoder::stateless::predictor::LowDelayDelegate; +use crate::encoder::stateless::vp9::ReferenceUse; +use crate::encoder::stateless::EncodeResult; +use crate::encoder::FrameMetadata; +use crate::encoder::RateControl; +use crate::encoder::Tunings; + +pub(crate) const MIN_Q_IDX: u8 = 0; +pub(crate) const MAX_Q_IDX: u8 = 255; + +pub(crate) struct LowDelayVP9Delegate { + config: EncoderConfig, +} + +pub(crate) type LowDelayVP9 = + LowDelay>; + +impl LowDelayVP9 { + pub(super) fn new(config: EncoderConfig, limit: u16) -> Self { + Self { + queue: Default::default(), + references: Default::default(), + counter: 0, + limit, + tunings: config.initial_tunings.clone(), + delegate: LowDelayVP9Delegate { config }, + tunings_queue: Default::default(), + _phantom: Default::default(), + } + } + + fn create_frame_header(&mut self, frame_type: FrameType) -> Header { + let width = self.delegate.config.resolution.width; + let height = self.delegate.config.resolution.height; + + let profile = match self.delegate.config.bit_depth { + BitDepth::Depth8 => Profile::Profile0, + BitDepth::Depth10 | BitDepth::Depth12 => Profile::Profile2, + }; + + let base_q_idx = if let RateControl::ConstantQuality(base_q_idx) = self.tunings.rate_control + { + // Limit Q index to valid values + base_q_idx.clamp(MIN_Q_IDX as u32, MAX_Q_IDX as u32) as u8 + } else { + // Pick middle Q index + (MAX_Q_IDX + MIN_Q_IDX) / 2 + }; + + Header { + profile, + bit_depth: BitDepth::Depth10, + frame_type, + show_frame: true, + error_resilient_mode: true, + width, + height, + render_and_frame_size_different: false, + intra_only: matches!(frame_type, FrameType::KeyFrame), + refresh_frame_flags: 0x01, + ref_frame_idx: [0, 0, 0], + quant: QuantizationParams { base_q_idx, ..Default::default() }, + + ..Default::default() + } + } +} + +impl LowDelayDelegate> + for LowDelayVP9 +{ + fn request_keyframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + _idr: bool, + ) -> EncodeResult> { + log::trace!("Requested keyframe timestamp={}", input_meta.timestamp); + + let request = BackendRequest { + header: self.create_frame_header(FrameType::KeyFrame), + input, + input_meta, + last_frame_ref: None, + golden_frame_ref: None, + altref_frame_ref: None, + tunings: self.tunings.clone(), + coded_output: Vec::new(), + }; + + Ok(request) + } + + fn request_interframe( + &mut self, + input: Picture, + input_meta: FrameMetadata, + ) -> EncodeResult> { + log::trace!("Requested interframe timestamp={}", input_meta.timestamp); + + let ref_frame = self.references.pop_front().unwrap(); + + let request = BackendRequest { + header: self.create_frame_header(FrameType::InterFrame), + input, + input_meta, + last_frame_ref: Some((ref_frame, ReferenceUse::Single)), + golden_frame_ref: None, + altref_frame_ref: None, + tunings: self.tunings.clone(), + coded_output: Vec::new(), + }; + + self.references.clear(); + + Ok(request) + } + + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } + + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { + Ok(()) + } +} diff --git a/vendor/cros-codecs/src/encoder/stateless/vp9/vaapi.rs b/vendor/cros-codecs/src/encoder/stateless/vp9/vaapi.rs new file mode 100644 index 0000000..16f7cf4 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/stateless/vp9/vaapi.rs @@ -0,0 +1,602 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::any::Any; +use std::borrow::Borrow; +use std::rc::Rc; + +use anyhow::Context; +use libva::BufferType; +use libva::Display; +use libva::EncPictureParameter; +use libva::EncPictureParameterBufferVP9; +use libva::EncSequenceParameter; +use libva::EncSequenceParameterBufferVP9; +use libva::Picture; +use libva::Surface; +use libva::SurfaceMemoryDescriptor; +use libva::VAProfile::VAProfileVP9Profile0; +use libva::VAProfile::VAProfileVP9Profile2; +use libva::VP9EncPicFlags; +use libva::VP9EncRefFlags; +use libva::VA_INVALID_SURFACE; + +use crate::backend::vaapi::encoder::tunings_to_libva_rc; +use crate::backend::vaapi::encoder::CodedOutputPromise; +use crate::backend::vaapi::encoder::Reconstructed; +use crate::backend::vaapi::encoder::VaapiBackend; +use crate::codec::vp9::parser::BitDepth; +use crate::codec::vp9::parser::FrameType; +use crate::codec::vp9::parser::InterpolationFilter; +use crate::codec::vp9::parser::ALTREF_FRAME; +use crate::codec::vp9::parser::GOLDEN_FRAME; +use crate::codec::vp9::parser::LAST_FRAME; +use crate::codec::vp9::parser::NUM_REF_FRAMES; +use crate::encoder::stateless::vp9::predictor::MAX_Q_IDX; +use crate::encoder::stateless::vp9::predictor::MIN_Q_IDX; +use crate::encoder::stateless::vp9::BackendRequest; +use crate::encoder::stateless::vp9::ReferenceUse; +use crate::encoder::stateless::vp9::StatelessEncoder; +use crate::encoder::stateless::vp9::StatelessVP9EncoderBackend; +use crate::encoder::stateless::ReadyPromise; +use crate::encoder::stateless::StatelessBackendResult; +use crate::encoder::stateless::StatelessVideoEncoderBackend; +use crate::encoder::vp9::EncoderConfig; +use crate::encoder::vp9::VP9; +use crate::encoder::EncodeResult; +use crate::encoder::RateControl; +use crate::video_frame::VideoFrame; +use crate::BlockingMode; +use crate::Fourcc; +use crate::Resolution; + +impl StatelessVideoEncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + Handle: Borrow>, +{ + type Picture = Handle; + type Reconstructed = Reconstructed; + type CodedPromise = CodedOutputPromise; + type ReconPromise = ReadyPromise; +} + +impl StatelessVP9EncoderBackend for VaapiBackend +where + M: SurfaceMemoryDescriptor, + Handle: Borrow>, +{ + fn encode_frame( + &mut self, + request: BackendRequest, + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)> { + let coded_buf = self.new_coded_buffer(&request.tunings.rate_control)?; + let recon = self.new_scratch_picture()?; + + // Use bitrate from RateControl or ask driver to ignore + let bits_per_second = request.tunings.rate_control.bitrate_target().unwrap_or(0) as u32; + + let seq_param = BufferType::EncSequenceParameter(EncSequenceParameter::VP9( + EncSequenceParameterBufferVP9::new( + request.input_meta.layout.size.width, + request.input_meta.layout.size.height, + 0, + 10, + 2000, + bits_per_second, + 1024, + ), + )); + + // From va_enc_vp9.h `ref_frame_ctrl_l0` documentation + const LAST_FRAME_AS_REF: u32 = 0x01; + const GOLDEN_FRAME_AS_REF: u32 = 0x02; + const ALTREF_FRAME_AS_REF: u32 = 0x04; + + let mut references = Vec::>::new(); + let mut reference_frames = [VA_INVALID_SURFACE; NUM_REF_FRAMES]; + + let mut ref_frame_ctrl_l0 = 0; + let mut ref_frame_ctrl_l1 = 0; + + let refs = [ + (&request.last_frame_ref, LAST_FRAME - 1, LAST_FRAME_AS_REF), + (&request.golden_frame_ref, GOLDEN_FRAME - 1, GOLDEN_FRAME_AS_REF), + (&request.altref_frame_ref, ALTREF_FRAME - 1, ALTREF_FRAME_AS_REF), + ]; + + for (r, ref_idx, ref_ctrl) in refs { + let Some((ref_frame, ref_use)) = r else { + continue; + }; + + reference_frames[request.header.ref_frame_idx[ref_idx] as usize] = + ref_frame.surface_id(); + references.push(ref_frame.clone()); + + match ref_use { + ReferenceUse::Single => ref_frame_ctrl_l0 |= ref_ctrl, + ReferenceUse::Compound => ref_frame_ctrl_l1 |= ref_ctrl, + ReferenceUse::Hybrid => { + ref_frame_ctrl_l0 |= ref_ctrl; + ref_frame_ctrl_l1 |= ref_ctrl; + } + } + } + + let force_kf = + request.header.frame_type == FrameType::KeyFrame || request.input_meta.force_keyframe; + + let ref_flags = VP9EncRefFlags::new( + // Force keyframe if requested + force_kf as u32, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + request.header.ref_frame_idx[LAST_FRAME - 1] as u32, + request.header.ref_frame_sign_bias[LAST_FRAME] as u32, + request.header.ref_frame_idx[GOLDEN_FRAME - 1] as u32, + request.header.ref_frame_sign_bias[GOLDEN_FRAME] as u32, + request.header.ref_frame_idx[ALTREF_FRAME - 1] as u32, + request.header.ref_frame_sign_bias[ALTREF_FRAME] as u32, + 0, + ); + + // From va_enc_vp9.h `mcomp_filter_type` documentation + let mcomp_filter_type = match request.header.interpolation_filter { + InterpolationFilter::EightTap => 0, + InterpolationFilter::EightTapSmooth => 1, + InterpolationFilter::EightTapSharp => 2, + InterpolationFilter::Bilinear => 3, + InterpolationFilter::Switchable => 4, + }; + + // TODO: show_existing_frame + assert!(!request.header.show_existing_frame); + + // From va_enc_vp9.h `comp_prediction_mode` documentation + const PRED_MODE_SINGLE: u32 = 0x00; + // const PRED_MODE_COMPOUND: u32 = 0x01; + const PRED_MODE_HYBRID: u32 = 0x02; + + let comp_prediction_mode = if ref_frame_ctrl_l1 != 0 { + // Use hybrid prediction mode if any future reference frame are enabled + PRED_MODE_HYBRID + } else { + PRED_MODE_SINGLE + }; + + let pic_flags = VP9EncPicFlags::new( + request.header.frame_type as u32, + request.header.show_frame as u32, + request.header.error_resilient_mode as u32, + request.header.intra_only as u32, + request.header.allow_high_precision_mv as u32, + mcomp_filter_type, + request.header.frame_parallel_decoding_mode as u32, + request.header.reset_frame_context as u32, + request.header.refresh_frame_context as u32, + request.header.frame_context_idx as u32, + request.header.seg.enabled as u32, + request.header.seg.temporal_update as u32, + request.header.seg.update_map as u32, + request.header.lossless as u32, + comp_prediction_mode, + 1, + 0, + ); + + let pic_param = BufferType::EncPictureParameter(EncPictureParameter::VP9( + EncPictureParameterBufferVP9::new( + request.header.width, + request.header.height, + request.header.render_width, + request.header.render_height, + recon.surface_id(), + reference_frames, + coded_buf.id(), + &ref_flags, + &pic_flags, + request.header.refresh_frame_flags, + request.header.quant.base_q_idx, + request.header.quant.delta_q_y_dc, + request.header.quant.delta_q_uv_ac, + request.header.quant.delta_q_uv_dc, + request.header.lf.level, + request.header.lf.sharpness, + request.header.lf.ref_deltas, + request.header.lf.mode_deltas, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + request.header.tile_rows_log2, + request.header.tile_cols_log2, + // Don't skip frames + 0, + 0, + 0, + ), + )); + + let rc_param = + tunings_to_libva_rc::<{ MIN_Q_IDX as u32 }, { MAX_Q_IDX as u32 }>(&request.tunings)?; + let rc_param = + libva::BufferType::EncMiscParameter(libva::EncMiscParameter::RateControl(rc_param)); + + let mut picture = + Picture::new(request.input_meta.timestamp, Rc::clone(self.context()), request.input); + + let framerate_param = BufferType::EncMiscParameter(libva::EncMiscParameter::FrameRate( + libva::EncMiscParameterFrameRate::new(request.tunings.framerate, 0), + )); + + picture.add_buffer(self.context().create_buffer(seq_param)?); + picture.add_buffer(self.context().create_buffer(pic_param)?); + picture.add_buffer(self.context().create_buffer(rc_param)?); + picture.add_buffer(self.context().create_buffer(framerate_param)?); + + // Start processing the picture encoding + let picture = picture.begin().context("picture begin")?; + let picture = picture.render().context("picture render")?; + let picture = picture.end().context("picture end")?; + + // libva will handle the synchronization of reconstructed surface with implicit fences. + // Therefore return the reconstructed frame immediately. + let reference_promise = ReadyPromise::from(recon); + + let bitstream_promise = + CodedOutputPromise::new(picture, references, coded_buf, request.coded_output); + + Ok((reference_promise, bitstream_promise)) + } +} + +impl StatelessEncoder>> { + pub fn new_vaapi( + display: Rc, + config: EncoderConfig, + fourcc: Fourcc, + coded_size: Resolution, + low_power: bool, + blocking_mode: BlockingMode, + ) -> EncodeResult { + let bitrate_control = match config.initial_tunings.rate_control { + RateControl::ConstantBitrate(_) => libva::VA_RC_CBR, + RateControl::ConstantQuality(_) => libva::VA_RC_CQP, + }; + + let va_profile = match config.bit_depth { + BitDepth::Depth8 => VAProfileVP9Profile0, + BitDepth::Depth10 | BitDepth::Depth12 => VAProfileVP9Profile2, + }; + + let backend = + VaapiBackend::new(display, va_profile, fourcc, coded_size, bitrate_control, low_power)?; + Self::new_vp9(backend, config, blocking_mode) + } +} + +#[cfg(test)] +pub(super) mod tests { + use std::rc::Rc; + + use libva::Display; + use libva::UsageHint; + use libva::VAEntrypoint::VAEntrypointEncSliceLP; + use libva::VA_RT_FORMAT_YUV420; + use libva::VA_RT_FORMAT_YUV420_10; + + use super::*; + use crate::backend::vaapi::encoder::tests::upload_test_frame_nv12; + use crate::backend::vaapi::encoder::tests::TestFrameGenerator; + use crate::backend::vaapi::encoder::VaapiBackend; + use crate::backend::vaapi::surface_pool::PooledVaSurface; + use crate::backend::vaapi::surface_pool::VaSurfacePool; + use crate::bitstream_utils::IvfFileHeader; + use crate::bitstream_utils::IvfFrameHeader; + use crate::codec::vp9::parser::Header; + use crate::decoder::FramePool; + use crate::encoder::simple_encode_loop; + use crate::encoder::stateless::vp9::BackendRequest; + use crate::encoder::stateless::vp9::EncoderConfig; + use crate::encoder::stateless::vp9::StatelessEncoder; + use crate::encoder::stateless::BackendPromise; + use crate::encoder::stateless::StatelessEncoderBackendImport; + use crate::encoder::FrameMetadata; + use crate::encoder::Tunings; + use crate::FrameLayout; + use crate::PlaneLayout; + use crate::Resolution; + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_simple_encode_frame() { + type Descriptor = (); + type Surface = libva::Surface; + const WIDTH: u32 = 256; + const HEIGHT: u32 = 256; + let fourcc = b"NV12".into(); + + let frame_layout = FrameLayout { + format: (fourcc, 0), + size: Resolution { width: WIDTH, height: HEIGHT }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH as usize }, + PlaneLayout { + buffer_index: 0, + offset: (WIDTH * HEIGHT) as usize, + stride: WIDTH as usize, + }, + ], + }; + + let display = Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileVP9Profile0).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let mut backend = VaapiBackend::::new( + Rc::clone(&display), + VAProfileVP9Profile0, + fourcc, + Resolution { width: WIDTH, height: HEIGHT }, + libva::VA_RC_CBR, + low_power, + ) + .unwrap(); + + let mut surfaces = display + .create_surfaces( + VA_RT_FORMAT_YUV420, + Some(frame_layout.format.0 .0), + WIDTH, + HEIGHT, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .unwrap(); + + let surface = surfaces.pop().unwrap(); + + upload_test_frame_nv12(&display, &surface, 0.0); + + let input_meta = + FrameMetadata { layout: frame_layout, force_keyframe: false, timestamp: 0 }; + + let pic = backend.import_picture(&input_meta, surface).unwrap(); + + let header = Header { + frame_type: FrameType::KeyFrame, + show_frame: true, + error_resilient_mode: false, + width: WIDTH, + height: HEIGHT, + render_and_frame_size_different: false, + render_width: WIDTH, + render_height: HEIGHT, + intra_only: true, + refresh_frame_flags: 0x01, + ref_frame_idx: [0, 0, 0], + + ..Default::default() + }; + + let request = BackendRequest { + header, + input: pic, + input_meta, + last_frame_ref: None, + golden_frame_ref: None, + altref_frame_ref: None, + tunings: Tunings { + rate_control: RateControl::ConstantBitrate(30_000), + ..Default::default() + }, + coded_output: Vec::new(), + }; + + let (_, output) = backend.encode_frame(request).unwrap(); + let output = output.sync().unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + + let mut out = std::fs::File::create("test_simple_encode_frame.vp9.ivf").unwrap(); + + let file_header = + IvfFileHeader::new(IvfFileHeader::CODEC_VP9, WIDTH as u16, HEIGHT as u16, 30, 1); + + let frame_header = IvfFrameHeader { frame_size: output.len() as u32, timestamp: 0 }; + + file_header.writo_into(&mut out).unwrap(); + frame_header.writo_into(&mut out).unwrap(); + + out.write_all(&output).unwrap(); + out.flush().unwrap(); + } + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_vaapi_encoder() { + type VaapiVp9Encoder<'l> = + StatelessEncoder, VaapiBackend<(), PooledVaSurface<()>>>; + + const WIDTH: usize = 512; + const HEIGHT: usize = 512; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let display = libva::Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileVP9Profile0).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let config = EncoderConfig { + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(200_000), + framerate: 30, + ..Default::default() + }, + ..Default::default() + }; + + let frame_layout = FrameLayout { + format: (b"NV12".into(), 0), + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, + ], + }; + + let mut encoder = VaapiVp9Encoder::new_vaapi( + Rc::clone(&display), + config, + frame_layout.format.0, + frame_layout.size, + low_power, + BlockingMode::Blocking, + ) + .unwrap(); + + let mut pool = VaSurfacePool::new( + Rc::clone(&display), + VA_RT_FORMAT_YUV420, + Some(UsageHint::USAGE_HINT_ENCODER), + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + ); + + pool.add_frames(vec![(); 16]).unwrap(); + + let mut frame_producer = TestFrameGenerator::new(FRAME_COUNT, display, pool, frame_layout); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP9, + WIDTH as u16, + HEIGHT as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }) + .unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_vaapi_encoder.vp9.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn test_vaapi_encoder_p010() { + type VaapiVp9Encoder<'l> = + StatelessEncoder, VaapiBackend<(), PooledVaSurface<()>>>; + + const WIDTH: usize = 512; + const HEIGHT: usize = 512; + const FRAME_COUNT: u64 = 100; + + let _ = env_logger::try_init(); + + let display = libva::Display::open().unwrap(); + let entrypoints = display.query_config_entrypoints(VAProfileVP9Profile2).unwrap(); + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); + + let config = EncoderConfig { + bit_depth: BitDepth::Depth10, + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(200_000), + framerate: 30, + ..Default::default() + }, + ..Default::default() + }; + + let frame_layout = FrameLayout { + format: (b"P010".into(), 0), + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, + ], + }; + + let mut encoder = VaapiVp9Encoder::new_vaapi( + Rc::clone(&display), + config, + frame_layout.format.0, + frame_layout.size, + low_power, + BlockingMode::Blocking, + ) + .unwrap(); + + let mut pool = VaSurfacePool::new( + Rc::clone(&display), + VA_RT_FORMAT_YUV420_10, + Some(UsageHint::USAGE_HINT_ENCODER), + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, + ); + + pool.add_frames(vec![(); 16]).unwrap(); + + let mut frame_producer = TestFrameGenerator::new(FRAME_COUNT, display, pool, frame_layout); + + let mut bitstream = Vec::new(); + + let file_header = IvfFileHeader::new( + IvfFileHeader::CODEC_VP9, + WIDTH as u16, + HEIGHT as u16, + 30, + FRAME_COUNT as u32, + ); + + file_header.writo_into(&mut bitstream).unwrap(); + + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { + let header = IvfFrameHeader { + timestamp: coded.metadata.timestamp, + frame_size: coded.bitstream.len() as u32, + }; + + header.writo_into(&mut bitstream).unwrap(); + bitstream.extend(coded.bitstream); + }) + .unwrap(); + + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); + if write_to_file { + use std::io::Write; + let mut out = std::fs::File::create("test_vaapi_encoder_p010.vp9.ivf").unwrap(); + out.write_all(&bitstream).unwrap(); + out.flush().unwrap(); + } + } +} diff --git a/vendor/cros-codecs/src/encoder/vp8.rs b/vendor/cros-codecs/src/encoder/vp8.rs new file mode 100644 index 0000000..f9a197f --- /dev/null +++ b/vendor/cros-codecs/src/encoder/vp8.rs @@ -0,0 +1,24 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::encoder::PredictionStructure; +use crate::Resolution; + +pub struct VP8; + +#[derive(Clone)] +pub struct EncoderConfig { + pub resolution: Resolution, + pub pred_structure: PredictionStructure, +} + +impl Default for EncoderConfig { + fn default() -> Self { + // Artificially encoder configuration with intent to be widely supported. + Self { + resolution: Resolution { width: 320, height: 240 }, + pred_structure: PredictionStructure::LowDelay { limit: 2048 }, + } + } +} diff --git a/vendor/cros-codecs/src/encoder/vp9.rs b/vendor/cros-codecs/src/encoder/vp9.rs new file mode 100644 index 0000000..2de2569 --- /dev/null +++ b/vendor/cros-codecs/src/encoder/vp9.rs @@ -0,0 +1,31 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// +use crate::codec::vp9::parser::BitDepth; +use crate::encoder::PredictionStructure; +use crate::encoder::Tunings; +use crate::Resolution; + +pub struct VP9; + +#[derive(Clone)] +pub struct EncoderConfig { + pub bit_depth: BitDepth, + pub resolution: Resolution, + pub pred_structure: PredictionStructure, + /// Initial tunings values + pub initial_tunings: Tunings, +} + +impl Default for EncoderConfig { + fn default() -> Self { + // Artificially encoder configuration with intent to be widely supported. + Self { + bit_depth: BitDepth::Depth8, + resolution: Resolution { width: 320, height: 240 }, + pred_structure: PredictionStructure::LowDelay { limit: 2048 }, + initial_tunings: Default::default(), + } + } +} diff --git a/vendor/cros-codecs/src/image_processing.rs b/vendor/cros-codecs/src/image_processing.rs new file mode 100644 index 0000000..0aec258 --- /dev/null +++ b/vendor/cros-codecs/src/image_processing.rs @@ -0,0 +1,551 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cmp::min; + +use crate::video_frame::{VideoFrame, UV_PLANE, U_PLANE, V_PLANE, Y_PLANE}; +use crate::DecodedFormat; + +/// TODO(greenjustin): This entire file should be replaced with LibYUV. +use byteorder::ByteOrder; +use byteorder::LittleEndian; + +#[cfg(feature = "v4l2")] +use std::arch::aarch64::*; + +pub const MM21_TILE_WIDTH: usize = 16; +pub const MM21_TILE_HEIGHT: usize = 32; + +/// Copies `src` into `dst` as NV12, handling padding. +pub fn nv12_copy( + src_y: &[u8], + src_y_stride: usize, + dst_y: &mut [u8], + dst_y_stride: usize, + src_uv: &[u8], + src_uv_stride: usize, + dst_uv: &mut [u8], + dst_uv_stride: usize, + width: usize, + height: usize, +) { + for y in 0..height { + dst_y[(y * dst_y_stride)..(y * dst_y_stride + width)] + .copy_from_slice(&src_y[(y * src_y_stride)..(y * src_y_stride + width)]); + } + for y in 0..(height / 2) { + dst_uv[(y * dst_uv_stride)..(y * dst_uv_stride + width)] + .copy_from_slice(&src_uv[(y * src_uv_stride)..(y * src_uv_stride + width)]); + } +} + +/// Replace 0 padding with the last pixels of the real image. This helps reduce compression +/// artifacts caused by the sharp transition between real image data and 0. +pub fn extend_border_nv12( + y_plane: &mut [u8], + uv_plane: &mut [u8], + visible_width: usize, + visible_height: usize, + coded_width: usize, + coded_height: usize, +) { + assert!(visible_width > 1); + assert!(visible_height > 1); + for y in 0..visible_height { + let row_start = y * coded_width; + for x in visible_width..coded_width { + y_plane[row_start + x] = y_plane[row_start + x - 1] + } + } + for y in visible_height..coded_height { + let (src, dst) = y_plane.split_at_mut(y * coded_width); + dst[0..coded_width].copy_from_slice(&src[((y - 1) * coded_width)..(y * coded_width)]); + } + for y in 0..(visible_height / 2) { + let row_start = y * coded_width; + for x in visible_width..coded_width { + // We use minus 2 here because we want to actually repeat the last 2 UV values. + uv_plane[row_start + x] = uv_plane[row_start + x - 2] + } + } + for y in (visible_height / 2)..(coded_height / 2) { + let (src, dst) = uv_plane.split_at_mut(y * coded_width); + dst[0..coded_width].copy_from_slice(&src[((y - 1) * coded_width)..(y * coded_width)]); + } +} + +pub fn copy_plane( + src: &[u8], + src_stride: usize, + dst: &mut [u8], + dst_stride: usize, + width: usize, + height: usize, +) { + for y in 0..height { + dst[(y * dst_stride)..(y * dst_stride + width)] + .copy_from_slice(&src[(y * src_stride)..(y * src_stride + width)]); + } +} + +/// Copies `src` into `dst` as I4xx (YUV tri-planar). +/// +/// `sub_h` and `sub_v` enable horizontal and vertical sub-sampling, respectively. E.g, if both +/// `sub_h` and `sub_v` are `true` the data will be `4:2:0`, if only `sub_v` is `true` then it will be +/// `4:2:2`, and if both are `false` then we have `4:4:4`. +pub fn i4xx_copy( + src_y: &[u8], + src_y_stride: usize, + dst_y: &mut [u8], + dst_y_stride: usize, + src_u: &[u8], + src_u_stride: usize, + dst_u: &mut [u8], + dst_u_stride: usize, + src_v: &[u8], + src_v_stride: usize, + dst_v: &mut [u8], + dst_v_stride: usize, + width: usize, + height: usize, + (sub_h, sub_v): (bool, bool), +) { + copy_plane(src_y, src_y_stride, dst_y, dst_y_stride, width, height); + + // Align width and height of UV planes to 2 if sub-sampling is used. + let uv_width = if sub_h { (width + 1) / 2 } else { width }; + let uv_height = if sub_v { (height + 1) / 2 } else { height }; + + copy_plane(src_u, src_u_stride, dst_u, dst_u_stride, uv_width, uv_height); + copy_plane(src_v, src_v_stride, dst_v, dst_v_stride, uv_width, uv_height); +} + +/// Copies `src` into `dst` as I410, removing all padding and changing the layout from packed to +/// triplanar. Also drops the alpha channel. +pub fn y410_to_i410( + src: &[u8], + dst: &mut [u8], + width: usize, + height: usize, + strides: [usize; 3], + offsets: [usize; 3], +) { + let src_lines = src[offsets[0]..].chunks(strides[0]).map(|line| &line[..width * 4]); + + let dst_y_size = width * 2 * height; + let dst_u_size = width * 2 * height; + + let (dst_y_plane, dst_uv_planes) = dst.split_at_mut(dst_y_size); + let (dst_u_plane, dst_v_plane) = dst_uv_planes.split_at_mut(dst_u_size); + let dst_y_lines = dst_y_plane.chunks_mut(width * 2); + let dst_u_lines = dst_u_plane.chunks_mut(width * 2); + let dst_v_lines = dst_v_plane.chunks_mut(width * 2); + + for (src_line, (dst_y_line, (dst_u_line, dst_v_line))) in + src_lines.zip(dst_y_lines.zip(dst_u_lines.zip(dst_v_lines))).take(height) + { + for (src, (dst_y, (dst_u, dst_v))) in src_line.chunks(4).zip( + dst_y_line.chunks_mut(2).zip(dst_u_line.chunks_mut(2).zip(dst_v_line.chunks_mut(2))), + ) { + let y = LittleEndian::read_u16(&[src[1] >> 2 | src[2] << 6, src[2] >> 2 & 0b11]); + let u = LittleEndian::read_u16(&[src[0], src[1] & 0b11]); + let v = LittleEndian::read_u16(&[src[2] >> 4 | src[3] << 4, src[3] >> 4 & 0b11]); + LittleEndian::write_u16(dst_y, y); + LittleEndian::write_u16(dst_u, u); + LittleEndian::write_u16(dst_v, v); + } + } +} + +#[cfg(feature = "v4l2")] +// SAFETY: Verified by caller that |src| and |dst| is valid and not +// a NULL-pointer or invalid memory. +pub unsafe fn align_detile(src: *const u8, src_tile_stride: isize, dst: *mut u8, width: usize) { + let mut vin = [0u8; MM21_TILE_WIDTH]; + let mut vout = [0u8; MM21_TILE_WIDTH]; + + let bytes_per_pixel = 1; + let mask = MM21_TILE_WIDTH - 1; + + let remainder = width & mask; + let width_aligned_down = width & !mask; + if width_aligned_down > 0 { + detile_row(src, src_tile_stride, dst, width_aligned_down); + } + + let index = (width_aligned_down / MM21_TILE_WIDTH * (src_tile_stride as usize)) as usize; + let input_slice = + std::slice::from_raw_parts(src.offset(index as isize), remainder * bytes_per_pixel); + (&mut vin[0..remainder * bytes_per_pixel]) + .copy_from_slice(&input_slice[0..remainder * bytes_per_pixel]); + + detile_row(vin.as_ptr(), src_tile_stride, vout.as_mut_ptr(), MM21_TILE_WIDTH); + + let output_slice = std::slice::from_raw_parts_mut( + dst.offset(width_aligned_down as isize), + remainder * bytes_per_pixel, + ); + output_slice[0..remainder * bytes_per_pixel] + .copy_from_slice(&vout[0..remainder * bytes_per_pixel]); +} + +#[cfg(feature = "v4l2")] +// SAFETY: Verified by caller that |src| and |dst| is valid and not +// a NULL-pointer or invalid memory. +pub unsafe fn detile_row( + mut src: *const u8, + src_tile_stride: isize, + mut dst: *mut u8, + width: usize, +) { + let mut w = width; + while w > 0 { + let v0: uint8x16_t = vld1q_u8(src); + src = src.offset(src_tile_stride as isize); + w = w - MM21_TILE_WIDTH; + vst1q_u8(dst, v0); + dst = dst.offset(MM21_TILE_WIDTH as isize); + } +} + +// TODO(bchoobineh): Use a fuzzer to verify the correctness of this SIMD +// code compared to its Rust equivalent +// Detiles a plane of data using implementation from LibYUV::DetilePlane. +#[cfg(feature = "v4l2")] +pub fn detile_plane( + src: &[u8], + src_stride: usize, + dst: &mut [u8], + mut dst_stride: isize, + width: usize, + mut height: isize, + tile_height: usize, +) -> Result<(), String> { + let src_tile_stride = (16 * tile_height) as isize; + + if width == 0 || height == 0 || (((tile_height) & ((tile_height) - 1)) > 0) { + return Err("Invalid width, height, or tile height is not a power of 2.".to_owned()); + } + + let mut aligned = true; + if (width & (MM21_TILE_WIDTH - 1)) > 0 { + aligned = false; + } + + if src.len() < (src_stride * (height.abs() as usize)) { + return Err("Src buffer not big enough.".to_owned()); + } + + if dst.len() < (dst_stride * height.abs()) as usize { + return Err("Dst buffer not big enough.".to_owned()); + } + + let mut src_ptr = src.as_ptr(); + let mut dst_ptr = dst.as_mut_ptr(); + + // Image inversion + if height < 0 { + height = -height; + // SAFETY: Verified the validity of src buffer and height. + unsafe { + src_ptr = src_ptr.offset(((height - 1) * dst_stride) as isize); + } + dst_stride = -dst_stride; + } + + // Detile Plane + for y in 0..height { + // SAFETY: Verified validity of src and dst pointers. + unsafe { + if aligned { + detile_row(src_ptr, src_tile_stride, dst_ptr, width); + } else { + align_detile(src_ptr, src_tile_stride, dst_ptr, width); + } + } + + // SAFETY: Verified the validity of the src and dst buffers. + unsafe { + dst_ptr = dst_ptr.offset(dst_stride as isize); + src_ptr = src_ptr.offset(MM21_TILE_WIDTH as isize); + } + // Advance to next row of tiles. + if (y & (tile_height - 1) as isize) == ((tile_height - 1) as isize) { + // SAFETY: Verified validity of the src buffers. + unsafe { + src_ptr = src_ptr.offset(-src_tile_stride + (src_stride * tile_height) as isize); + } + } + } + + Ok(()) +} + +// Converts MM21 to NV12 using the implementation from LibYUV::MM21ToNV12. +#[cfg(feature = "v4l2")] +pub fn mm21_to_nv12( + src_y: &[u8], + src_stride_y: usize, + dst_y: &mut [u8], + dst_stride_y: usize, + src_uv: &[u8], + src_stride_uv: usize, + dst_uv: &mut [u8], + dst_stride_uv: usize, + width: usize, + height: isize, +) -> Result<(), String> { + if width <= 0 { + return Err("Width must be greater than 0.".to_owned()); + } + + let sign = if height < 0 { -1 } else { 1 }; + + // Detile Plane Y + detile_plane( + src_y, + src_stride_y, + dst_y, + dst_stride_y as isize, + width, + height, + MM21_TILE_HEIGHT, + )?; + + // Detile Plane UV + detile_plane( + src_uv, + src_stride_uv, + dst_uv, + dst_stride_uv as isize, + (width + 1) & !1, + (height + sign) / 2, + MM21_TILE_HEIGHT / 2, + ) +} + +pub fn nv12_to_i420( + src_y: &[u8], + src_y_stride: usize, + dst_y: &mut [u8], + dst_y_stride: usize, + src_uv: &[u8], + src_uv_stride: usize, + dst_u: &mut [u8], + dst_u_stride: usize, + dst_v: &mut [u8], + dst_v_stride: usize, + width: usize, + height: usize, +) { + copy_plane(src_y, src_y_stride, dst_y, dst_y_stride, width, height); + + // We can just assume 4:2:0 subsampling + let aligned_width = (width + 1) & (!1); + for y in 0..((height + 1) / 2) { + let src_row = &src_uv[(y * src_uv_stride)..(y * src_uv_stride + aligned_width)]; + let dst_u_row = &mut dst_u[(y * dst_u_stride)..(y * dst_u_stride + aligned_width / 2)]; + let dst_v_row = &mut dst_v[(y * dst_v_stride)..(y * dst_v_stride + aligned_width / 2)]; + for x in 0..aligned_width { + if x % 2 == 0 { + dst_u_row[x / 2] = src_row[x]; + } else { + dst_v_row[x / 2] = src_row[x]; + } + } + } +} + +pub fn i420_to_nv12_chroma(src_u: &[u8], src_v: &[u8], dst_uv: &mut [u8]) { + for i in 0..dst_uv.len() { + if i % 2 == 0 { + dst_uv[i] = src_u[i / 2]; + } else { + dst_uv[i] = src_v[i / 2]; + } + } +} + +pub fn i420_to_nv12(src_y: &[u8], dst_y: &mut [u8], src_u: &[u8], src_v: &[u8], dst_uv: &mut [u8]) { + dst_y.copy_from_slice(src_y); + i420_to_nv12_chroma(src_u, src_v, dst_uv); +} + +// TODO: Add more conversions. All supported conversion functions need to take stride parameters. +pub const SUPPORTED_CONVERSION: &'static [(DecodedFormat, DecodedFormat)] = &[ + #[cfg(feature = "v4l2")] + (DecodedFormat::MM21, DecodedFormat::NV12), + (DecodedFormat::NV12, DecodedFormat::NV12), + (DecodedFormat::I420, DecodedFormat::I420), + (DecodedFormat::I422, DecodedFormat::I422), + (DecodedFormat::I444, DecodedFormat::I444), +]; + +pub fn convert_video_frame(src: &impl VideoFrame, dst: &mut impl VideoFrame) -> Result<(), String> { + let width = min(dst.resolution().width, src.resolution().width) as usize; + let height = min(dst.resolution().height, src.resolution().height) as usize; + + let conversion = (src.decoded_format()?, dst.decoded_format()?); + let src_pitches = src.get_plane_pitch(); + let src_mapping = src.map().expect("Image processor src mapping failed!"); + let src_planes = src_mapping.get(); + let dst_pitches = dst.get_plane_pitch(); + let dst_mapping = dst.map_mut().expect("Image processor dst mapping failed!"); + let dst_planes = dst_mapping.get(); + match conversion { + #[cfg(feature = "v4l2")] + (DecodedFormat::MM21, DecodedFormat::NV12) => mm21_to_nv12( + src_planes[Y_PLANE], + src_pitches[Y_PLANE], + *dst_planes[Y_PLANE].borrow_mut(), + dst_pitches[Y_PLANE], + src_planes[UV_PLANE], + src_pitches[UV_PLANE], + *dst_planes[UV_PLANE].borrow_mut(), + dst_pitches[UV_PLANE], + width, + height as isize, + ), + (DecodedFormat::NV12, DecodedFormat::NV12) => { + nv12_copy( + src_planes[Y_PLANE], + src_pitches[Y_PLANE], + *dst_planes[Y_PLANE].borrow_mut(), + dst_pitches[Y_PLANE], + src_planes[UV_PLANE], + src_pitches[UV_PLANE], + *dst_planes[UV_PLANE].borrow_mut(), + dst_pitches[UV_PLANE], + width, + height, + ); + Ok(()) + } + (DecodedFormat::I420, DecodedFormat::I420) => { + i4xx_copy( + src_planes[Y_PLANE], + src_pitches[Y_PLANE], + *dst_planes[Y_PLANE].borrow_mut(), + dst_pitches[Y_PLANE], + src_planes[U_PLANE], + src_pitches[U_PLANE], + *dst_planes[U_PLANE].borrow_mut(), + dst_pitches[U_PLANE], + src_planes[V_PLANE], + src_pitches[V_PLANE], + *dst_planes[V_PLANE].borrow_mut(), + dst_pitches[V_PLANE], + width, + height, + (true, true), + ); + Ok(()) + } + (DecodedFormat::I422, DecodedFormat::I422) => { + i4xx_copy( + src_planes[Y_PLANE], + src_pitches[Y_PLANE], + *dst_planes[Y_PLANE].borrow_mut(), + dst_pitches[Y_PLANE], + src_planes[U_PLANE], + src_pitches[U_PLANE], + *dst_planes[U_PLANE].borrow_mut(), + dst_pitches[U_PLANE], + src_planes[V_PLANE], + src_pitches[V_PLANE], + *dst_planes[V_PLANE].borrow_mut(), + dst_pitches[V_PLANE], + width, + height, + (true, false), + ); + Ok(()) + } + (DecodedFormat::I444, DecodedFormat::I444) => { + i4xx_copy( + src_planes[Y_PLANE], + src_pitches[Y_PLANE], + *dst_planes[Y_PLANE].borrow_mut(), + dst_pitches[Y_PLANE], + src_planes[U_PLANE], + src_pitches[U_PLANE], + *dst_planes[U_PLANE].borrow_mut(), + dst_pitches[U_PLANE], + src_planes[V_PLANE], + src_pitches[V_PLANE], + *dst_planes[V_PLANE].borrow_mut(), + dst_pitches[V_PLANE], + width, + height, + (false, false), + ); + Ok(()) + } + _ => Err(format!("Unsupported conversion {:?} -> {:?}", conversion.0, conversion.1)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(feature = "v4l2")] + fn test_mm21_to_nv12() { + let test_input = include_bytes!("test_data/puppets-480x270_20230825.mm21.yuv"); + let test_expected_output = include_bytes!("test_data/puppets-480x270_20230825.nv12.yuv"); + + let mut test_output = [0u8; 480 * 288 * 3 / 2]; + let (test_y_output, test_uv_output) = test_output.split_at_mut(480 * 288); + mm21_to_nv12( + &test_input[0..480 * 288], + 480, + test_y_output, + 480, + &test_input[480 * 288..480 * 288 * 3 / 2], + 480, + test_uv_output, + 480, + 480, + 288, + ) + .expect("Failed to detile!"); + assert_eq!(test_output, *test_expected_output); + } + + #[test] + fn test_nv12_to_i420() { + let test_input = include_bytes!("test_data/puppets-480x270_20230825.nv12.yuv"); + let test_expected_output = include_bytes!("test_data/puppets-480x270_20230825.i420.yuv"); + + let mut test_output = [0u8; 480 * 288 * 3 / 2]; + let (test_y_output, test_uv_output) = test_output.split_at_mut(480 * 288); + let (test_u_output, test_v_output) = test_uv_output.split_at_mut(480 * 288 / 4); + nv12_to_i420( + &test_input[0..480 * 288], + test_y_output, + &test_input[480 * 288..480 * 288 * 3 / 2], + test_u_output, + test_v_output, + ); + assert_eq!(test_output, *test_expected_output); + } + + #[test] + fn test_i420_to_nv12() { + let test_input = include_bytes!("test_data/puppets-480x270_20230825.i420.yuv"); + let test_expected_output = include_bytes!("test_data/puppets-480x270_20230825.nv12.yuv"); + + let mut test_output = [0u8; 480 * 288 * 3 / 2]; + let (test_y_output, test_uv_output) = test_output.split_at_mut(480 * 288); + i420_to_nv12( + &test_input[0..(480 * 288)], + test_y_output, + &test_input[(480 * 288)..(480 * 288 * 5 / 4)], + &test_input[(480 * 288 * 5 / 4)..(480 * 288 * 3 / 2)], + test_uv_output, + ); + assert_eq!(test_output, *test_expected_output); + } +} diff --git a/vendor/cros-codecs/src/lib.rs b/vendor/cros-codecs/src/lib.rs new file mode 100644 index 0000000..8b6860c --- /dev/null +++ b/vendor/cros-codecs/src/lib.rs @@ -0,0 +1,463 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// LOCAL PATCH: vendored verbatim, so its warnings are upstream's business and +// would otherwise drown out this workspace's own. +#![allow(warnings)] + +//! This crate provides tools to help decode and encode various video codecs, leveraging the +//! hardware acceleration available on the target. +//! +//! The [codec] module contains tools to parse encoded video streams like H.264 or VP9 and extract +//! the information useful in order to perform e.g. hardware-accelerated decoding. +//! +//! The [backend] module contains common backend code. A backend is a provider of some way to +//! decode or encode a particular codec, like VAAPI. +//! +//! The [decoder] module contains decoders that can turn an encoded video stream into a sequence of +//! decoded frames using the hardware acceleration available on the host. +//! +//! The [encoder] module contains encoder that can turn a picture sequence into a compressed +//! sequence of decodable encoded packets using the hardware acceleration available on the host. +//! +//! The [utils] module contains some useful code that is shared between different parts of this +//! crate and didn't fit any of the modules above. + +pub mod bitstream_utils; +pub mod codec; + +#[cfg(feature = "backend")] +pub mod backend; +#[cfg(feature = "backend")] +pub mod c2_wrapper; +#[cfg(feature = "backend")] +pub mod decoder; +#[cfg(feature = "v4l2")] +pub mod device; +#[cfg(feature = "backend")] +pub mod encoder; +#[cfg(feature = "backend")] +pub mod image_processing; +#[cfg(feature = "backend")] +pub mod utils; +#[cfg(feature = "backend")] +pub mod video_frame; + +use std::str::FromStr; + +#[cfg(feature = "vaapi")] +pub use libva; +#[cfg(feature = "v4l2")] +pub use v4l2r; + +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +pub enum FrameMemoryType { + Managed, + Prime, + User, +} + +impl FromStr for FrameMemoryType { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + match s { + "managed" => Ok(FrameMemoryType::Managed), + "prime" => Ok(FrameMemoryType::Prime), + "user" => Ok(FrameMemoryType::User), + _ => Err("unrecognized memory type. Valid values: managed, prime, user"), + } + } +} + +/// Rounding modes for `Resolution` +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ResolutionRoundMode { + /// Rounds component-wise to the next even value. + Even, +} + +/// A frame resolution in pixels. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct Resolution { + pub width: u32, + pub height: u32, +} + +impl Resolution { + /// Whether `self` can contain `other`. + pub fn can_contain(&self, other: Self) -> bool { + self.width >= other.width && self.height >= other.height + } + + /// Rounds `self` according to `rnd_mode`. + pub fn round(mut self, rnd_mode: ResolutionRoundMode) -> Self { + match rnd_mode { + ResolutionRoundMode::Even => { + if self.width % 2 != 0 { + self.width += 1; + } + + if self.height % 2 != 0 { + self.height += 1; + } + } + } + + self + } + + pub fn get_area(&self) -> usize { + (self.width as usize) * (self.height as usize) + } +} + +impl From<(u32, u32)> for Resolution { + fn from(value: (u32, u32)) -> Self { + Self { width: value.0, height: value.1 } + } +} + +impl From for (u32, u32) { + fn from(value: Resolution) -> Self { + (value.width, value.height) + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + +impl From for Resolution { + fn from(value: Rect) -> Self { + Self { width: value.width - value.x, height: value.height - value.y } + } +} + +impl From for Rect { + fn from(value: Resolution) -> Self { + Self { x: 0, y: 0, width: value.width, height: value.height } + } +} + +impl From<((u32, u32), (u32, u32))> for Rect { + fn from(value: ((u32, u32), (u32, u32))) -> Self { + Self { x: value.0 .0, y: value.0 .1, width: value.1 .0, height: value.1 .1 } + } +} +/// Wrapper around u32 when they are meant to be a fourcc. +/// +/// Provides conversion and display/debug implementations useful when dealing with fourcc codes. +#[derive(Clone, Copy, Default, PartialEq)] +pub struct Fourcc(u32); + +impl From for Fourcc { + fn from(fourcc: u32) -> Self { + Self(fourcc) + } +} + +impl From for u32 { + fn from(fourcc: Fourcc) -> Self { + fourcc.0 + } +} + +impl From<&[u8; 4]> for Fourcc { + fn from(n: &[u8; 4]) -> Self { + Self(n[0] as u32 | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24) + } +} + +impl From for [u8; 4] { + fn from(n: Fourcc) -> Self { + [n.0 as u8, (n.0 >> 8) as u8, (n.0 >> 16) as u8, (n.0 >> 24) as u8] + } +} + +impl std::fmt::Display for Fourcc { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let c: [u8; 4] = (*self).into(); + + f.write_fmt(format_args!( + "{}{}{}{}", + c[0] as char, c[1] as char, c[2] as char, c[3] as char + )) + } +} + +impl std::fmt::Debug for Fourcc { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("0x{:08x} ({})", self.0, self)) + } +} + +/// Formats that buffers can be mapped into for the CPU to read. +/// +/// The conventions here largely follow these of libyuv. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum DecodedFormat { + /// Y, U and V planes, 4:2:0 sampling, 8 bits per sample. + I420, + /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample. + NV12, + /// Y, U and V planes, 4:2:2 sampling, 8 bits per sample. + I422, + /// Y, U and V planes, 4:4:4 sampling, 8 bits per sample. + I444, + /// Y, U and V planes, 4:2:0 sampling, 16 bits per sample, LE. Only the 10 LSBs are used. + I010, + /// Y, U and V planes, 4:2:0 sampling, 16 bits per sample, LE. Only the 12 LSBs are used. + I012, + /// Y, U and V planes, 4:2:2 sampling, 16 bits per sample, LE. Only the 10 LSBs are used. + I210, + /// Y, U and V planes, 4:2:2 sampling, 16 bits per sample, LE. Only the 12 LSBs are used. + I212, + /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 10 LSBs are used. + I410, + /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used. + I412, + /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample. + /// In a tiled format. + MM21, +} + +impl FromStr for DecodedFormat { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + match s { + "i420" | "I420" => Ok(DecodedFormat::I420), + "i422" | "I422" => Ok(DecodedFormat::I422), + "i444" | "I444" => Ok(DecodedFormat::I444), + "nv12" | "NV12" => Ok(DecodedFormat::NV12), + "i010" | "I010" => Ok(DecodedFormat::I010), + "i012" | "I012" => Ok(DecodedFormat::I012), + "i210" | "I210" => Ok(DecodedFormat::I210), + "i212" | "I212" => Ok(DecodedFormat::I212), + "i410" | "I410" => Ok(DecodedFormat::I410), + "i412" | "I412" => Ok(DecodedFormat::I412), + "mm21" | "MM21" => Ok(DecodedFormat::MM21), + _ => Err("unrecognized output format. \ + Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"), + } + } +} + +impl From for DecodedFormat { + fn from(fourcc: Fourcc) -> DecodedFormat { + match fourcc.to_string().as_str() { + "I420" => DecodedFormat::I420, + "NV12" | "NM12" => DecodedFormat::NV12, + "MM21" => DecodedFormat::MM21, + _ => todo!("Fourcc {} not yet supported", fourcc), + } + } +} + +impl From for Fourcc { + fn from(format: DecodedFormat) -> Fourcc { + match format { + DecodedFormat::I420 => Fourcc::from(b"I420"), + DecodedFormat::NV12 => Fourcc::from(b"NV12"), + DecodedFormat::MM21 => Fourcc::from(b"MM21"), + _ => todo!(), + } + } +} + +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +pub enum EncodedFormat { + H264, + H265, + VP8, + VP9, + AV1, +} + +impl FromStr for EncodedFormat { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + match s { + "h264" | "H264" => Ok(EncodedFormat::H264), + "h265" | "H265" => Ok(EncodedFormat::H265), + "vp8" | "VP8" => Ok(EncodedFormat::VP8), + "vp9" | "VP9" => Ok(EncodedFormat::VP9), + "av1" | "AV1" => Ok(EncodedFormat::AV1), + _ => Err("unrecognized input format. Valid values: h264, h265, vp8, vp9, av1"), + } + } +} + +impl From for EncodedFormat { + fn from(fourcc: Fourcc) -> EncodedFormat { + match fourcc.to_string().as_str() { + "H264" => EncodedFormat::H264, + "HEVC" => EncodedFormat::H265, + "VP80" => EncodedFormat::VP8, + "VP90" => EncodedFormat::VP9, + "AV1F" => EncodedFormat::AV1, + _ => todo!("Fourcc {} not yet supported", fourcc), + } + } +} + +impl From for Fourcc { + fn from(format: EncodedFormat) -> Fourcc { + match format { + EncodedFormat::H264 => Fourcc::from(b"H264"), + EncodedFormat::H265 => Fourcc::from(b"HEVC"), + EncodedFormat::VP8 => Fourcc::from(b"VP80"), + EncodedFormat::VP9 => Fourcc::from(b"VP90"), + EncodedFormat::AV1 => Fourcc::from(b"AV1F"), + } + } +} + +/// Describes the layout of a plane within a frame. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct PlaneLayout { + /// Index of the memory buffer the plane belongs to. + pub buffer_index: usize, + /// Start offset of the plane within its buffer. + pub offset: usize, + /// Distance in bytes between two lines of data in this plane. + pub stride: usize, +} + +/// Unambiguously describes the layout of a frame. +/// +/// A frame can be made of one or several memory buffers, each containing one or several planes. +/// For a given frame, this structure defines where each plane can be found. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct FrameLayout { + /// `(Fourcc, modifier)` tuple describing the arrangement of the planes. + /// + /// This member is enough to infer how many planes and buffers the frame has, and which + /// buffer each plane belongs into. + pub format: (Fourcc, u64), + /// Size in pixels of the frame. + pub size: Resolution, + /// Layout of each individual plane. + pub planes: Vec, +} + +/// Build a frame memory descriptor enum that supports multiple descriptor types. +/// +/// This is useful for the case where the frames' memory backing is not decided at compile-time. +/// In this case, this macro can be used to list all the potential types supported at run-time, and +/// the selected one can be built as the program is run. +/// +/// # Example +/// +/// +/// use cros_codecs::multiple_desc_type; +/// use cros_codecs::utils::DmabufFrame; +/// +/// /// Frames' memory can be provided either by the backend, or via PRIME DMABUF handles. +/// multiple_desc_type! { +/// enum OwnedOrDmaDescriptor { +/// Owned(()), +/// Dmabuf(DmabufFrame), +/// } +/// } +/// +#[macro_export] +macro_rules! multiple_desc_type { + (enum $s:ident { $($v:ident($t:ty),)* } ) => { + pub enum $s { + $($v($t),)* + } + + #[cfg(feature = "vaapi")] + impl libva::SurfaceMemoryDescriptor for $s { + fn add_attrs(&mut self, attrs: &mut Vec) -> Option> { + match self { + $($s::$v(desc) => desc.add_attrs(attrs),)* + } + } + } + } +} + +/// Returns the size required to store a frame of `format` with size `width`x`height`, without any +/// padding. This is the minimum size of the destination buffer passed to `nv12_copy` or +/// `i420_copy`. +pub fn decoded_frame_size(format: DecodedFormat, width: usize, height: usize) -> usize { + match format { + DecodedFormat::I420 | DecodedFormat::NV12 => { + let u_size = width * height; + // U and V planes need to be aligned to 2. + let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2; + + u_size + uv_size + } + DecodedFormat::I422 => { + let u_size = width * height; + // U and V planes need to be aligned to 2. + let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2; + + u_size + uv_size + } + DecodedFormat::I444 => (width * height) * 3, + DecodedFormat::I010 | DecodedFormat::I012 => { + decoded_frame_size(DecodedFormat::I420, width, height) * 2 + } + DecodedFormat::I210 | DecodedFormat::I212 => { + let u_size = width * height * 2; + // U and V planes need to be aligned to 2. + let uv_size = ((width + 1) / 2) * ((height + 1) / 2) * 2 * 2; + + u_size + uv_size + } + DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3, + DecodedFormat::MM21 => panic!("Unable to convert to MM21"), + } +} + +/// Instructs on whether it should block on the operation(s). +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +pub enum BlockingMode { + Blocking, + #[default] + NonBlocking, +} + +#[cfg(test)] +mod tests { + use super::Fourcc; + + const NV12_FOURCC: u32 = 0x3231564E; + + #[test] + fn fourcc_u32() { + let fourcc = Fourcc::from(NV12_FOURCC); + let value: u32 = fourcc.into(); + assert_eq!(value, NV12_FOURCC); + } + + #[test] + fn fourcc_u8_4() { + let fourcc = Fourcc::from(NV12_FOURCC); + let value: [u8; 4] = fourcc.into(); + assert_eq!(value, *b"NV12"); + } + + #[test] + fn fourcc_display() { + let fourcc = Fourcc::from(NV12_FOURCC); + assert_eq!(fourcc.to_string(), "NV12"); + } + + #[test] + fn fourcc_debug() { + let fourcc = Fourcc::from(NV12_FOURCC); + assert_eq!(format!("{:?}", fourcc), "0x3231564e (NV12)"); + } +} diff --git a/vendor/cros-codecs/src/utils.rs b/vendor/cros-codecs/src/utils.rs new file mode 100644 index 0000000..c6f3f02 --- /dev/null +++ b/vendor/cros-codecs/src/utils.rs @@ -0,0 +1,117 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Utility functions used by several parts of this crate. +//! +//! This module is for anything that doesn't fit into the other top-level modules. Try not to add +//! new code here unless it really doesn't belong anywhere else. + +use std::marker::Copy; +use std::ops::Add; +use std::ops::Div; +use std::ops::Mul; +use std::ops::Sub; +use std::os::fd::OwnedFd; + +use crate::Fourcc; +use crate::FrameLayout; +use crate::PlaneLayout; +use crate::Resolution; + +pub fn align_up(x: T, alignment: T) -> T +where + T: Add + Sub + Div + Mul + From + Copy, +{ + ((x + alignment - T::from(1)) / alignment) * alignment +} + +// This is the formula we use to approximate the maximum compressed buffer size for a video frame. +pub fn buffer_size_for_area(width: u32, height: u32) -> u32 { + let area = width * height; + let mut buffer_size: u32 = 1024 * 1024; + + if area > 720 * 480 { + buffer_size *= 2; + } + if area > 1920 * 1080 { + buffer_size *= 2; + } + buffer_size +} + +/// A structure that holds user-allocated memory for a frame as well as its layout. +#[derive(Debug)] +pub struct UserPtrFrame { + pub buffers: Vec<*mut u8>, + pub mem_layout: std::alloc::Layout, + pub layout: FrameLayout, +} + +impl UserPtrFrame { + /// Allocate enough memory to back a NV12 frame of `size` dimension. + pub fn new_nv12(size: Resolution) -> Self { + /// Add what is needed to a value in order to make it a multiple of some alignment. + macro_rules! align { + ($n:expr, $r:expr) => { + ($n + ($r - 1)) & !($r - 1) + }; + } + + // Align according to VAAPI constraints. + let width = align!(size.width, 16) as usize; + let height = align!(size.height, 4) as usize; + let stride = align!(width, 64); + let uv_start = height * stride; + let uv_size = (height / 2) * stride; + + Self::alloc( + FrameLayout { + format: (Fourcc::from(b"NV12"), 0), + size: Resolution::from((width as u32, height as u32)), + planes: vec![ + PlaneLayout { buffer_index: 0, offset: 0, stride }, + PlaneLayout { buffer_index: 0, offset: uv_start, stride }, + ], + }, + uv_start.max(uv_size), + ) + } + + pub fn alloc(layout: FrameLayout, buffer_size: usize) -> Self { + let buffer_count = layout + .planes + .iter() + .map(|plane| plane.buffer_index) + .collect::>() + .len(); + + // SAFETY: the invariants of `Layout` are respected. + let mem_layout = + unsafe { std::alloc::Layout::from_size_align_unchecked(buffer_size, 4096) }; + + let buffers = (0..buffer_count) + .map(|_| { + // SAFETY: the invariants of `Layout` are respected. + unsafe { std::alloc::alloc(mem_layout) } + }) + .collect(); + + Self { buffers, mem_layout, layout } + } +} + +#[derive(Debug)] +pub struct DmabufFrame { + pub fds: Vec, + pub layout: FrameLayout, +} + +impl Drop for UserPtrFrame { + fn drop(&mut self) { + for buffer in std::mem::take(&mut self.buffers).into_iter() { + // Safe because we allocated the memory using `std::alloc::alloc`. + unsafe { std::alloc::dealloc(buffer, self.mem_layout) } + } + } +} diff --git a/vendor/cros-codecs/src/video_frame.rs b/vendor/cros-codecs/src/video_frame.rs new file mode 100644 index 0000000..2cd8a2b --- /dev/null +++ b/vendor/cros-codecs/src/video_frame.rs @@ -0,0 +1,311 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::fmt::Debug; +#[cfg(feature = "vaapi")] +use std::rc::Rc; +#[cfg(feature = "v4l2")] +use std::sync::Arc; + +use crate::utils::align_up; +use crate::DecodedFormat; +use crate::EncodedFormat; +use crate::Fourcc; +use crate::Resolution; + +pub mod frame_pool; +#[cfg(feature = "backend")] +pub mod gbm_video_frame; +#[cfg(feature = "backend")] +pub mod generic_dma_video_frame; +#[cfg(feature = "v4l2")] +pub mod v4l2_mmap_video_frame; + +#[cfg(feature = "vaapi")] +use libva::{Display, Surface, SurfaceMemoryDescriptor}; +#[cfg(feature = "v4l2")] +use v4l2r::bindings::v4l2_plane; +#[cfg(feature = "v4l2")] +use v4l2r::device::Device; +#[cfg(feature = "v4l2")] +use v4l2r::ioctl::V4l2Buffer; +#[cfg(feature = "v4l2")] +use v4l2r::memory::{BufferHandles, Memory, MemoryType, PlaneHandle, PrimitiveBufferHandles}; +#[cfg(feature = "v4l2")] +use v4l2r::Format; + +pub const Y_PLANE: usize = 0; +pub const UV_PLANE: usize = 1; +pub const U_PLANE: usize = 1; +pub const V_PLANE: usize = 2; + +// RAII wrappers for video memory mappings. The Drop method should implement any necessary +// munmap()'ing and cache flushing. +pub trait ReadMapping<'a> { + fn get(&self) -> Vec<&[u8]>; +} + +pub trait WriteMapping<'a> { + fn get(&self) -> Vec>; +} + +// Rust doesn't allow type aliases in traits, so we use this stupid hack to accomplish effectively +// the same thing. +pub trait Equivalent: From + Into { + fn from_ref(value: &A) -> &Self; + fn into_ref(self: &Self) -> &A; +} + +impl Equivalent for A { + fn from_ref(value: &A) -> &Self { + value + } + fn into_ref(self: &Self) -> &A { + self + } +} + +// Unified abstraction for any kind of frame data that might be sent to the hardware. +pub trait VideoFrame: Send + Sync + Sized + Debug + 'static { + #[cfg(feature = "v4l2")] + type NativeHandle: PlaneHandle; + + #[cfg(feature = "vaapi")] + type MemDescriptor: SurfaceMemoryDescriptor; + #[cfg(feature = "vaapi")] + type NativeHandle: Equivalent>; + + fn fourcc(&self) -> Fourcc; + + // Outputs visible resolution. Use pitch and plane size for coded resolution calculations. + fn resolution(&self) -> Resolution; + + fn is_compressed(&self) -> bool { + match self.fourcc().to_string().as_str() { + "H264" | "HEVC" | "VP80" | "VP90" | "AV1F" => true, + _ => false, + } + } + + // Whether or not all the planes are in a contiguous memory allocation. For example, returns + // true for NV12 and false for NM12. + fn is_contiguous(&self) -> bool { + if self.is_compressed() { + return false; + } + + // TODO: Add more formats. + match self.fourcc().to_string().as_str() { + "MM21" | "NM12" => false, + _ => true, + } + } + + fn decoded_format(&self) -> Result { + if self.is_compressed() { + return Err("Cannot convert compressed format into decoded format".to_string()); + } + + Ok(DecodedFormat::from(self.fourcc())) + } + + fn encoded_format(&self) -> Result { + if !self.is_compressed() { + return Err("Cannot convert uncompressed format into encoded format".to_string()); + } + + Ok(EncodedFormat::from(self.fourcc())) + } + + fn num_planes(&self) -> usize { + if self.is_compressed() { + return 1; + } + + match self.decoded_format().unwrap() { + DecodedFormat::I420 + | DecodedFormat::I422 + | DecodedFormat::I444 + | DecodedFormat::I010 + | DecodedFormat::I012 + | DecodedFormat::I210 + | DecodedFormat::I212 + | DecodedFormat::I410 + | DecodedFormat::I412 => 3, + DecodedFormat::NV12 | DecodedFormat::MM21 => 2, + } + } + + fn get_horizontal_subsampling(&self) -> Vec { + let mut ret: Vec = vec![]; + for plane_idx in 0..self.num_planes() { + if self.is_compressed() { + ret.push(1); + } else { + ret.push(match self.decoded_format().unwrap() { + DecodedFormat::I420 + | DecodedFormat::NV12 + | DecodedFormat::I422 + | DecodedFormat::I010 + | DecodedFormat::I012 + | DecodedFormat::I210 + | DecodedFormat::I212 + | DecodedFormat::MM21 => { + if plane_idx == 0 { + 1 + } else { + 2 + } + } + DecodedFormat::I444 | DecodedFormat::I410 | DecodedFormat::I412 => 1, + }); + } + } + ret + } + + fn get_vertical_subsampling(&self) -> Vec { + let mut ret: Vec = vec![]; + for plane_idx in 0..self.num_planes() { + if self.is_compressed() { + ret.push(1); + } else { + ret.push(match self.decoded_format().unwrap() { + DecodedFormat::I420 + | DecodedFormat::NV12 + | DecodedFormat::I010 + | DecodedFormat::I012 + | DecodedFormat::MM21 => { + if plane_idx == 0 { + 1 + } else { + 2 + } + } + DecodedFormat::I422 + | DecodedFormat::I444 + | DecodedFormat::I210 + | DecodedFormat::I212 + | DecodedFormat::I410 + | DecodedFormat::I412 => 1, + }) + } + } + ret + } + + fn get_bytes_per_element(&self) -> Vec { + let mut ret: Vec = vec![]; + for plane_idx in 0..self.num_planes() { + if self.is_compressed() { + ret.push(1); + } else { + ret.push(match self.decoded_format().unwrap() { + DecodedFormat::I420 | DecodedFormat::I422 | DecodedFormat::I444 => 1, + DecodedFormat::I010 + | DecodedFormat::I012 + | DecodedFormat::I210 + | DecodedFormat::I212 + | DecodedFormat::I410 + | DecodedFormat::I412 => 2, + DecodedFormat::NV12 | DecodedFormat::MM21 => { + if plane_idx == 0 { + 1 + } else { + 2 + } + } + }) + } + } + ret + } + + fn get_plane_size(&self) -> Vec; + + // Pitch is measured in bytes while stride is measured in pixels. + fn get_plane_pitch(&self) -> Vec; + + fn validate_frame(&self) -> Result<(), String> { + if self.is_compressed() { + return Ok(()); + } + + let horizontal_subsampling = self.get_horizontal_subsampling(); + let vertical_subsampling = self.get_vertical_subsampling(); + let bytes_per_element = self.get_bytes_per_element(); + let plane_pitch = self.get_plane_pitch(); + let plane_size = self.get_plane_size(); + + for plane in 0..self.num_planes() { + let minimum_pitch = + align_up(self.resolution().width as usize, horizontal_subsampling[plane]) + * bytes_per_element[plane] + / horizontal_subsampling[plane]; + if plane_pitch[plane] < minimum_pitch { + return Err( + "Pitch of plane {plane} is insufficient to accomodate format!".to_string() + ); + } + let minimum_size = + align_up(self.resolution().height as usize, vertical_subsampling[plane]) + / vertical_subsampling[plane] + * plane_pitch[plane]; + if plane_size[plane] < minimum_size { + return Err( + "Size of plane {plane} is insufficient to accomodate format!".to_string() + ); + } + } + + Ok(()) + } + + fn map<'a>(&'a self) -> Result + 'a>, String>; + + fn map_mut<'a>(&'a mut self) -> Result + 'a>, String>; + + #[cfg(feature = "v4l2")] + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2_plane); + + #[cfg(feature = "v4l2")] + fn process_dqbuf(&mut self, device: Arc, format: &Format, buf: &V4l2Buffer); + + #[cfg(feature = "vaapi")] + fn to_native_handle(&self, display: &Rc) -> Result; +} + +// Rust has restrictions about implementing foreign types, so this is a stupid workaround to get +// VideoFrame to implement BufferHandles. +#[cfg(feature = "v4l2")] +#[derive(Debug)] +pub struct V4l2VideoFrame(pub V); + +#[cfg(feature = "v4l2")] +impl From for V4l2VideoFrame { + fn from(value: V) -> Self { + Self(value) + } +} + +#[cfg(feature = "v4l2")] +impl BufferHandles for V4l2VideoFrame { + type SupportedMemoryType = MemoryType; + + fn len(&self) -> usize { + self.0.num_planes() + } + + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2_plane) { + self.0.fill_v4l2_plane(index, plane) + } +} + +#[cfg(feature = "v4l2")] +impl PrimitiveBufferHandles for V4l2VideoFrame { + type HandleType = V::NativeHandle; + const MEMORY_TYPE: Self::SupportedMemoryType = + ::Memory::MEMORY_TYPE; +} diff --git a/vendor/cros-codecs/src/video_frame/frame_pool.rs b/vendor/cros-codecs/src/video_frame/frame_pool.rs new file mode 100644 index 0000000..b186b72 --- /dev/null +++ b/vendor/cros-codecs/src/video_frame/frame_pool.rs @@ -0,0 +1,115 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::collections::VecDeque; +#[cfg(feature = "vaapi")] +use std::rc::Rc; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::Weak; + +use crate::decoder::StreamInfo; +use crate::video_frame::ReadMapping; +use crate::video_frame::VideoFrame; +use crate::video_frame::WriteMapping; +use crate::Fourcc; +use crate::Resolution; + +#[cfg(feature = "v4l2")] +use crate::v4l2r::device::Device; +#[cfg(feature = "vaapi")] +use libva::Display; +#[cfg(feature = "v4l2")] +use v4l2r::bindings::v4l2_plane; +#[cfg(feature = "v4l2")] +use v4l2r::ioctl::V4l2Buffer; +#[cfg(feature = "v4l2")] +use v4l2r::Format; + +#[derive(Debug)] +pub struct PooledVideoFrame { + inner: Option, + pool: Weak>>, +} + +impl VideoFrame for PooledVideoFrame { + #[cfg(feature = "vaapi")] + type MemDescriptor = V::MemDescriptor; + + type NativeHandle = V::NativeHandle; + + fn fourcc(&self) -> Fourcc { + self.inner.as_ref().unwrap().fourcc() + } + + fn resolution(&self) -> Resolution { + self.inner.as_ref().unwrap().resolution() + } + + fn get_plane_size(&self) -> Vec { + self.inner.as_ref().unwrap().get_plane_size() + } + + fn get_plane_pitch(&self) -> Vec { + self.inner.as_ref().unwrap().get_plane_pitch() + } + + fn map<'a>(&'a self) -> Result + 'a>, String> { + self.inner.as_ref().unwrap().map() + } + + fn map_mut<'a>(&'a mut self) -> Result + 'a>, String> { + self.inner.as_mut().unwrap().map_mut() + } + + #[cfg(feature = "v4l2")] + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2_plane) { + self.inner.as_ref().unwrap().fill_v4l2_plane(index, plane) + } + + #[cfg(feature = "v4l2")] + fn process_dqbuf(&mut self, device: Arc, format: &Format, buf: &V4l2Buffer) { + self.inner.as_mut().unwrap().process_dqbuf(device, format, buf) + } + + #[cfg(feature = "vaapi")] + fn to_native_handle(&self, display: &Rc) -> Result { + self.inner.as_ref().unwrap().to_native_handle(display) + } +} + +impl Drop for PooledVideoFrame { + fn drop(&mut self) { + if let Some(pool) = self.pool.upgrade() { + (*pool.lock().unwrap()).push_back(self.inner.take().unwrap()); + } + } +} + +pub struct FramePool { + alloc_cb: Box V + Send + 'static>, + pool: Option>>>, +} + +impl FramePool { + pub fn new(alloc_cb: impl FnMut(&StreamInfo) -> V + Send + 'static) -> FramePool { + Self { alloc_cb: Box::new(alloc_cb), pool: None } + } + + pub fn resize(&mut self, stream_info: &StreamInfo) { + let mut pool: VecDeque = VecDeque::new(); + for _i in 0..stream_info.min_num_frames { + pool.push_back((self.alloc_cb)(stream_info)); + } + self.pool = Some(Arc::new(Mutex::new(pool))) + } + + pub fn alloc(&mut self) -> Option> { + let frame = (*self.pool.as_mut()?.lock().unwrap()).pop_front()?; + Some(PooledVideoFrame { + inner: Some(frame), + pool: Arc::downgrade(self.pool.as_ref().unwrap()), + }) + } +} diff --git a/vendor/cros-codecs/src/video_frame/gbm_video_frame.rs b/vendor/cros-codecs/src/video_frame/gbm_video_frame.rs new file mode 100644 index 0000000..dcfa757 --- /dev/null +++ b/vendor/cros-codecs/src/video_frame/gbm_video_frame.rs @@ -0,0 +1,784 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::fs::File; +use std::iter::zip; +use std::os::fd::AsRawFd; +#[cfg(feature = "v4l2")] +use std::os::fd::BorrowedFd; +use std::os::fd::FromRawFd; +use std::path::Path; +use std::ptr; +#[cfg(feature = "vaapi")] +use std::rc::Rc; +use std::slice; +use std::sync::Arc; + +use crate::utils::align_up; +use crate::utils::buffer_size_for_area; +use crate::video_frame::generic_dma_video_frame::GenericDmaVideoFrame; +use crate::video_frame::ReadMapping; +use crate::video_frame::VideoFrame; +use crate::video_frame::WriteMapping; +#[cfg(feature = "vaapi")] +use crate::DecodedFormat; +use crate::Fourcc; +use crate::FrameLayout; +use crate::PlaneLayout; +use crate::Resolution; + +use drm_fourcc::DrmFourcc; +#[cfg(feature = "v4l2")] +use gbm_sys::gbm_import_fd_data; +#[cfg(feature = "vaapi")] +use gbm_sys::gbm_import_fd_modifier_data; +use gbm_sys::{ + gbm_bo, gbm_bo_create, gbm_bo_destroy, gbm_bo_flags, gbm_bo_get_fd, gbm_bo_get_height, + gbm_bo_get_modifier, gbm_bo_get_offset, gbm_bo_get_stride_for_plane, gbm_bo_get_width, + gbm_bo_import, gbm_bo_map, gbm_bo_transfer_flags, gbm_bo_unmap, gbm_create_device, gbm_device, + gbm_device_destroy, +}; +#[cfg(feature = "vaapi")] +use libva::{ + Display, ExternalBufferDescriptor, MemoryType, Surface, UsageHint, VADRMPRIMESurfaceDescriptor, + VADRMPRIMESurfaceDescriptorLayer, VADRMPRIMESurfaceDescriptorObject, +}; +use nix::libc; +#[cfg(feature = "v4l2")] +use v4l2r::bindings::v4l2_plane; +#[cfg(feature = "v4l2")] +use v4l2r::device::Device; +#[cfg(feature = "v4l2")] +use v4l2r::ioctl::V4l2Buffer; +#[cfg(feature = "v4l2")] +use v4l2r::memory::{DmaBufHandle, DmaBufSource, PlaneHandle}; +#[cfg(feature = "v4l2")] +use v4l2r::Format; + +// The gbm crate's wrapper for map() doesn't have the lifetime semantics that we want, so we need +// to implement our own. +// Unfortunately, because the GBM crate's BufferObject class does not expose the raw gbm_bo +// pointer, we are going to need to reimplement a lot of its functionality. This means a lot of +// "unsafe" code will be needed in this module. We guarantee the safety of this code by using +// Rust's native lifetime system to ensure that parent objects do not get deallocated before all of +// their children. For example, map objects maintain a reference to the underlying video frame, +// and video frames maintain a reference to the GBM device that allocated them. + +fn map_bo( + bo: *mut gbm_bo, + is_writable: bool, +) -> Result<(*mut libc::c_void, *mut libc::c_void), String> { + let permissions = if is_writable { + gbm_bo_transfer_flags::GBM_BO_TRANSFER_READ_WRITE + } else { + gbm_bo_transfer_flags::GBM_BO_TRANSFER_READ + }; + let mut stride: u32 = 0; + let mut map_data: *mut libc::c_void = ptr::null_mut(); + // SAFETY: This should be safe because we validate that bo is non-null on creation and we tie + // the lifetimes of the VideoFrames to the underlying GBM device. + unsafe { + let map_result = gbm_bo_map( + bo, + 0, + 0, + gbm_bo_get_width(bo), + gbm_bo_get_height(bo), + permissions, + &mut stride as *mut u32, + &mut map_data as *mut *mut libc::c_void, + ); + if map_result.is_null() { + Err(format!( + "Failed to map GBM buffer object read {}!", + if is_writable { "write" } else { "only" } + )) + } else { + Ok((map_result, map_data)) + } + } +} + +#[cfg(feature = "v4l2")] +fn import_bo_from_dmabuf_fd( + device: *mut gbm_device, + dma: BorrowedFd<'_>, + width: u32, + height: u32, + stride: u32, + format: u32, + usage: u32, +) -> *mut gbm_bo { + let mut import_data = gbm_import_fd_data { + fd: dma.as_raw_fd(), + width: width, + height: height, + stride: stride, + format: format, + }; + // SAFETY: This assumes that gbm_device is valid and that the FD given points to a DRM Prime FD + // with the layout dictated by the other parameters to this function. + unsafe { + gbm_bo_import( + device, + gbm_sys::GBM_BO_IMPORT_FD, + &mut import_data as *mut gbm_import_fd_data as *mut libc::c_void, + usage, + ) + } +} + +pub struct GbmMapping<'a> { + map_datas: Vec<*mut libc::c_void>, + raw_mems: Vec<*mut libc::c_void>, + lens: Vec, + is_writable: bool, + frame: &'a GbmVideoFrame, +} + +impl<'a> ReadMapping<'a> for GbmMapping<'a> { + fn get(&self) -> Vec<&[u8]> { + // SAFETY: This should be safe because we validate that gbm_bo_map returns a non-null + // pointer before instantiating a GbmMapping object. + unsafe { + zip(self.raw_mems.iter(), self.lens.iter()) + .map(|x| slice::from_raw_parts(*x.0 as *const u8, *x.1)) + .collect() + } + } +} + +impl<'a> WriteMapping<'a> for GbmMapping<'a> { + fn get(&self) -> Vec> { + if !self.is_writable { + panic!("Attempted to get writable slice to read only mapping!"); + } + + // SAFETY: This should be safe because we validate that gbm_bo_map returns a non-null + // pointer before instantiating a GbmMapping object. The above check prevents us from + // attempting to get a writable slice to a read-only mapping. + unsafe { + zip(self.raw_mems.iter(), self.lens.iter()) + .map(|x| RefCell::new(slice::from_raw_parts_mut(*x.0 as *mut u8, *x.1))) + .collect() + } + } +} + +impl<'a> Drop for GbmMapping<'a> { + fn drop(&mut self) { + for plane_idx in 0..self.map_datas.len() { + let bo = + if self.frame.bo.len() == 1 { self.frame.bo[0] } else { self.frame.bo[plane_idx] }; + let map_data = self.map_datas[plane_idx]; + // SAFETY: This should be safe because we validate that gbm_bo_map returns a non-null + // pointer before instantiating a GbmMapping object. + unsafe { gbm_bo_unmap(bo, map_data) }; + } + } +} + +#[derive(Debug)] +pub struct GbmVideoFrame { + fourcc: Fourcc, + resolution: Resolution, + bo: Vec<*mut gbm_bo>, + // This reference is just to create a lifetime constraint. We don't want someone to close the + // device before free'ing up all allocated VideoFrames. We keep it optional just so that we can + // create default video frames for the purpose of signaling a drain event. + _device: Option>, + // This ties the lifetime of the DRM FDs to the lifetime of this object so that we can export + // to V4L2. + #[cfg(feature = "v4l2")] + export_handles: Vec>, +} + +impl GbmVideoFrame { + fn get_plane_offset(&self) -> Vec { + let mut ret: Vec = vec![]; + for plane_idx in 0..self.num_planes() { + // SAFETY: This assumes self.bo contains valid GBM buffer objects. + if self.bo.len() > 1 { + ret.push(unsafe { gbm_bo_get_offset(self.bo[plane_idx], 0) as usize }); + } else { + ret.push(unsafe { + gbm_bo_get_offset(self.bo[0], plane_idx as libc::c_int) as usize + }); + } + } + ret + } + + #[allow(dead_code)] + fn get_modifier(&self) -> u64 { + // SAFETY: This assumes self.bo[0] contains a valid GBM buffer object. + unsafe { gbm_bo_get_modifier(self.bo[0]) } + } + + fn map_helper(&self, is_writable: bool) -> Result { + let offsets = self.get_plane_offset(); + let mut ret = GbmMapping { + map_datas: vec![], + raw_mems: vec![], + lens: self.get_plane_size(), + is_writable: is_writable, + frame: self, + }; + for plane_idx in 0..self.num_planes() { + let bo = if self.bo.len() == 1 { self.bo[0] } else { self.bo[plane_idx] }; + let (raw_mem, map_data) = map_bo(bo, is_writable)?; + ret.map_datas.push(map_data); + // SAFETY: This assumes that GBM gave us a valid offset. + ret.raw_mems.push(unsafe { raw_mem.offset(offsets[plane_idx] as isize) }); + } + Ok(ret) + } + + pub fn to_generic_dma_video_frame(self) -> Result { + let planes: Vec = zip(self.get_plane_offset(), self.get_plane_pitch()) + .enumerate() + .map(|x| PlaneLayout { buffer_index: x.0, offset: x.1 .0, stride: x.1 .1 }) + .collect(); + // SAFETY: gbm_bo_get_fd returns a new, owned FD every time it is called, so this should be + // safe as long as self.bo contains valid buffer objects. + let dma_handles: Vec = + self.bo.iter().map(|bo| unsafe { File::from_raw_fd(gbm_bo_get_fd(*bo)) }).collect(); + GenericDmaVideoFrame::new( + dma_handles, + FrameLayout { + format: (self.fourcc, self.get_modifier()), + size: self.resolution(), + planes: planes, + }, + ) + } +} + +#[cfg(feature = "vaapi")] +pub struct GbmExternalBufferDescriptor { + fourcc: Fourcc, + modifier: u64, + resolution: Resolution, + pitches: Vec, + offsets: Vec, + // We use a proper File object here to correctly manage the lifetimes of the exported FDs. + // Otherwise we risk exhausting the FD limit on the machine for certain test vectors. + export_file: File, +} + +#[cfg(feature = "vaapi")] +impl ExternalBufferDescriptor for GbmExternalBufferDescriptor { + const MEMORY_TYPE: MemoryType = MemoryType::DrmPrime2; + type DescriptorAttribute = VADRMPRIMESurfaceDescriptor; + + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute { + let objects = [ + VADRMPRIMESurfaceDescriptorObject { + fd: self.export_file.as_raw_fd(), + size: self.export_file.metadata().unwrap().len() as u32, + drm_format_modifier: self.modifier, + }, + Default::default(), + Default::default(), + Default::default(), + ]; + + let layers = [ + VADRMPRIMESurfaceDescriptorLayer { + drm_format: u32::from(self.fourcc), + num_planes: self.pitches.len() as u32, + object_index: [0, 0, 0, 0], + offset: self + .offsets + .iter() + .map(|x| *x as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + pitch: self + .pitches + .iter() + .map(|x| *x as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + }, + Default::default(), + Default::default(), + Default::default(), + ]; + let resolution = self.resolution; + let ret = VADRMPRIMESurfaceDescriptor { + fourcc: u32::from(self.fourcc), + width: resolution.width, + height: resolution.height, + num_objects: 1, + objects, + num_layers: 1, + layers, + }; + ret + } +} + +impl VideoFrame for GbmVideoFrame { + #[cfg(feature = "v4l2")] + type NativeHandle = DmaBufHandle; + + #[cfg(feature = "vaapi")] + type MemDescriptor = GbmExternalBufferDescriptor; + #[cfg(feature = "vaapi")] + type NativeHandle = Surface; + + fn fourcc(&self) -> Fourcc { + self.fourcc.clone() + } + + fn resolution(&self) -> Resolution { + self.resolution.clone() + } + + // GBM allocates all the planes in one buffer and doesn't expose a means to get the size of a + // single plane, so just stub this method. + fn get_plane_size(&self) -> Vec { + let mut ret: Vec = vec![]; + let vertical_subsampling = self.get_vertical_subsampling(); + let plane_pitch = self.get_plane_pitch(); + for plane_idx in 0..self.num_planes() { + ret.push( + plane_pitch[plane_idx] + * align_up(self.resolution().height as usize, vertical_subsampling[plane_idx]) + / vertical_subsampling[plane_idx], + ); + } + ret + } + + fn get_plane_pitch(&self) -> Vec { + let mut ret: Vec = vec![]; + for plane_idx in 0..self.num_planes() { + // SAFETY: This assumes self.bo contains valid GBM buffer objects. + if self.bo.len() > 1 { + ret.push(unsafe { gbm_bo_get_stride_for_plane(self.bo[plane_idx], 0) as usize }); + } else { + ret.push(unsafe { + gbm_bo_get_stride_for_plane(self.bo[0], plane_idx as libc::c_int) as usize + }); + } + } + ret + } + + fn map<'a>(&'a self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper(false)?)) + } + + fn map_mut<'a>(&'a mut self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper(true)?)) + } + + #[cfg(feature = "v4l2")] + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2_plane) { + // TODO: Support |data_offset| here. + self.export_handles[index].fill_v4l2_plane(plane) + } + + // No-op for GBM buffers since the backing FD already disambiguates them. + #[cfg(feature = "v4l2")] + fn process_dqbuf(&mut self, _device: Arc, _format: &Format, _buf: &V4l2Buffer) {} + + #[cfg(feature = "vaapi")] + fn to_native_handle(&self, display: &Rc) -> Result { + if self.is_compressed() { + return Err("Compressed buffer export to VA-API is not currently supported".to_string()); + } + if !self.is_contiguous() { + return Err( + "Exporting non-contiguous GBM buffers to VA-API is not currently supported" + .to_string(), + ); + } + + // TODO: Add more supported formats + let rt_format = match self.decoded_format().unwrap() { + DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420, + _ => return Err("Format unsupported for VA-API export".to_string()), + }; + + let export_descriptor = vec![GbmExternalBufferDescriptor { + fourcc: self.fourcc.clone(), + modifier: self.get_modifier(), + resolution: self.resolution(), + pitches: self.get_plane_pitch(), + offsets: self.get_plane_offset(), + // SAFETY: gbm_bo_get_fd returns a new, owned FD every time it is called, so this should + // be safe as long as self.bo contains valid buffer objects. + export_file: unsafe { File::from_raw_fd(gbm_bo_get_fd(self.bo[0])) }, + }]; + + let mut ret = display + .create_surfaces( + rt_format, + Some(u32::from(self.fourcc)), + self.resolution().width, + self.resolution().height, + Some(UsageHint::USAGE_HINT_DECODER), + export_descriptor, + ) + .map_err(|_| "Error importing GbmVideoFrame to VA-API".to_string())?; + + Ok(ret.pop().unwrap()) + } +} + +impl Drop for GbmVideoFrame { + fn drop(&mut self) { + for bo in self.bo.iter() { + // SAFETY: This should be safe because we would not instantiate a GbmVideoFrame if the + // buffer object creation failed. + unsafe { gbm_bo_destroy(*bo) }; + } + } +} + +// SAFETY: We will only access the raw BOs from the worker thread, and there are no other copies of +// these pointers. +unsafe impl Send for GbmVideoFrame {} +unsafe impl Sync for GbmVideoFrame {} + +#[derive(Clone, Debug, PartialEq)] +pub enum GbmUsage { + Decode, + Encode, +} + +#[derive(Debug)] +pub struct GbmDevice { + device: *mut gbm_device, + // Keeps device file descriptors valid as long as the GbmDevice is alive. + _device_file: std::fs::File, +} + +impl GbmDevice { + pub fn open>(path: P) -> Result, String> { + let device_file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(path) + .map_err(|_| "Error opening GBM device!".to_string())?; + // SAFETY: We keep the GBM device File inside GbmDevice specifically for the purpose of + // making sure this FD is valid for the lifetime of the GbmDevice. + let device = unsafe { gbm_create_device(device_file.as_raw_fd()) }; + if device.is_null() { + Err("Could not create GBM device from file!".to_string()) + } else { + Ok(Arc::new(Self { device: device, _device_file: device_file })) + } + } + + pub fn new_frame( + self: Arc, + fourcc: Fourcc, + visible_resolution: Resolution, + coded_resolution: Resolution, + usage: GbmUsage, + ) -> Result { + let mut ret = GbmVideoFrame { + fourcc: fourcc, + resolution: visible_resolution, + bo: vec![], + _device: Some(Arc::clone(&self)), + #[cfg(feature = "v4l2")] + export_handles: vec![], + }; + + if ret.is_compressed() { + let buffer_size = buffer_size_for_area(coded_resolution.width, coded_resolution.height); + // The width and height values are ultimately arbitrary, but we should try to pick some + // that won't trigger the GEM driver to add padding, so we only allocate what we need. + // 32 pixels is a common enough alignment that this provides us with a decent guess. + let fake_width = align_up((buffer_size as f64).sqrt() as u32, 32); + let fake_height = align_up(buffer_size as u32, fake_width) / fake_width; + // SAFETY: This should be safe because we would not instantiate a GbmDevice unless the + // call to gbm_create_device was successful. + let bo = unsafe { + gbm_bo_create( + self.device, + fake_width, + fake_height, + DrmFourcc::R8 as u32, + gbm_bo_flags::GBM_BO_USE_LINEAR as u32, + ) + }; + if bo.is_null() { + return Err("Error allocating compressed buffer!".to_string()); + } + + ret.bo.push(bo); + } else if ret.is_contiguous() { + // These flags are not present in every system's GBM headers. + const GBM_BO_USE_HW_VIDEO_DECODER: u32 = 1 << 13; + const GBM_BO_USE_HW_VIDEO_ENCODER: u32 = 1 << 14; + // It's important that we use the correct use flag for platforms that support directly + // importing GBM allocated frame buffers to the video decoding hardware because the + // video decoding hardware sometimes makes assumptions about the modifier flags. If we + // try to force everything to be linear, we can end up getting a tiled frame when we + // try to map it. + // SAFETY: This should be safe because we would not instantiate a GbmDevice unless the + // call to gbm_create_device was successful. + let bo = unsafe { + gbm_bo_create( + self.device, + coded_resolution.width, + coded_resolution.height, + u32::from(fourcc), + if usage == GbmUsage::Decode { + GBM_BO_USE_HW_VIDEO_DECODER + } else { + GBM_BO_USE_HW_VIDEO_ENCODER + }, + ) + }; + if bo.is_null() { + return Err(format!( + "Error allocating contiguous buffer! Fourcc: {} width: {} height: {}", + fourcc.to_string(), + coded_resolution.width, + coded_resolution.height + )); + } + + ret.bo.push(bo); + } else { + // We hack multiplanar formats into GBM by making a bunch of separate BO's. + // The usage flag is ignored here because R8 are generally not supported + // decoder and encoder formats, so we just have to accept we're on our own for figuring + // out alignment, modifier, fourcc, etc. + let horizontal_subsampling = ret.get_horizontal_subsampling(); + let vertical_subsampling = ret.get_vertical_subsampling(); + let bytes_per_element = ret.get_bytes_per_element(); + for plane_idx in 0..ret.num_planes() { + // SAFETY: This should be safe because we would not instantiate a GbmDevice unless + // the call to gbm_create_device was successful. + let bo = unsafe { + gbm_bo_create( + self.device, + (align_up( + coded_resolution.width as usize, + horizontal_subsampling[plane_idx], + ) / horizontal_subsampling[plane_idx] + * bytes_per_element[plane_idx]) as u32, + (align_up( + coded_resolution.height as usize, + vertical_subsampling[plane_idx], + ) / vertical_subsampling[plane_idx]) as u32, + DrmFourcc::R8 as u32, + gbm_bo_flags::GBM_BO_USE_LINEAR as u32, + ) + }; + if bo.is_null() { + return Err(format!( + "Error allocating plane {} for format {}", + plane_idx, + fourcc.to_string() + )); + } + + ret.bo.push(bo); + } + } + + #[cfg(feature = "v4l2")] + { + // SAFETY: gbm_bo_get_fd returns a new, owned FD every time it is called, so this + // should be safe as long as ret.bo contains valid buffer objects. + ret.export_handles = ret + .bo + .iter() + .map(|bo| unsafe { + DmaBufHandle::from(File::from_raw_fd(gbm_bo_get_fd(bo.clone()))) + }) + .collect::<_>(); + } + + Ok(ret) + } + + #[cfg(feature = "v4l2")] + pub fn import_from_v4l2( + self: Arc, + fourcc: Fourcc, + resolution: Resolution, + strides: Vec, + native_handle: Vec>, + ) -> Result { + let mut ret = GbmVideoFrame { + fourcc: fourcc, + resolution: resolution, + bo: vec![], + export_handles: vec![], + _device: Some(Arc::clone(&self)), + }; + + if strides.is_empty() || native_handle.is_empty() { + return Err("Cannot import empty V4L2 handle!".to_string()); + } + if !ret.is_contiguous() && strides.len() != ret.num_planes() { + return Err(format!("Invalid number of strides for format {}", fourcc.to_string())); + } + if !ret.is_contiguous() && native_handle.len() != ret.num_planes() { + return Err(format!("Invalid number of V4L2 planes for format {}", fourcc.to_string())); + } + + // TODO: Pass in a parameter that determines this usage rather than just OR'ing everything + // together. + let usage = gbm_bo_flags::GBM_BO_USE_LINEAR as u32; + if ret.is_contiguous() { + let bo = import_bo_from_dmabuf_fd( + self.device, + native_handle[0].0.as_fd(), + ret.resolution.width, + ret.resolution.height, + strides[0] as u32, + u32::from(fourcc), + usage, + ); + if bo.is_null() { + return Err("Error importing contiguous V4L2 buffer!".to_string()); + } + ret.bo.push(bo); + } else { + let horizontal_subsampling = ret.get_horizontal_subsampling(); + let vertical_subsampling = ret.get_vertical_subsampling(); + let bytes_per_element = ret.get_bytes_per_element(); + for plane_idx in 0..ret.num_planes() { + let bo = import_bo_from_dmabuf_fd( + self.device, + native_handle[plane_idx].0.as_fd(), + (align_up(resolution.width as usize, horizontal_subsampling[plane_idx]) + / horizontal_subsampling[plane_idx] + * bytes_per_element[plane_idx]) as u32, + (align_up(resolution.height as usize, vertical_subsampling[plane_idx]) + / vertical_subsampling[plane_idx]) as u32, + strides[plane_idx] as u32, + DrmFourcc::R8 as u32, + usage, + ); + if bo.is_null() { + return Err(format!("Error importing plane {}", plane_idx)); + } + ret.bo.push(bo); + } + } + + // SAFETY: gbm_bo_get_fd returns a new, owned FD every time it is called, so this should be + // safe as long as self.bo contains valid buffer objects. + ret.export_handles = ret + .bo + .iter() + .map(|bo| unsafe { DmaBufHandle::from(File::from_raw_fd(gbm_bo_get_fd(bo.clone()))) }) + .collect::<_>(); + + Ok(ret) + } + + #[cfg(feature = "vaapi")] + pub fn import_from_vaapi( + self: Arc, + surface: &Surface, + ) -> Result { + let descriptor = surface + .export_prime() + .map_err(|err| format!("Could not export VA-API surface! {err:?}"))?; + + if descriptor.layers.len() != 1 { + return Err("Cannot import more than 1 layers as a single GBM buffer".to_string()); + } + + for idx in descriptor.layers[0].object_index { + if idx as usize >= descriptor.objects.len() { + return Err("Object index {idx} out of bounds".to_string()); + } + } + + let mut ret = GbmVideoFrame { + _device: Some(Arc::clone(&self)), + fourcc: Fourcc::from(descriptor.fourcc), + resolution: Resolution { width: descriptor.width, height: descriptor.height }, + bo: vec![], + }; + + let buffers = [ + descriptor.objects[descriptor.layers[0].object_index[0] as usize].fd.as_raw_fd() + as libc::c_int, + -1, + -1, + -1, + ]; + let mut import_data = gbm_import_fd_modifier_data { + width: descriptor.width, + height: descriptor.height, + format: descriptor.fourcc, + num_fds: 1, + fds: buffers, + strides: [ + descriptor.layers[0].pitch[0] as libc::c_int, + descriptor.layers[0].pitch[1] as libc::c_int, + descriptor.layers[0].pitch[2] as libc::c_int, + descriptor.layers[0].pitch[3] as libc::c_int, + ], + offsets: [ + descriptor.layers[0].offset[0] as libc::c_int, + descriptor.layers[0].offset[1] as libc::c_int, + descriptor.layers[0].offset[2] as libc::c_int, + descriptor.layers[0].offset[3] as libc::c_int, + ], + modifier: descriptor.objects[0].drm_format_modifier, + }; + + // TODO: Plumb real usage flags in here. + let usage = gbm_bo_flags::GBM_BO_USE_SCANOUT as u32; + + // The constant in gbm_sys is wrong for some reason + const GBM_BO_IMPORT_FD_MODIFIER: u32 = 0x5505; + // SAFETY: This should be safe as long as VA-API correctly exports the DRM Prime FD. The + // GBM device is guaranteed to be valid or we wouldn't have instantiated the GbmDevice in + // the first place. + let bo = unsafe { + gbm_bo_import( + self.device, + GBM_BO_IMPORT_FD_MODIFIER, + &mut import_data as *mut gbm_import_fd_modifier_data as *mut libc::c_void, + usage, + ) + }; + + if bo.is_null() { + Err("Error importing VA-API surface!".to_string()) + } else { + ret.bo.push(bo); + Ok(ret) + } + } +} + +impl Drop for GbmDevice { + fn drop(&mut self) { + // SAFETY: device should be valid because we wouldn't instantiate a GbmDevice if + // gbm_create_device failed. + unsafe { gbm_device_destroy(self.device) } + } +} + +// UNSAFE: We will only access the raw GBM device from the worker thread, and there are no other +// copies of the raw pointer available. +unsafe impl Send for GbmDevice {} +unsafe impl Sync for GbmDevice {} + +// TODO: Add unit tests diff --git a/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs new file mode 100644 index 0000000..fffc960 --- /dev/null +++ b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs @@ -0,0 +1,548 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(target_arch = "x86_64")] +use core::arch::x86_64::_mm_clflush; +#[cfg(target_arch = "x86_64")] +use core::arch::x86_64::_mm_mfence; +use std::cell::RefCell; +use std::fs::File; +use std::iter::zip; +use std::num::NonZeroUsize; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd}; +use std::ptr::NonNull; +#[cfg(feature = "vaapi")] +use std::rc::Rc; +use std::slice; +use std::sync::atomic::{fence, Ordering}; +#[cfg(feature = "v4l2")] +use std::sync::Arc; + +use crate::video_frame::{ReadMapping, VideoFrame, WriteMapping}; +#[cfg(feature = "vaapi")] +use crate::DecodedFormat; +use crate::{Fourcc, FrameLayout, Resolution}; + +use drm_fourcc::DrmModifier; +use nix::errno::Errno; +use nix::ioctl_write_ptr; +use nix::libc; +use nix::poll::poll; +use nix::poll::PollFd; +use nix::poll::PollFlags; +use nix::poll::PollTimeout; +use nix::sys::mman::mmap; +use nix::sys::mman::munmap; +use nix::sys::mman::MapFlags; +use nix::sys::mman::ProtFlags; +use nix::unistd::dup; + +#[cfg(feature = "vaapi")] +use libva::{ + Display, ExternalBufferDescriptor, MemoryType, Surface, UsageHint, VADRMPRIMESurfaceDescriptor, + VADRMPRIMESurfaceDescriptorLayer, VADRMPRIMESurfaceDescriptorObject, +}; +#[cfg(feature = "v4l2")] +use v4l2r::bindings::v4l2_plane; +#[cfg(feature = "v4l2")] +use v4l2r::device::Device; +#[cfg(feature = "v4l2")] +use v4l2r::ioctl::V4l2Buffer; +#[cfg(feature = "v4l2")] +use v4l2r::memory::DmaBufHandle; +#[cfg(feature = "v4l2")] +use v4l2r::Format; + +// UNSAFE: This file uses tons of unsafe code because we are directly interacting with the kernel's +// DMA infrastructure. The core assumption is that GenericDmaVideoFrame is initialized with a +// valid DRM Prime File Descriptor, and that the FrameLayout given accurately describes the memory +// layout of the frame. We leverage Rust's lifetime system and RAII design patterns to guarantee +// that mappings will not last longer than the underlying DMA buffer. + +// Defined in include/linux/dma-buf.h +const DMA_BUF_BASE: u8 = b'b'; +const DMA_BUF_IOCTL_SYNC: u8 = 0; +const DMA_BUF_SYNC_READ: u64 = 1 << 0; +const DMA_BUF_SYNC_WRITE: u64 = 2 << 0; +const DMA_BUF_SYNC_START: u64 = 0 << 2; +const DMA_BUF_SYNC_END: u64 = 1 << 2; +#[repr(C)] +struct dma_buf_sync { + flags: u64, +} +ioctl_write_ptr!(dma_buf_ioctl_sync, DMA_BUF_BASE, DMA_BUF_IOCTL_SYNC, dma_buf_sync); + +fn handle_eintr(cb: &mut impl FnMut() -> nix::Result) -> Result { + loop { + match cb() { + Ok(ret) => return Ok(ret), + Err(errno) => { + if errno != Errno::EINTR { + return Err(format!("Error executing DMA buf sync! {errno}")); + } + } + } + } +} + +// Because we are limited to executing raw mmap instead of leveraging the GEM driver, all of our +// buffers will be mapped linear even if the backing frame has a modifier. So, we have to manually +// detile the buffers. +const Y_SUBTILE_WIDTH: usize = 16; +const Y_SUBTILE_HEIGHT: usize = 4; +const Y_SUBTILE_SIZE: usize = Y_SUBTILE_WIDTH * Y_SUBTILE_HEIGHT; +const Y_TILE_WIDTH_IN_SUBTILES: usize = 8; +const Y_TILE_HEIGHT_IN_SUBTILES: usize = 8; +const Y_TILE_WIDTH: usize = Y_TILE_WIDTH_IN_SUBTILES * Y_SUBTILE_WIDTH; +const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT; +const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT; + +fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { + let tiles_per_row = width / Y_TILE_WIDTH; + for y in 0..height { + for x in 0..width { + let tile_x = x / Y_TILE_WIDTH; + let tile_y = y / Y_TILE_HEIGHT; + let intra_tile_x = x % Y_TILE_WIDTH; + let intra_tile_y = y % Y_TILE_HEIGHT; + let subtile_x = intra_tile_x / Y_SUBTILE_WIDTH; + let subtile_y = intra_tile_y / Y_SUBTILE_HEIGHT; + let intra_subtile_x = intra_tile_x % Y_SUBTILE_WIDTH; + let intra_subtile_y = intra_tile_y % Y_SUBTILE_HEIGHT; + // TODO: We should batch up the writes since subtile rows are contiguous. Also consider + // SIMD'ifying this function. + dst[y * width + x] = src[(tile_y * tiles_per_row + tile_x) * Y_TILE_SIZE + + (subtile_x * Y_TILE_HEIGHT_IN_SUBTILES + subtile_y) * Y_SUBTILE_SIZE + + intra_subtile_y * Y_SUBTILE_WIDTH + + intra_subtile_x] + } + } +} + +pub struct DmaMapping<'a> { + dma_handles: Vec>, + addrs: Vec>, + detiled_bufs: Vec>, + lens: Vec, + is_writable: bool, +} + +impl<'a> DmaMapping<'a> { + fn new( + dma_handles: &'a Vec, + offsets: Vec, + pitches: Vec, + lens: Vec, + modifier: DrmModifier, + is_writable: bool, + ) -> Result { + if is_writable && modifier != DrmModifier::Linear { + return Err( + "Writable mappings currently only supported for linear buffers!".to_string() + ); + } + if modifier != DrmModifier::Linear && modifier != DrmModifier::I915_y_tiled { + return Err( + "Only linear and Y tile buffers are currently supported for mapping!".to_string() + ); + } + + let borrowed_dma_handles: Vec = dma_handles.iter().map(|x| x.as_fd()).collect(); + + // Wait on all memory fences to finish before attempting to map this DMA buffer. + for fd in borrowed_dma_handles.iter() { + let mut fence_poll_fd = + [PollFd::new(fd.clone(), PollFlags::POLLIN | PollFlags::POLLOUT)]; + poll(&mut fence_poll_fd, PollTimeout::NONE).unwrap(); + } + + // Some architectures do not put DMA in the same coherency zone as CPU, so we need to + // invalidate cache lines corresponding to this memory. The DMA infrastructure provides + // this convenient IOCTL for doing so. + let sync_struct = + dma_buf_sync { flags: DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ | DMA_BUF_SYNC_WRITE }; + + for fd in borrowed_dma_handles.iter() { + // SAFETY: This assumes fd is a valid DMA buffer. + handle_eintr(&mut || unsafe { dma_buf_ioctl_sync(fd.as_raw_fd(), &sync_struct) })?; + } + + // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then + // do pointer arithmetic to get the right buffer. + let mut addrs: Vec> = vec![]; + if borrowed_dma_handles.len() > 1 { + for i in 0..offsets.len() { + // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets + // are correct. + addrs.push(unsafe { + mmap( + None, + NonZeroUsize::new(lens[i] + offsets[i]) + .ok_or("Attempted to map plane of length 0!")?, + if is_writable { + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE + } else { + ProtFlags::PROT_READ + }, + MapFlags::MAP_SHARED, + borrowed_dma_handles[i].as_fd(), + 0, + ) + .map_err(|err| format!("Error mapping plane {err}"))? + .add(offsets[i]) + }); + } + } else { + let total_size = NonZeroUsize::new(lens.iter().sum::() + offsets[0]) + .ok_or("Attempted to map VideoFrame of length 0")?; + // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets are + // correct. + unsafe { + let base_addr = mmap( + None, + total_size, + if is_writable { + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE + } else { + ProtFlags::PROT_READ + }, + MapFlags::MAP_SHARED, + borrowed_dma_handles[0].as_fd(), + 0, + ) + .map_err(|err| format!("Error mapping plane {err}"))?; + for i in 0..offsets.len() { + addrs.push(base_addr.add(offsets[i])); + } + } + } + + let mut detiled_bufs = vec![]; + if modifier == DrmModifier::I915_y_tiled { + // SAFETY: This assumes mmap returned a valid memory address. Note that nix's mmap + // bindings already check for null pointers, which we turn into Rust Err objects. So + // this assumption will only be violated if mmap itself has a bug that returns a + // non-NULL, but invalid pointer. + let tiled_bufs: Vec<&[u8]> = unsafe { + zip(addrs.iter(), lens.iter()) + .map(|x| slice::from_raw_parts(x.0.as_ptr() as *const u8, *x.1)) + .collect() + }; + for i in 0..tiled_bufs.len() { + let mut detiled_buf: Vec = vec![]; + detiled_buf.resize(tiled_bufs[i].len(), 0); + detile_y_tile( + detiled_buf.as_mut_slice(), + tiled_bufs[i], + pitches[i], + lens[i] / pitches[i], + ); + detiled_bufs.push(detiled_buf); + } + } + + Ok(DmaMapping { + dma_handles: borrowed_dma_handles.clone(), + addrs: addrs, + detiled_bufs: detiled_bufs, + lens: lens.clone(), + is_writable: is_writable, + }) + } +} + +impl<'a> ReadMapping<'a> for DmaMapping<'a> { + fn get(&self) -> Vec<&[u8]> { + if self.detiled_bufs.len() > 0 { + self.detiled_bufs.iter().map(|x| x.as_slice()).collect() + } else { + // SAFETY: This assumes mmap returned a valid memory address. Note that nix's mmap + // bindings already check for null pointers, which we turn into Rust Err objects. So + // this assumption will only be violated if mmap itself has a bug that returns a + // non-NULL, but invalid pointer. + unsafe { + zip(self.addrs.iter(), self.lens.iter()) + .map(|x| slice::from_raw_parts(x.0.as_ptr() as *const u8, *x.1)) + .collect() + } + } + } +} + +impl<'a> WriteMapping<'a> for DmaMapping<'a> { + fn get(&self) -> Vec> { + if !self.is_writable { + panic!("Attempted to get writable slice to read only mapping!"); + } + + // The above check prevents us from undefined behavior in the event that the user attempts + // to coerce a ReadMapping into a WriteMapping. + // SAFETY: This assumes mmap returned a valid memory address. Note that nix's mmap bindings + // already check for null pointers, which we turn into Rust Err objects. So this assumptoin + // will only be violated if mmap itself has a bug that returns a non-NULL, but invalid + // pointer. + unsafe { + zip(self.addrs.iter(), self.lens.iter()) + .map(|x| RefCell::new(slice::from_raw_parts_mut(x.0.as_ptr() as *mut u8, *x.1))) + .collect() + } + } +} + +impl<'a> Drop for DmaMapping<'a> { + fn drop(&mut self) { + // SAFETY: This should be safe because we would not instantiate a DmaMapping object if the + // first call to dma_buf_ioctl_sync or the mmap call failed. + unsafe { + fence(Ordering::SeqCst); + + // Flush all cache lines back to main memory. + let sync_struct = + dma_buf_sync { flags: DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ | DMA_BUF_SYNC_WRITE }; + for fd in self.dma_handles.iter() { + let _ = handle_eintr(&mut || dma_buf_ioctl_sync(fd.as_raw_fd(), &sync_struct)); + } + + // For some reason, DMA_BUF_IOCTL_SYNC is insufficient on Intel machines, and we have + // to manually flush the cache lines. This is probably a violation of the DMA API spec? + #[cfg(target_arch = "x86_64")] + { + // Note that fence() only guarantees that the compiler won't reorder memory + // operations, and we need to call _mm_mfence() to guarantee the CPU won't do it. + _mm_mfence(); + + for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) { + // TODO: We shouldn't actually have to flush every address, we should just + // flush the address at the beginning of each cache line. But, during testing + // this caused a race condition. + for offset in 0..*len { + _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize)); + } + } + + _mm_mfence(); + } + + fence(Ordering::SeqCst); + + let _ = zip(self.addrs.iter(), self.lens.iter()).map(|x| munmap(*x.0, *x.1).unwrap()); + } + } +} + +#[derive(Debug)] +pub struct GenericDmaVideoFrame { + dma_handles: Vec, + layout: FrameLayout, +} + +impl Clone for GenericDmaVideoFrame { + fn clone(&self) -> Self { + Self { + // SAFETY: This is safe because we are dup'ing the fd, giving the clone'd + // GenericDmaVideoFrame ownership of the new fd. + dma_handles: self + .dma_handles + .iter() + .map(|x| unsafe { + File::from_raw_fd(dup(x.as_raw_fd()).expect("Could not dup DMAbuf FD!")) + }) + .collect(), + layout: self.layout.clone(), + } + } +} + +impl GenericDmaVideoFrame { + pub fn new( + dma_handles: Vec, + layout: FrameLayout, + ) -> Result { + let ret = GenericDmaVideoFrame { dma_handles: dma_handles, layout: layout }; + ret.validate_frame()?; + Ok(ret) + } + + fn get_single_plane_size(&self, index: usize) -> usize { + if index >= self.num_planes() { + panic!("Invalid plane index {index}!"); + } + + if self.dma_handles.len() == 1 { + if index == self.num_planes() - 1 { + let total_size = self.dma_handles[0].metadata().unwrap().len() as usize; + total_size - self.layout.planes[index].offset + } else { + self.layout.planes[index + 1].offset - self.layout.planes[index].offset + } + } else { + self.dma_handles[index].metadata().unwrap().len() as usize + } + } + + fn get_plane_offset(&self) -> Vec { + self.layout.planes.iter().map(|x| x.offset).collect() + } + + fn map_helper(&self, is_writable: bool) -> Result { + let lens = self.get_plane_size(); + let pitches = self.get_plane_pitch(); + let offsets = self.get_plane_offset(); + DmaMapping::new( + &self.dma_handles, + offsets, + pitches, + lens, + DrmModifier::from(self.layout.format.1), + is_writable, + ) + } +} + +#[cfg(feature = "vaapi")] +impl ExternalBufferDescriptor for GenericDmaVideoFrame { + const MEMORY_TYPE: MemoryType = MemoryType::DrmPrime2; + type DescriptorAttribute = VADRMPRIMESurfaceDescriptor; + + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute { + let objects = self + .dma_handles + .iter() + .map(|fd| VADRMPRIMESurfaceDescriptorObject { + fd: fd.as_raw_fd(), + size: fd.metadata().unwrap().len() as u32, + drm_format_modifier: self.layout.format.1, + }) + .chain(std::iter::repeat(Default::default())) + .take(4) + .collect::>(); + let layers = [ + VADRMPRIMESurfaceDescriptorLayer { + drm_format: u32::from(self.layout.format.0), + num_planes: self.num_planes() as u32, + object_index: (0..self.dma_handles.len() as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + offset: self + .get_plane_offset() + .iter() + .map(|x| *x as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + pitch: self + .get_plane_pitch() + .iter() + .map(|x| *x as u32) + .chain(std::iter::repeat(0)) + .take(4) + .collect::>() + .try_into() + .unwrap(), + }, + Default::default(), + Default::default(), + Default::default(), + ]; + VADRMPRIMESurfaceDescriptor { + fourcc: u32::from(self.layout.format.0), + width: self.layout.size.width, + height: self.layout.size.height, + num_objects: self.dma_handles.len() as u32, + objects: objects.try_into().unwrap(), + num_layers: 1, + layers: layers, + } + } +} + +impl VideoFrame for GenericDmaVideoFrame { + #[cfg(feature = "v4l2")] + type NativeHandle = DmaBufHandle; + + #[cfg(feature = "vaapi")] + type MemDescriptor = GenericDmaVideoFrame; + #[cfg(feature = "vaapi")] + type NativeHandle = Surface; + + fn fourcc(&self) -> Fourcc { + self.layout.format.0.clone() + } + + fn resolution(&self) -> Resolution { + self.layout.size.clone() + } + + fn get_plane_size(&self) -> Vec { + (0..self.num_planes()).map(|idx| self.get_single_plane_size(idx)).collect() + } + + fn get_plane_pitch(&self) -> Vec { + self.layout.planes.iter().map(|x| x.stride).collect() + } + + fn map<'a>(&'a self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper(false)?)) + } + + fn map_mut<'a>(&'a mut self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper(true)?)) + } + + #[cfg(feature = "v4l2")] + fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2_plane) { + if self.dma_handles.len() == 1 { + plane.m.fd = self.dma_handles[0].as_raw_fd(); + plane.length = self.dma_handles[0].metadata().unwrap().len() as u32; + } else { + plane.m.fd = self.dma_handles[index].as_raw_fd(); + plane.length = self.get_single_plane_size(index) as u32; + } + // WARNING: Importing DMA buffers with an offset is not officially supported by V4L2, but + // several drivers (including MTK venc) will respect the data_offset field. + plane.data_offset = self.layout.planes[index].offset as u32; + } + + // No-op for DMA buffers since the backing FD already disambiguates them. + #[cfg(feature = "v4l2")] + fn process_dqbuf(&mut self, _device: Arc, _format: &Format, _buf: &V4l2Buffer) {} + + #[cfg(feature = "vaapi")] + fn to_native_handle(&self, display: &Rc) -> Result { + if self.is_compressed() { + return Err("Compressed buffer export to VA-API is not currently supported".to_string()); + } + if !self.is_contiguous() { + return Err( + "Exporting non-contiguous GBM buffers to VA-API is not currently supported" + .to_string(), + ); + } + + // TODO: Add more supported formats + let rt_format = match self.decoded_format().unwrap() { + DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420, + _ => return Err("Format unsupported for VA-API export".to_string()), + }; + + let mut ret = display + .create_surfaces( + rt_format, + Some(u32::from(self.layout.format.0)), + self.resolution().width, + self.resolution().height, + // TODO: Should we add USAGE_HINT_ENCODER support? + Some(UsageHint::USAGE_HINT_DECODER), + vec![self.clone()], + ) + .map_err(|_| "Error importing GenericDmaVideoFrame to VA-API".to_string())?; + + Ok(ret.pop().unwrap()) + } +} diff --git a/vendor/cros-codecs/src/video_frame/v4l2_mmap_video_frame.rs b/vendor/cros-codecs/src/video_frame/v4l2_mmap_video_frame.rs new file mode 100644 index 0000000..2093bfb --- /dev/null +++ b/vendor/cros-codecs/src/video_frame/v4l2_mmap_video_frame.rs @@ -0,0 +1,158 @@ +// Copyright 2025 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::cell::RefCell; +use std::fmt; +use std::fmt::Debug; +use std::iter::zip; +use std::sync::Arc; + +use crate::utils::align_up; +use crate::video_frame::ReadMapping; +use crate::video_frame::VideoFrame; +use crate::video_frame::WriteMapping; +use crate::Fourcc; +use crate::Resolution; + +use crate::v4l2r::device::Device; +use v4l2r::bindings::v4l2_plane; +use v4l2r::ioctl::{mmap, PlaneMapping, V4l2Buffer}; +use v4l2r::memory::{MmapHandle, PlaneHandle}; +use v4l2r::Format; + +pub struct V4l2MmapMapping { + planes: Vec, +} + +impl<'a> ReadMapping<'a> for V4l2MmapMapping { + fn get(&self) -> Vec<&[u8]> { + self.planes.iter().map(|x| &*x.data).collect() + } +} + +impl<'a> WriteMapping<'a> for V4l2MmapMapping { + fn get(&self) -> Vec> { + todo!("Writable mappings not yet supported!") + } +} + +pub struct V4l2MmapVideoFrame { + fourcc: Fourcc, + resolution: Resolution, + handle: MmapHandle, + device: Option>, + queue_format: Option, + buffer: Option, +} + +impl Debug for V4l2MmapVideoFrame { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MmapVideoFrame") + .field("fourcc", &self.fourcc) + .field("resolution", &self.resolution) + .field("queue_format", &self.queue_format) + .field("buffer", &self.buffer) + .finish() + } +} + +impl V4l2MmapVideoFrame { + pub fn new(fourcc: Fourcc, resolution: Resolution) -> Self { + let ret = V4l2MmapVideoFrame { + fourcc: fourcc, + resolution: resolution, + handle: MmapHandle {}, + device: None, + queue_format: None, + buffer: None, + }; + + if ret.is_contiguous() { + todo!("Contiguous formats are not currently supported for MMAP!"); + } + + ret + } + + fn map_helper(&self) -> Result { + let device = self.device.as_ref().ok_or("No V4L2 device!".to_string())?; + // SAFETY: The unsafe block is just because we're accessing a union, which is guaranteed + // to be initialized in this circumstance because the handle is of type MmapHandle. + // TODO: This will not work for single planar video formats such as NV12. + Ok(V4l2MmapMapping { + planes: self + .buffer + .as_ref() + .ok_or("No V4L2 buffer!")? + .as_v4l2_planes() + .iter() + .map(|x| unsafe { mmap(device, x.m.mem_offset, x.length) }) + .collect::, _>>() + .map_err(|err| format!("Error mmap'ing buffer {err}"))?, + }) + } +} + +impl VideoFrame for V4l2MmapVideoFrame { + type NativeHandle = MmapHandle; + + fn fourcc(&self) -> Fourcc { + self.fourcc.clone() + } + + fn resolution(&self) -> Resolution { + self.resolution.clone() + } + + fn get_plane_size(&self) -> Vec { + match self.buffer.as_ref() { + Some(buffer) => buffer.as_v4l2_planes().iter().map(|x| x.length as usize).collect(), + None => { + let mut plane_size: Vec = vec![]; + let vertical_subsampling = self.get_vertical_subsampling(); + let horizontal_subsampling = self.get_horizontal_subsampling(); + let bpp = self.get_bytes_per_element(); + for i in 0..self.num_planes() { + plane_size.push( + align_up(self.resolution.width as usize, horizontal_subsampling[i]) + / horizontal_subsampling[i] + * align_up(self.resolution.height as usize, vertical_subsampling[i]) + / vertical_subsampling[i] + * bpp[i], + ); + } + plane_size + } + } + } + + fn get_plane_pitch(&self) -> Vec { + match self.queue_format.as_ref() { + Some(format) => format.plane_fmt.iter().map(|x| x.bytesperline as usize).collect(), + None => zip(self.get_bytes_per_element(), self.get_horizontal_subsampling()) + .map(|x| align_up(self.resolution.width as usize, x.1) / x.1 * x.0) + .collect(), + } + } + + fn map<'a>(&'a self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper()?)) + } + + fn map_mut<'a>(&'a mut self) -> Result + 'a>, String> { + Ok(Box::new(self.map_helper()?)) + } + + #[cfg(feature = "v4l2")] + fn fill_v4l2_plane(&self, _index: usize, plane: &mut v4l2_plane) { + self.handle.fill_v4l2_plane(plane) + } + + #[cfg(feature = "v4l2")] + fn process_dqbuf(&mut self, device: Arc, format: &Format, buf: &V4l2Buffer) { + self.device = Some(device); + self.queue_format = Some(format.clone()); + self.buffer = Some(buf.clone()); + } +} diff --git a/vendor/cros-libva/.cargo_vcs_info.json b/vendor/cros-libva/.cargo_vcs_info.json new file mode 100644 index 0000000..ddeb78f --- /dev/null +++ b/vendor/cros-libva/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "29940e8130ecd941b59c249fb5b83b8cb4c299e0" + }, + "path_in_vcs": "lib" +} \ No newline at end of file diff --git a/vendor/cros-libva/Android.bp b/vendor/cros-libva/Android.bp new file mode 100644 index 0000000..ea7bf85 --- /dev/null +++ b/vendor/cros-libva/Android.bp @@ -0,0 +1,76 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file is generated by cargo_embargo. +// Do not modify this file because the changes will be overridden on upgrade. + +package { + default_applicable_licenses: ["external_rust_crates_cros-libva_license"], +} + +rust_test { + name: "cros-libva_test_src_lib", + crate_name: "cros_libva", + cargo_env_compat: true, + cargo_pkg_version: "0.0.8", + crate_root: "src/lib.rs", + test_suites: ["general-tests"], + auto_gen_config: true, + test_options: { + unit_test: true, + }, + edition: "2021", + rustlibs: [ + "libbitflags", + "libcrc32fast", + "liblog_rust", + "libthiserror", + ], + + vendor: true, + enabled: false, + arch: { + x86_64: { + enabled: true, + // Bindgen-generated bindings of our local libva headers. + srcs: [":libcros_libva_bindgen"], + }, + }, +} + +rust_library { + name: "libcros_libva", + crate_name: "cros_libva", + cargo_env_compat: true, + cargo_pkg_version: "0.0.8", + crate_root: "src/lib.rs", + edition: "2021", + rustlibs: [ + "libbitflags", + "liblog_rust", + "libthiserror", + ], + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], + + cfgs: [ + "libva_1_21_or_higher", + "libva_1_20_or_higher", + "libva_1_19_or_higher", + "libva_1_16_or_higher", + ], + + vendor: true, + enabled: false, + arch: { + x86_64: { + enabled: true, + // Bindgen-generated bindings of our local libva headers. + srcs: [":libcros_libva_bindgen"], + shared_libs: [ "libva" ], + }, + }, +} diff --git a/vendor/cros-libva/Cargo.toml b/vendor/cros-libva/Cargo.toml new file mode 100644 index 0000000..ddbb222 --- /dev/null +++ b/vendor/cros-libva/Cargo.toml @@ -0,0 +1,42 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "cros-libva" +version = "0.0.12" +authors = ["The Chromium OS Authors"] +description = "Safe bindings over libva" +readme = "README.md" +license = "BSD-3-Clause" +repository = "https://github.com/chromeos/cros-libva" + +[dependencies.bitflags] +version = "2.5" + +[dependencies.log] +version = "0" +features = ["release_max_level_debug"] + +[dependencies.thiserror] +version = "1" + +[dev-dependencies.crc32fast] +version = "1.2.1" + +[build-dependencies.bindgen] +version = "0.70.1" + +[build-dependencies.pkg-config] +version = "0.3.31" + +[build-dependencies.regex] +version = "1.11.1" diff --git a/vendor/cros-libva/README.md b/vendor/cros-libva/README.md new file mode 100644 index 0000000..da3e73c --- /dev/null +++ b/vendor/cros-libva/README.md @@ -0,0 +1,83 @@ +# Libva Rust Wrapper + +This crate provides lightweight and (hopefully) safe libva abstractions for use +within Rust code with minimal dependencies. It is developed for use in +ChromeOS, but has no ChromeOS specifics or dependencies and should thus be +usable anywhere. + +## Dependencies + +The native [libva](https://github.com/intel/libva) library is required at link +time, so make sure to have the `libva-dev` or equivalent package for your +distribution installed. The libva version needs to be 1.20.0 or newer. The +VA-API driver corresponding to your hardware is also required: for Intel +hardware it will be [intel-media-driver](https://github.com/intel/media-driver), +whereas AMD hardware relies on [Mesa](https://gitlab.freedesktop.org/mesa/mesa). + +An easy way to see whether everything is in order is to run the `vainfo` +utility packaged with `libva-utils` or as a standalone package in some +distributions. `vainfo` will print the VA-API version, driver string, and a +list of supported profiles and endpoints, i.e.: + +``` +vainfo: VA-API version: 1.13 (libva 2.13.0) +vainfo: Driver version: Intel iHD driver for Intel(R) Gen Graphics - 22.2.2 () +vainfo: Supported profile and entrypoints + VAProfileNone : VAEntrypointVideoProc + VAProfileNone : VAEntrypointStats + VAProfileMPEG2Simple : VAEntrypointVLD + VAProfileMPEG2Simple : VAEntrypointEncSlice + VAProfileMPEG2Main : VAEntrypointVLD + VAProfileMPEG2Main : VAEntrypointEncSlice + VAProfileH264Main : VAEntrypointVLD + etc +``` + +For decoding, the desired profile must be supported under `VAEntrypointVLD`. +For example, in order to decode VP8 media, this line must be present in the +output of `vainfo`: + +``` + VAProfileVP8Version0_3 : VAEntrypointVLD +``` + +Whereas to decode H264 Main profile media, this line must be present: + +``` + VAProfileH264Main : VAEntrypointVLD +``` + +For more information on VA-API and its usage within ChromeOS, see [this +guide](https://chromium.googlesource.com/chromium/src/+/master/docs/gpu/vaapi.md). + +cros-libva can also be built in Android. Android.bp files are provided that +should work on AOSP >= 15. Just check this repository into +external/rust/crates/cros-libva and the libcros_libva library target will be + available. + +## Using + +The name of this crate is `cros-libva` to highlight the fact that it originates +from ChromeOS and it not an official bindings. For ease of use, it is +recommended to rename it to just `libva` in your project by using the following +line in your `Cargo.toml`: + +``` +libva = { package = "cros-libva", version = "0.0.1" } +``` + +## Testing + +For a brief introduction on how to use this crate, see the +`libva_utils_mpeg2vldemo` test under `src/lib.rs`. You can also quickly test +MPEG2 decoding by running it: + +``` +cargo test -- --ignored libva_utils_mpeg2vldemo +``` + +## Credits + +The first version of this crate was written by Daniel Almeida and hosted in the +[crosvm repository](https://chromium.googlesource.com/crosvm/crosvm/) before +being split. diff --git a/vendor/cros-libva/bindgen_gen.rs b/vendor/cros-libva/bindgen_gen.rs new file mode 100644 index 0000000..9a8fb8e --- /dev/null +++ b/vendor/cros-libva/bindgen_gen.rs @@ -0,0 +1,18 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The allow list of VA functions, structures and enum values. +const ALLOW_LIST_TYPE : &str = ".*ExternalBuffers.*|.*PRIME.*|.*MPEG2.*|.*VP8.*|.*VP9.*|.*H264.*|.*HEVC.*|VACodedBufferSegment|.*AV1.*|VAEncMisc.*|VASurfaceDecodeMBErrors|VADecodeErrorType"; + +// The common bindgen builder for VA-API. +pub fn vaapi_gen_builder(builder: bindgen::Builder) -> bindgen::Builder { + builder + .derive_default(true) + .derive_eq(true) + .layout_tests(false) + .constified_enum_module("VA.*") + .allowlist_var("VA.*") + .allowlist_function("va.*") + .allowlist_type(ALLOW_LIST_TYPE) +} diff --git a/vendor/cros-libva/build.rs b/vendor/cros-libva/build.rs new file mode 100644 index 0000000..b6730e6 --- /dev/null +++ b/vendor/cros-libva/build.rs @@ -0,0 +1,141 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use regex::Regex; +use std::env::VarError; +use std::env::{self}; +use std::fs::read_to_string; +use std::path::{Path, PathBuf}; + +mod bindgen_gen; +use bindgen_gen::vaapi_gen_builder; + +/// Environment variable that can be set to point to the directory containing the `va.h`, `va_drm.h` and `va_drmcommon.h` +/// files to use to generate the bindings. +const CROS_LIBVA_H_PATH_ENV: &str = "CROS_LIBVA_H_PATH"; +const CROS_LIBVA_LIB_PATH_ENV: &str = "CROS_LIBVA_LIB_PATH"; + +/// Wrapper file to use as input of bindgen. +const WRAPPER_PATH: &str = "libva-wrapper.h"; + +// Return VA_MAJOR_VERSION and VA_MINOR_VERSION from va_version.h. +fn get_va_version(va_h_path: &str) -> (u32, u32) { + let va_version_h_path = Path::new(va_h_path).join("va/va_version.h"); + assert!( + va_version_h_path.exists(), + "{} doesn't exist", + va_version_h_path.display() + ); + let header_content = read_to_string(va_version_h_path).unwrap(); + let lines = header_content.lines(); + + const VERSION_REGEX_STRINGS: [&str; 2] = [ + r"#define VA_MAJOR_VERSION\s*[0-9]+", + r"#define VA_MINOR_VERSION\s*[0-9]+", + ]; + let mut numbers: [u32; 2] = [0; 2]; + for i in 0..2 { + let re = Regex::new(VERSION_REGEX_STRINGS[i]).unwrap(); + let match_line = lines + .clone() + .filter(|&s| re.is_match(s)) + .collect::>(); + assert_eq!( + match_line.len(), + 1, + "unexpected match for {}: {:?}", + VERSION_REGEX_STRINGS[i], + match_line + ); + let number_str = Regex::new(r"[0-9]+") + .unwrap() + .find(match_line[0]) + .unwrap() + .as_str(); + numbers[i] = number_str.parse::().unwrap(); + } + + (numbers[0], numbers[1]) +} + +fn main() { + // Do not require dependencies when generating docs. + if std::env::var("CARGO_DOC").is_ok() || std::env::var("DOCS_RS").is_ok() { + return; + } + + let va_h_path = env::var(CROS_LIBVA_H_PATH_ENV) + .or_else(|e| { + if let VarError::NotPresent = e { + let libva_library = pkg_config::probe_library("libva"); + match libva_library { + Ok(_) => Ok(libva_library.unwrap().include_paths[0] + .clone() + .into_os_string() + .into_string() + .unwrap()), + Err(e) => panic!("libva is not found in system: {}", e), + } + } else { + Err(e) + } + }) + .expect("libva header location is unknown"); + + let va_lib_path = env::var(CROS_LIBVA_LIB_PATH_ENV).unwrap_or_default(); + // Check the path exists. + if !va_h_path.is_empty() { + assert!( + Path::new(&va_h_path).exists(), + "{} doesn't exist", + va_h_path + ); + } + + let (major, minor) = get_va_version(&va_h_path); + println!("libva {}.{} is used to generate bindings", major, minor); + let va_check_version = |desired_major: u32, desired_minor: u32| { + major > desired_major || (major == desired_major && minor >= desired_minor) + }; + + if va_check_version(1, 21) { + println!("cargo::rustc-cfg=libva_1_21_or_higher"); + } + if va_check_version(1, 20) { + println!("cargo::rustc-cfg=libva_1_20_or_higher") + } + if va_check_version(1, 19) { + println!("cargo::rustc-cfg=libva_1_19_or_higher") + } + if va_check_version(1, 16) { + println!("cargo::rustc-cfg=libva_1_16_or_higher") + } + + if !va_lib_path.is_empty() { + assert!( + Path::new(&va_lib_path).exists(), + "{} doesn't exist", + va_lib_path + ); + println!("cargo:rustc-link-arg=-Wl,-rpath={}", va_lib_path); + } + + // Tell cargo to link va and va-drm objects dynamically. + println!("cargo:rustc-link-lib=dylib=va"); + println!("cargo:rustc-link-lib=dylib=va-drm"); // for the vaGetDisplayDRM entrypoint + + let mut bindings_builder = vaapi_gen_builder(bindgen::builder()).header(WRAPPER_PATH); + if !va_h_path.is_empty() { + bindings_builder = bindings_builder.clang_arg(format!("-I{}", va_h_path)); + } + let bindings = bindings_builder + .generate() + .expect("unable to generate bindings"); + + let out_path = PathBuf::from(env::var("OUT_DIR").expect("`OUT_DIR` is not set")); + + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("Couldn't write bindings!"); +} diff --git a/vendor/cros-libva/libva-wrapper.h b/vendor/cros-libva/libva-wrapper.h new file mode 100644 index 0000000..2e5ba38 --- /dev/null +++ b/vendor/cros-libva/libva-wrapper.h @@ -0,0 +1,7 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include diff --git a/vendor/cros-libva/src/bindings.rs b/vendor/cros-libva/src/bindings.rs new file mode 100644 index 0000000..1ee7a7d --- /dev/null +++ b/vendor/cros-libva/src/bindings.rs @@ -0,0 +1,15 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! This module implements the bindgen C FFI bindings for use within this crate + +#![allow(missing_docs)] +#![allow(clippy::useless_transmute)] +#![allow(clippy::too_many_arguments)] +#![allow(non_upper_case_globals)] +#![allow(non_snake_case)] +#![allow(non_camel_case_types)] +#![allow(dead_code)] + +include!(concat!(env!("OUT_DIR"), "/bindings.rs")); diff --git a/vendor/cros-libva/src/buffer.rs b/vendor/cros-libva/src/buffer.rs new file mode 100644 index 0000000..0ab539b --- /dev/null +++ b/vendor/cros-libva/src/buffer.rs @@ -0,0 +1,553 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers and helpers around `VABuffer`s. + +mod av1; +mod enc_misc; +mod h264; +mod hevc; +mod mpeg2; +mod vp8; +mod vp9; + +pub use av1::*; +pub use enc_misc::*; +pub use h264::*; +pub use hevc::*; +pub use mpeg2::*; +pub use vp8::*; +pub use vp9::*; + +use std::rc::Rc; + +use log::error; + +use crate::bindings; +use crate::va_check; +use crate::Context; +use crate::VaError; + +/// Wrapper type representing a buffer created with `vaCreateBuffer`. +pub struct Buffer { + context: Rc, + id: bindings::VABufferID, +} + +impl Buffer { + /// Creates a new buffer by wrapping a `vaCreateBuffer` call. This is just a helper for + /// [`Context::create_buffer`]. + pub(crate) fn new(context: Rc, mut type_: BufferType) -> Result { + let mut buffer_id = 0; + + /* we send all slices parameters as a single array in H264, AV1 */ + let nb_elements = match type_ { + BufferType::SliceParameter(SliceParameter::H264(ref mut params)) => { + params.inner_mut().len() + } + BufferType::SliceParameter(SliceParameter::AV1(ref mut params)) => { + params.inner_mut().len() + } + _ => 1, + }; + + let (ptr, size) = match type_ { + BufferType::PictureParameter(ref mut picture_param) => match picture_param { + PictureParameter::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVCRext(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::HEVCScc(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + PictureParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::SliceParameter(ref mut slice_param) => match slice_param { + SliceParameter::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut().as_mut_ptr() as *mut std::ffi::c_void, + std::mem::size_of::(), + ), + SliceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::HEVCRext(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + SliceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut().as_mut_ptr() as *mut std::ffi::c_void, + std::mem::size_of::(), + ), + }, + + BufferType::IQMatrix(ref mut iq_matrix) => match iq_matrix { + IQMatrix::MPEG2(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + IQMatrix::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::Probability(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + + BufferType::SliceData(ref mut data) => { + (data.as_mut_ptr() as *mut std::ffi::c_void, data.len()) + } + + BufferType::EncSequenceParameter(ref mut seq_param) => match seq_param { + EncSequenceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSequenceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncPictureParameter(ref mut picture_param) => match picture_param { + EncPictureParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::VP8(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::VP9(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncPictureParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncSliceParameter(ref mut slice_param) => match slice_param { + EncSliceParameter::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSliceParameter::HEVC(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncSliceParameter::AV1(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncMacroblockParameterBuffer(ref mut mb_param) => match mb_param { + EncMacroblockParameterBuffer::H264(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + + BufferType::EncCodedBuffer(size) => (std::ptr::null_mut(), size), + + BufferType::EncMiscParameter(ref mut enc_misc_param) => match enc_misc_param { + EncMiscParameter::FrameRate(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::RateControl(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::MaxSliceSize(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::MaxFrameSize(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::SkipFrame(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::HRD(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::QualityLevel(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + EncMiscParameter::Quantization(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + }, + }; + + // Safe because `self` represents a valid `VAContext`. `ptr` and `size` are also ensured to + // be correct, as `ptr` is just a cast to `*c_void` from a Rust struct, and `size` is + // computed from `std::mem::size_of_val`. + va_check(unsafe { + bindings::vaCreateBuffer( + context.display().handle(), + context.id(), + type_.inner(), + size as u32, + nb_elements as u32, + ptr, + &mut buffer_id, + ) + })?; + + Ok(Self { + context, + id: buffer_id, + }) + } + + /// Convenience function to return a `VABufferID` vector from a slice of `Buffer`s in order to + /// easily interface with the C API where a buffer array might be needed. + pub fn as_id_vec(buffers: &[Self]) -> Vec { + buffers.iter().map(|buffer| buffer.id).collect() + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + // Safe because `self` represents a valid buffer, created with + // vaCreateBuffers. + let status = va_check(unsafe { + bindings::vaDestroyBuffer(self.context.display().handle(), self.id) + }); + + if status.is_err() { + error!("vaDestroyBuffer failed: {}", status.unwrap_err()); + } + } +} + +/// Abstraction over `VABufferType`s. +pub enum BufferType { + /// Abstraction over `VAPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264. + PictureParameter(PictureParameter), + /// Abstraction over `VASliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264. + SliceParameter(SliceParameter), + /// Abstraction over `VAIQMatrixBufferType`. Needed for VP8, H264. + IQMatrix(IQMatrix), + /// Abstraction over `VAProbabilityDataBufferType`. Needed for VP8. + Probability(vp8::ProbabilityDataBufferVP8), + /// Abstraction over `VASliceDataBufferType`. Needed for VP9, H264. + SliceData(Vec), + /// Abstraction over `VAEncSequenceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncSequenceParameter(EncSequenceParameter), + /// Abstraction over `VAEncPictureParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncPictureParameter(EncPictureParameter), + /// Abstraction over `VAEncSliceParameterBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncSliceParameter(EncSliceParameter), + /// Abstraction over `VAEncMacroblockMapBufferType`. Needed for H264. + EncMacroblockParameterBuffer(EncMacroblockParameterBuffer), + /// Abstraction over `VAEncCodedBufferType`. Needed for MPEG2, VP8, VP9, H264, HEVC. + EncCodedBuffer(usize), + /// Abstraction over `VAEncMiscParameterBuffer`. + EncMiscParameter(EncMiscParameter), +} + +impl BufferType { + /// Returns the inner FFI buffer type. + pub(crate) fn inner(&self) -> bindings::VABufferType::Type { + match self { + BufferType::PictureParameter(_) => bindings::VABufferType::VAPictureParameterBufferType, + BufferType::SliceParameter(_) => bindings::VABufferType::VASliceParameterBufferType, + BufferType::IQMatrix(_) => bindings::VABufferType::VAIQMatrixBufferType, + BufferType::Probability(_) => bindings::VABufferType::VAProbabilityBufferType, + BufferType::SliceData { .. } => bindings::VABufferType::VASliceDataBufferType, + + BufferType::EncSequenceParameter(_) => { + bindings::VABufferType::VAEncSequenceParameterBufferType + } + + BufferType::EncPictureParameter(_) => { + bindings::VABufferType::VAEncPictureParameterBufferType + } + + BufferType::EncSliceParameter(_) => { + bindings::VABufferType::VAEncSliceParameterBufferType + } + + BufferType::EncMacroblockParameterBuffer(_) => { + bindings::VABufferType::VAEncMacroblockMapBufferType + } + + BufferType::EncCodedBuffer(_) => bindings::VABufferType::VAEncCodedBufferType, + + BufferType::EncMiscParameter(_) => bindings::VABufferType::VAEncMiscParameterBufferType, + } + } +} + +/// Abstraction over the `PictureParameterBuffer` types we support. +pub enum PictureParameter { + /// Wrapper over VAPictureParameterBufferMPEG2. + MPEG2(mpeg2::PictureParameterBufferMPEG2), + /// Wrapper over VAPictureParameterBufferVP8. + VP8(vp8::PictureParameterBufferVP8), + /// Wrapper over VAPictureParameterBufferVP9. + VP9(vp9::PictureParameterBufferVP9), + /// Wrapper over VAPictureParameterBufferH264. + H264(h264::PictureParameterBufferH264), + /// Wrapper over VAPictureParameterBufferHEVC + HEVC(hevc::PictureParameterBufferHEVC), + /// Wrapper over VAPictureParameterBufferHEVCRext + HEVCRext(hevc::PictureParameterBufferHEVCRext), + /// Wrapper over VAPictureParameterBufferHEVCScc + HEVCScc(hevc::PictureParameterBufferHEVCScc), + /// Wrapper over VADecPictureParameterBufferAV1 + AV1(av1::PictureParameterBufferAV1), +} + +/// Abstraction over the `SliceParameterBuffer` types we support +pub enum SliceParameter { + /// Wrapper over VASliceParameterBufferMPEG2 + MPEG2(mpeg2::SliceParameterBufferMPEG2), + /// Wrapper over VASliceParameterBufferVP8 + VP8(vp8::SliceParameterBufferVP8), + /// Wrapper over VASliceParameterBufferVP9 + VP9(vp9::SliceParameterBufferVP9), + /// Wrapper over VASliceParameterBufferH264 + H264(h264::SliceParameterBufferH264), + /// Wrapper over VASliceParameterBufferHEVC + HEVC(hevc::SliceParameterBufferHEVC), + /// Wrapper over VASliceParameterBufferHEVCRext + HEVCRext(hevc::SliceParameterBufferHEVCRext), + /// Wrapper over VASliceParameterBufferAV1 + AV1(av1::SliceParameterBufferAV1), +} + +/// Abstraction over the `IQMatrixBuffer` types we support. +pub enum IQMatrix { + /// Abstraction over `VAIQMatrixBufferMPEG2` + MPEG2(mpeg2::IQMatrixBufferMPEG2), + /// Abstraction over `VAIQMatrixBufferVP8` + VP8(vp8::IQMatrixBufferVP8), + /// Abstraction over `VAIQMatrixBufferH264` + H264(h264::IQMatrixBufferH264), + /// Abstraction over `VAIQMatrixBufferHEVC` + HEVC(hevc::IQMatrixBufferHEVC), +} + +/// Abstraction over the `EncSequenceParameter` types we support. +pub enum EncSequenceParameter { + /// Abstraction over `VAEncSequenceParameterBufferH264` + H264(h264::EncSequenceParameterBufferH264), + /// Abstraction over `VAEncSequenceParameterBufferHEVC` + HEVC(hevc::EncSequenceParameterBufferHEVC), + /// Abstraction over `VAEncSequenceParameterBufferVP8` + VP8(vp8::EncSequenceParameterBufferVP8), + /// Abstraction over `VAEncSequenceParameterBufferVP9` + VP9(vp9::EncSequenceParameterBufferVP9), + /// Abstraction over `VAEncSequenceParameterBufferAV1` + AV1(av1::EncSequenceParameterBufferAV1), +} + +/// Abstraction over the `EncPictureParameter` types we support. +pub enum EncPictureParameter { + /// Abstraction over `VAEncPictureParameterBufferH264` + H264(h264::EncPictureParameterBufferH264), + /// Abstraction over `VAEncPictureParameterBufferHEVC` + HEVC(hevc::EncPictureParameterBufferHEVC), + /// Abstraction over `VAEncPictureParameterBufferVP8` + VP8(vp8::EncPictureParameterBufferVP8), + /// Abstraction over `VAEncPictureParameterBufferVP9` + VP9(vp9::EncPictureParameterBufferVP9), + /// Abstraction over `VAEncPictureParameterBufferAV1` + AV1(av1::EncPictureParameterBufferAV1), +} + +/// Abstraction over the `EncSliceParameter` types we support. +pub enum EncSliceParameter { + /// Abstraction over `VAEncSliceParameterBufferH264` + H264(h264::EncSliceParameterBufferH264), + /// Abstraction over `VAEncSliceParameterBufferHEVC` + HEVC(hevc::EncSliceParameterBufferHEVC), + /// Abstraction over `VAEncTileGroupBufferAV1` + AV1(av1::EncTileGroupBufferAV1), +} + +/// Abstraction over the `EncMacroblockParameterBuffer` types we support. +pub enum EncMacroblockParameterBuffer { + /// Abstraction over `VAEncMacroblockParameterBufferH264` + H264(h264::EncMacroblockParameterBufferH264), +} + +/// Wrapper type representing a buffer created with `vaCreateBuffer` with VAEncCodedBufferType. +pub struct EncCodedBuffer(Buffer); + +impl EncCodedBuffer { + pub(crate) fn new(context: Rc, size: usize) -> Result { + Ok(Self(Buffer::new( + context, + BufferType::EncCodedBuffer(size), + )?)) + } + + /// Convenience function to return buffer's `VABufferID`. + pub fn id(&self) -> bindings::VABufferID { + self.0.id + } +} + +/// Helper to access a single segment of mapped coded buffer +pub struct MappedCodedSegment<'s> { + pub bit_offset: u32, + pub status: u32, + pub buf: &'s [u8], +} + +/// Helper to access segments of mapped coded buffer +pub struct MappedCodedBuffer<'p> { + segments: Vec>, + buffer: &'p EncCodedBuffer, +} + +impl<'p> MappedCodedBuffer<'p> { + /// Map a 'VAEncCodedBufferType' buffer. + pub fn new(buffer: &'p EncCodedBuffer) -> Result { + let mut addr = std::ptr::null_mut(); + let mut segments = Vec::new(); + + va_check(unsafe { + bindings::vaMapBuffer(buffer.0.context.display().handle(), buffer.id(), &mut addr) + })?; + + while !addr.is_null() { + let segment: &bindings::VACodedBufferSegment = + unsafe { &*(addr as *const bindings::VACodedBufferSegment) }; + + let size = segment.size; + let buf = segment.buf; + + let buf = unsafe { std::slice::from_raw_parts(buf as *mut u8, size as usize) }; + + segments.push(MappedCodedSegment { + bit_offset: segment.bit_offset, + status: segment.status, + buf, + }); + + addr = segment.next; + } + + Ok(Self { segments, buffer }) + } + + /// Returns the iterator over segments + pub fn iter(&self) -> impl Iterator> { + self.segments.iter() + } + + /// Returns the segments of mapped coded buffers. + pub fn segments(&self) -> &Vec> { + &self.segments + } +} + +impl<'p> Drop for MappedCodedBuffer<'p> { + fn drop(&mut self) { + let status = va_check(unsafe { + bindings::vaUnmapBuffer(self.buffer.0.context.display().handle(), self.buffer.id()) + }); + + if status.is_err() { + error!("vaUnmapBuffer failed: {}", status.unwrap_err()); + } + } +} + +/// Abstraction over the `EncMiscParameterBuffer` types we support. +pub enum EncMiscParameter { + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterFrameRate`. + FrameRate(EncMiscParameterFrameRate), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterRateControl`. + RateControl(EncMiscParameterRateControl), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterMaxSliceSize`. + MaxSliceSize(EncMiscParameterMaxSliceSize), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterBufferMaxFrameSize`. + MaxFrameSize(EncMiscParameterBufferMaxFrameSize), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterSkipFrame`. + SkipFrame(EncMiscParameterSkipFrame), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterHRD`. + HRD(EncMiscParameterHRD), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterBufferQualityLevel`. + QualityLevel(EncMiscParameterBufferQualityLevel), + /// Wrapper over `VAEncMiscParameterBuffer` with `VAEncMiscParameterQuantization`. + Quantization(EncMiscParameterQuantization), +} diff --git a/vendor/cros-libva/src/buffer/av1.rs b/vendor/cros-libva/src/buffer/av1.rs new file mode 100644 index 0000000..bc60782 --- /dev/null +++ b/vendor/cros-libva/src/buffer/av1.rs @@ -0,0 +1,1156 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around AV1 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `seq_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1SeqFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1); + +impl AV1SeqFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + still_picture: u32, + use_128x128_superblock: u32, + enable_filter_intra: u32, + enable_intra_edge_filter: u32, + enable_interintra_compound: u32, + enable_masked_compound: u32, + enable_dual_filter: u32, + enable_order_hint: u32, + enable_jnt_comp: u32, + enable_cdef: u32, + mono_chrome: u32, + color_range: u32, + subsampling_x: u32, + subsampling_y: u32, + chroma_sample_position: u32, + film_grain_params_present: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + still_picture, + use_128x128_superblock, + enable_filter_intra, + enable_intra_edge_filter, + enable_interintra_compound, + enable_masked_compound, + enable_dual_filter, + enable_order_hint, + enable_jnt_comp, + enable_cdef, + mono_chrome, + color_range, + subsampling_x, + subsampling_y, + chroma_sample_position, + film_grain_params_present, + 0, + ); + + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1 { + fields: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `segment_info_fields` bindgen field in `VASegmentationStructAV1`. +pub struct AV1SegmentInfoFields(bindings::_VASegmentationStructAV1__bindgen_ty_1); + +impl AV1SegmentInfoFields { + /// Creates the bindgen field + pub fn new(enabled: u32, update_map: u32, temporal_update: u32, update_data: u32) -> Self { + let _bitfield_1 = + bindings::_VASegmentationStructAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + enabled, + update_map, + temporal_update, + update_data, + 0, + ); + + Self(bindings::_VASegmentationStructAV1__bindgen_ty_1 { + bits: bindings::_VASegmentationStructAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `seg_info` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1Segmentation(bindings::VASegmentationStructAV1); + +impl AV1Segmentation { + /// Creates the bindgen field + pub fn new( + segment_info_fields: &AV1SegmentInfoFields, + feature_data: [[i16; 8usize]; 8usize], + feature_mask: [u8; 8usize], + ) -> Self { + let segment_info_fields = segment_info_fields.0; + Self(bindings::VASegmentationStructAV1 { + segment_info_fields, + feature_data, + feature_mask, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `film_grain_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1FilmGrainFields(bindings::_VAFilmGrainStructAV1__bindgen_ty_1); + +impl AV1FilmGrainFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + apply_grain: u32, + chroma_scaling_from_luma: u32, + grain_scaling_minus_8: u32, + ar_coeff_lag: u32, + ar_coeff_shift_minus_6: u32, + grain_scale_shift: u32, + overlap_flag: u32, + clip_to_restricted_range: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAFilmGrainStructAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + apply_grain, + chroma_scaling_from_luma, + grain_scaling_minus_8, + ar_coeff_lag, + ar_coeff_shift_minus_6, + grain_scale_shift, + overlap_flag, + clip_to_restricted_range, + 0, + ); + Self(bindings::_VAFilmGrainStructAV1__bindgen_ty_1 { + bits: bindings::_VAFilmGrainStructAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `film_grain_info` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1FilmGrain(bindings::VAFilmGrainStructAV1); + +impl AV1FilmGrain { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + film_grain_info_fields: &AV1FilmGrainFields, + grain_seed: u16, + num_y_points: u8, + point_y_value: [u8; 14usize], + point_y_scaling: [u8; 14usize], + num_cb_points: u8, + point_cb_value: [u8; 10usize], + point_cb_scaling: [u8; 10usize], + num_cr_points: u8, + point_cr_value: [u8; 10usize], + point_cr_scaling: [u8; 10usize], + ar_coeffs_y: [i8; 24usize], + ar_coeffs_cb: [i8; 25usize], + ar_coeffs_cr: [i8; 25usize], + cb_mult: u8, + cb_luma_mult: u8, + cb_offset: u16, + cr_mult: u8, + cr_luma_mult: u8, + cr_offset: u16, + ) -> Self { + let film_grain_info_fields = film_grain_info_fields.0; + Self(bindings::VAFilmGrainStructAV1 { + film_grain_info_fields, + grain_seed, + num_y_points, + point_y_value, + point_y_scaling, + num_cb_points, + point_cb_value, + point_cb_scaling, + num_cr_points, + point_cr_value, + point_cr_scaling, + ar_coeffs_y, + ar_coeffs_cb, + ar_coeffs_cr, + cb_mult, + cb_luma_mult, + cb_offset, + cr_mult, + cr_luma_mult, + cr_offset, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `pic_info_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1PicInfoFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2); + +impl AV1PicInfoFields { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + show_frame: u32, + showable_frame: u32, + error_resilient_mode: u32, + disable_cdf_update: u32, + allow_screen_content_tools: u32, + force_integer_mv: u32, + allow_intrabc: u32, + use_superres: u32, + allow_high_precision_mv: u32, + is_motion_mode_switchable: u32, + use_ref_frame_mvs: u32, + disable_frame_end_update_cdf: u32, + uniform_tile_spacing_flag: u32, + allow_warped_motion: u32, + large_scale_tile: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + show_frame, + showable_frame, + error_resilient_mode, + disable_cdf_update, + allow_screen_content_tools, + force_integer_mv, + allow_intrabc, + use_superres, + allow_high_precision_mv, + is_motion_mode_switchable, + use_ref_frame_mvs, + disable_frame_end_update_cdf, + uniform_tile_spacing_flag, + allow_warped_motion, + large_scale_tile, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `loop_filter_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1LoopFilterFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3); + +impl AV1LoopFilterFields { + /// Creates the wrapper + pub fn new(sharpness_level: u8, mode_ref_delta_enabled: u8, mode_ref_delta_update: u8) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + sharpness_level, + mode_ref_delta_enabled, + mode_ref_delta_update, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `wm` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1WarpedMotionParams(bindings::VAWarpedMotionParamsAV1); + +impl AV1WarpedMotionParams { + /// Creates the wrapper + pub fn new( + wmtype: bindings::VAAV1TransformationType::Type, + wmmat: [i32; 8], + invalid: u8, + ) -> Self { + Self(bindings::VAWarpedMotionParamsAV1 { + wmtype, + wmmat, + invalid, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `loop_restoration_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1LoopRestorationFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6); + +impl AV1LoopRestorationFields { + /// Creates the wrapper + pub fn new( + yframe_restoration_type: u16, + cbframe_restoration_type: u16, + crframe_restoration_type: u16, + lr_unit_shift: u16, + lr_uv_shift: u16, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1::new_bitfield_1( + yframe_restoration_type, + cbframe_restoration_type, + crframe_restoration_type, + lr_unit_shift, + lr_uv_shift, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `mode_control_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1ModeControlFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5); + +impl AV1ModeControlFields { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + delta_q_present_flag: u32, + log2_delta_q_res: u32, + delta_lf_present_flag: u32, + log2_delta_lf_res: u32, + delta_lf_multi: u32, + tx_mode: u32, + reference_select: u32, + reduced_tx_set_used: u32, + skip_mode_present: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1::new_bitfield_1( + delta_q_present_flag, + log2_delta_q_res, + delta_lf_present_flag, + log2_delta_lf_res, + delta_lf_multi, + tx_mode, + reference_select, + reduced_tx_set_used, + skip_mode_present, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// Wrapper over the `qmatrix_fields` bindgen field in `VADecPictureParameterBufferAV1`. +pub struct AV1QMatrixFields(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4); + +impl AV1QMatrixFields { + /// Creates the wrapper + pub fn new(using_qmatrix: u16, qm_y: u16, qm_u: u16, qm_v: u16) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1::new_bitfield_1( + using_qmatrix, + qm_y, + qm_u, + qm_v, + 0, + ); + Self(bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4 { + bits: bindings::_VADecPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +/// A wrapper over `VADecPictureParameterBufferAV1` FFI type +pub struct PictureParameterBufferAV1(Box); + +impl PictureParameterBufferAV1 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + profile: u8, + order_hint_bits_minus_1: u8, + bit_depth_idx: u8, + matrix_coefficients: u8, + seq_info_fields: &AV1SeqFields, + current_frame: bindings::VASurfaceID, + current_display_picture: bindings::VASurfaceID, + mut anchor_frames_list: Vec, + frame_width_minus1: u16, + frame_height_minus1: u16, + output_frame_width_in_tiles_minus_1: u16, + output_frame_height_in_tiles_minus_1: u16, + ref_frame_map: [bindings::VASurfaceID; 8usize], + ref_frame_idx: [u8; 7usize], + primary_ref_frame: u8, + order_hint: u8, + seg_info: &AV1Segmentation, + film_grain_info: &AV1FilmGrain, + tile_cols: u8, + tile_rows: u8, + width_in_sbs_minus_1: [u16; 63usize], + height_in_sbs_minus_1: [u16; 63usize], + tile_count_minus_1: u16, + context_update_tile_id: u16, + pic_info_fields: &AV1PicInfoFields, + superres_scale_denominator: u8, + interp_filter: u8, + filter_level: [u8; 2usize], + filter_level_u: u8, + filter_level_v: u8, + loop_filter_info_fields: &AV1LoopFilterFields, + ref_deltas: [i8; 8usize], + mode_deltas: [i8; 2usize], + base_qindex: u8, + y_dc_delta_q: i8, + u_dc_delta_q: i8, + u_ac_delta_q: i8, + v_dc_delta_q: i8, + v_ac_delta_q: i8, + qmatrix_fields: &AV1QMatrixFields, + mode_control_fields: &AV1ModeControlFields, + cdef_damping_minus_3: u8, + cdef_bits: u8, + cdef_y_strengths: [u8; 8usize], + cdef_uv_strengths: [u8; 8usize], + loop_restoration_fields: &AV1LoopRestorationFields, + wm: &[AV1WarpedMotionParams; 7usize], + ) -> Self { + let seq_info_fields = seq_info_fields.0; + let seg_info = seg_info.0; + let pic_info_fields = pic_info_fields.0; + let loop_filter_info_fields = loop_filter_info_fields.0; + let qmatrix_fields = qmatrix_fields.0; + let mode_control_fields = mode_control_fields.0; + + let anchor_frames_num = anchor_frames_list.len() as u8; + let anchor_frames_list = anchor_frames_list.as_mut_ptr(); + + let film_grain_info = film_grain_info.0; + let loop_restoration_fields = loop_restoration_fields.0; + + // Will not panic, as the arrays are the same size. + let wm = wm + .iter() + .map(|wm| wm.0) + .collect::>() + .try_into() + .unwrap(); + + Self(Box::new(bindings::VADecPictureParameterBufferAV1 { + profile, + order_hint_bits_minus_1, + bit_depth_idx, + matrix_coefficients, + seq_info_fields, + current_frame, + current_display_picture, + anchor_frames_num, + anchor_frames_list, + frame_width_minus1, + frame_height_minus1, + output_frame_width_in_tiles_minus_1, + output_frame_height_in_tiles_minus_1, + ref_frame_map, + ref_frame_idx, + primary_ref_frame, + order_hint, + seg_info, + film_grain_info, + tile_cols, + tile_rows, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + tile_count_minus_1, + context_update_tile_id, + pic_info_fields, + superres_scale_denominator, + interp_filter, + filter_level, + filter_level_u, + filter_level_v, + loop_filter_info_fields, + ref_deltas, + mode_deltas, + base_qindex, + y_dc_delta_q, + u_dc_delta_q, + u_ac_delta_q, + v_dc_delta_q, + v_ac_delta_q, + qmatrix_fields, + mode_control_fields, + cdef_damping_minus_3, + cdef_bits, + cdef_y_strengths, + cdef_uv_strengths, + loop_restoration_fields, + wm, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VADecPictureParameterBufferAV1 { + self.0.as_mut() + } +} + +/// A wrapper over an array of the `VASliceParameterBufferAV1` FFI type. This +/// allows for passing all tile parameters in a single call if multiple tiles +/// are present in the tile group. +#[derive(Default)] +pub struct SliceParameterBufferAV1(Vec); + +impl SliceParameterBufferAV1 { + /// Creates the wrapper + pub fn new() -> Self { + Default::default() + } + + /// Adds a slice parameter to the wrapper + #[allow(clippy::too_many_arguments)] + pub fn add_slice_parameter( + &mut self, + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + tile_row: u16, + tile_column: u16, + tg_start: u16, + tg_end: u16, + anchor_frame_idx: u8, + tile_idx_in_tile_list: u16, + ) { + self.0.push(bindings::VASliceParameterBufferAV1 { + slice_data_size, + slice_data_offset, + slice_data_flag, + tile_row, + tile_column, + tg_start, + tg_end, + anchor_frame_idx, + tile_idx_in_tile_list, + va_reserved: Default::default(), + }); + } + + pub(crate) fn inner_mut(&mut self) -> &mut Vec { + self.0.as_mut() + } +} + +pub struct AV1EncSeqFields(bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1); + +impl AV1EncSeqFields { + pub fn new( + still_picture: bool, + use_128x128_superblock: bool, + enable_filter_intra: bool, + enable_intra_edge_filter: bool, + enable_interintra_compound: bool, + enable_masked_compound: bool, + enable_warped_motion: bool, + enable_dual_filter: bool, + enable_order_hint: bool, + enable_jnt_comp: bool, + enable_ref_frame_mvs: bool, + enable_superres: bool, + enable_cdef: bool, + enable_restoration: bool, + bit_depth_minus8: u32, + subsampling_x: bool, + subsampling_y: bool, + mono_chrome: bool, + ) -> Self { + let still_picture = still_picture as u32; + let use_128x128_superblock = use_128x128_superblock as u32; + let enable_filter_intra = enable_filter_intra as u32; + let enable_intra_edge_filter = enable_intra_edge_filter as u32; + let enable_interintra_compound = enable_interintra_compound as u32; + let enable_masked_compound = enable_masked_compound as u32; + let enable_warped_motion = enable_warped_motion as u32; + let enable_dual_filter = enable_dual_filter as u32; + let enable_order_hint = enable_order_hint as u32; + let enable_jnt_comp = enable_jnt_comp as u32; + let enable_ref_frame_mvs = enable_ref_frame_mvs as u32; + let enable_superres = enable_superres as u32; + let enable_cdef = enable_cdef as u32; + let enable_restoration = enable_restoration as u32; + let subsampling_x = subsampling_x as u32; + let subsampling_y = subsampling_y as u32; + let mono_chrome = mono_chrome as u32; + + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + still_picture, + use_128x128_superblock, + enable_filter_intra, + enable_intra_edge_filter, + enable_interintra_compound, + enable_masked_compound, + enable_warped_motion, + enable_dual_filter, + enable_order_hint, + enable_jnt_comp, + enable_ref_frame_mvs, + enable_superres, + enable_cdef, + enable_restoration, + bit_depth_minus8, + subsampling_x, + subsampling_y, + #[cfg(libva_1_19_or_higher)] + mono_chrome, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSequenceParameterBufferAV1(Box); + +impl EncSequenceParameterBufferAV1 { + pub fn new( + seq_profile: u8, + seq_level_idx: u8, + seq_tier: u8, + hierarchical_flag: u8, + intra_period: u32, + ip_period: u32, + bits_per_second: u32, + seq_fields: &AV1EncSeqFields, + order_hint_bits_minus_1: u8, + ) -> Self { + let seq_fields = seq_fields.0; + + Self(Box::new(bindings::_VAEncSequenceParameterBufferAV1 { + seq_profile, + seq_level_idx, + seq_tier, + #[cfg(libva_1_16_or_higher)] + hierarchical_flag, + intra_period, + ip_period, + bits_per_second, + seq_fields, + order_hint_bits_minus_1, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferAV1 { + &mut self.0 + } +} + +#[derive(Default)] +pub struct RefFrameCtrlAV1(bindings::VARefFrameCtrlAV1); + +impl RefFrameCtrlAV1 { + pub fn new( + search_idx0: u32, + search_idx1: u32, + search_idx2: u32, + search_idx3: u32, + search_idx4: u32, + search_idx5: u32, + search_idx6: u32, + ) -> Self { + let _bitfield_1 = bindings::VARefFrameCtrlAV1__bindgen_ty_1::new_bitfield_1( + search_idx0, + search_idx1, + search_idx2, + search_idx3, + search_idx4, + search_idx5, + search_idx6, + Default::default(), + ); + + Self(bindings::VARefFrameCtrlAV1 { + fields: bindings::VARefFrameCtrlAV1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncPictureFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1); + +impl AV1EncPictureFlags { + pub fn new( + frame_type: u32, + error_resilient_mode: bool, + disable_cdf_update: bool, + use_superres: bool, + allow_high_precision_mv: bool, + use_ref_frame_mvs: bool, + disable_frame_end_update_cdf: bool, + reduced_tx_set: bool, + enable_frame_obu: bool, + long_term_reference: bool, + disable_frame_recon: bool, + allow_intrabc: bool, + palette_mode_enable: bool, + allow_screen_content_tools: bool, + force_integer_mv: bool, + ) -> Self { + let error_resilient_mode = error_resilient_mode as u32; + let disable_cdf_update = disable_cdf_update as u32; + let use_superres = use_superres as u32; + let allow_high_precision_mv = allow_high_precision_mv as u32; + let use_ref_frame_mvs = use_ref_frame_mvs as u32; + let disable_frame_end_update_cdf = disable_frame_end_update_cdf as u32; + let reduced_tx_set = reduced_tx_set as u32; + let enable_frame_obu = enable_frame_obu as u32; + let long_term_reference = long_term_reference as u32; + let disable_frame_recon = disable_frame_recon as u32; + let allow_intrabc = allow_intrabc as u32; + let palette_mode_enable = palette_mode_enable as u32; + #[cfg(libva_1_21_or_higher)] + let allow_screen_content_tools = allow_screen_content_tools as u32; + #[cfg(libva_1_21_or_higher)] + let force_integer_mv = force_integer_mv as u32; + + let _bitfield_1 = { + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + frame_type, + error_resilient_mode, + disable_cdf_update, + use_superres, + allow_high_precision_mv, + use_ref_frame_mvs, + disable_frame_end_update_cdf, + reduced_tx_set, + enable_frame_obu, + long_term_reference, + disable_frame_recon, + allow_intrabc, + palette_mode_enable, + #[cfg(libva_1_21_or_higher)] + allow_screen_content_tools, + #[cfg(libva_1_21_or_higher)] + force_integer_mv, + Default::default(), + ) + }; + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncLoopFilterFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2); + +impl AV1EncLoopFilterFlags { + pub fn new( + sharpness_level: u8, + mode_ref_delta_enabled: bool, + mode_ref_delta_update: bool, + ) -> Self { + let mode_ref_delta_enabled = mode_ref_delta_enabled as u8; + let mode_ref_delta_update = mode_ref_delta_update as u8; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + sharpness_level, + mode_ref_delta_enabled, + mode_ref_delta_update, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncQMatrixFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3); + +impl AV1EncQMatrixFlags { + pub fn new(using_qmatrix: bool, qm_y: u16, qm_u: u16, qm_v: u16) -> Self { + let using_qmatrix = using_qmatrix as u16; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + using_qmatrix, + qm_y, + qm_u, + qm_v, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_3__bindgen_ty_1 { + _bitfield_1, + _bitfield_align_1: Default::default(), + }, + }) + } +} + +#[derive(Default)] +pub struct AV1EncModeControlFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4); + +impl AV1EncModeControlFlags { + pub fn new( + delta_q_present: bool, + delta_q_res: u32, + delta_lf_present: bool, + delta_lf_res: u32, + delta_lf_multi: bool, + tx_mode: u32, + reference_mode: u32, + skip_mode_present: bool, + ) -> Self { + let delta_q_present = delta_q_present as u32; + let delta_lf_present = delta_lf_present as u32; + let delta_lf_multi = delta_lf_multi as u32; + let skip_mode_present = skip_mode_present as u32; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1::new_bitfield_1( + delta_q_present, + delta_q_res, + delta_lf_present, + delta_lf_res, + delta_lf_multi, + tx_mode, + reference_mode, + skip_mode_present, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_4__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSegParamFlagsAV1(bindings::_VAEncSegParamAV1__bindgen_ty_1); + +impl EncSegParamFlagsAV1 { + pub fn new( + segmentation_enabled: bool, + segmentation_update_map: bool, + segmentation_temporal_update: bool, + ) -> Self { + let segmentation_enabled = segmentation_enabled as u8; + let segmentation_update_map = segmentation_update_map as u8; + let segmentation_temporal_update = segmentation_temporal_update as u8; + + let _bitfield_1 = bindings::_VAEncSegParamAV1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + segmentation_enabled, + segmentation_update_map, + segmentation_temporal_update, + Default::default(), + ); + + Self(bindings::_VAEncSegParamAV1__bindgen_ty_1 { + bits: bindings::_VAEncSegParamAV1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncSegParamAV1(bindings::VAEncSegParamAV1); + +impl EncSegParamAV1 { + pub fn new( + seg_flags: &EncSegParamFlagsAV1, + segment_number: u8, + feature_data: [[i16; 8usize]; 8usize], + feature_mask: [u8; 8usize], + ) -> Self { + let seg_flags = seg_flags.0; + + Self(bindings::_VAEncSegParamAV1 { + seg_flags, + segment_number, + feature_data, + feature_mask, + va_reserved: Default::default(), + }) + } +} + +pub struct AV1EncLoopRestorationFlags(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5); + +impl AV1EncLoopRestorationFlags { + pub fn new( + yframe_restoration_type: u16, + cbframe_restoration_type: u16, + crframe_restoration_type: u16, + lr_unit_shift: u16, + lr_uv_shift: bool, + ) -> Self { + let lr_uv_shift = lr_uv_shift as u16; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1::new_bitfield_1( + yframe_restoration_type, + cbframe_restoration_type, + crframe_restoration_type, + lr_unit_shift, + lr_uv_shift, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_5__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default, Copy, Clone)] +pub struct EncWarpedMotionParamsAV1(bindings::VAEncWarpedMotionParamsAV1); + +impl EncWarpedMotionParamsAV1 { + pub fn new( + wmtype: bindings::VAEncTransformationTypeAV1::Type, + wmmat: [i32; 8usize], + invalid: u8, + ) -> Self { + Self(bindings::_VAEncWarpedMotionParamsAV1 { + wmtype, + wmmat, + invalid, + va_reserved: Default::default(), + }) + } +} + +pub struct AV1EncTileGroupObuHdrInfo(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6); + +impl AV1EncTileGroupObuHdrInfo { + pub fn new( + obu_extension_flag: bool, + obu_has_size_field: bool, + temporal_id: u8, + spatial_id: u8, + ) -> Self { + let obu_extension_flag = obu_extension_flag as u8; + let obu_has_size_field = obu_has_size_field as u8; + + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1::new_bitfield_1( + obu_extension_flag, + obu_has_size_field, + temporal_id, + spatial_id, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6 { + bits: bindings::_VAEncPictureParameterBufferAV1__bindgen_ty_6__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncPictureParameterBufferAV1(Box); + +impl EncPictureParameterBufferAV1 { + pub fn new( + frame_width_minus_1: u16, + frame_height_minus_1: u16, + reconstructed_frame: bindings::VASurfaceID, + coded_buf: bindings::VABufferID, + reference_frames: [bindings::VASurfaceID; 8usize], + ref_frame_idx: [u8; 7usize], + hierarchical_level_plus1: u8, + primary_ref_frame: u8, + order_hint: u8, + refresh_frame_flags: u8, + ref_frame_ctrl_l0: &RefFrameCtrlAV1, + ref_frame_ctrl_l1: &RefFrameCtrlAV1, + picture_flags: &AV1EncPictureFlags, + seg_id_block_size: u8, + num_tile_groups_minus1: u8, + temporal_id: u8, + filter_level: [u8; 2usize], + filter_level_u: u8, + filter_level_v: u8, + loop_filter_flags: &AV1EncLoopFilterFlags, + superres_scale_denominator: u8, + interpolation_filter: u8, + ref_deltas: [i8; 8usize], + mode_deltas: [i8; 2usize], + base_qindex: u8, + y_dc_delta_q: i8, + u_dc_delta_q: i8, + u_ac_delta_q: i8, + v_dc_delta_q: i8, + v_ac_delta_q: i8, + min_base_qindex: u8, + max_base_qindex: u8, + qmatrix_flags: &AV1EncQMatrixFlags, + mode_control_flags: &AV1EncModeControlFlags, + segments: &EncSegParamAV1, + tile_cols: u8, + tile_rows: u8, + width_in_sbs_minus_1: [u16; 63usize], + height_in_sbs_minus_1: [u16; 63usize], + context_update_tile_id: u16, + cdef_damping_minus_3: u8, + cdef_bits: u8, + cdef_y_strengths: [u8; 8usize], + cdef_uv_strengths: [u8; 8usize], + loop_restoration_flags: &AV1EncLoopRestorationFlags, + wm: [EncWarpedMotionParamsAV1; 7usize], + bit_offset_qindex: u32, + bit_offset_segmentation: u32, + bit_offset_loopfilter_params: u32, + bit_offset_cdef_params: u32, + size_in_bits_cdef_params: u32, + byte_offset_frame_hdr_obu_size: u32, + size_in_bits_frame_hdr_obu: u32, + tile_group_obu_hdr_info: &AV1EncTileGroupObuHdrInfo, + number_skip_frames: u8, + skip_frames_reduced_size: i32, + ) -> Self { + let ref_frame_ctrl_l0 = ref_frame_ctrl_l0.0; + let ref_frame_ctrl_l1 = ref_frame_ctrl_l1.0; + let picture_flags = picture_flags.0; + let loop_filter_flags = loop_filter_flags.0; + let qmatrix_flags = qmatrix_flags.0; + let mode_control_flags = mode_control_flags.0; + let segments = segments.0; + let loop_restoration_flags = loop_restoration_flags.0; + let wm = wm.map(|e| e.0); + let tile_group_obu_hdr_info = tile_group_obu_hdr_info.0; + + Self(Box::new(bindings::_VAEncPictureParameterBufferAV1 { + frame_width_minus_1, + frame_height_minus_1, + reconstructed_frame, + coded_buf, + reference_frames, + ref_frame_idx, + #[cfg(libva_1_19_or_higher)] + hierarchical_level_plus1, + primary_ref_frame, + order_hint, + refresh_frame_flags, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + picture_flags, + seg_id_block_size, + num_tile_groups_minus1, + temporal_id, + filter_level, + filter_level_u, + filter_level_v, + loop_filter_flags, + superres_scale_denominator, + interpolation_filter, + ref_deltas, + mode_deltas, + base_qindex, + y_dc_delta_q, + u_dc_delta_q, + u_ac_delta_q, + v_dc_delta_q, + v_ac_delta_q, + min_base_qindex, + max_base_qindex, + qmatrix_flags, + mode_control_flags, + segments, + tile_cols, + tile_rows, + width_in_sbs_minus_1, + height_in_sbs_minus_1, + context_update_tile_id, + cdef_damping_minus_3, + cdef_bits, + cdef_y_strengths, + cdef_uv_strengths, + loop_restoration_flags, + wm, + bit_offset_qindex, + bit_offset_segmentation, + bit_offset_loopfilter_params, + bit_offset_cdef_params, + size_in_bits_cdef_params, + byte_offset_frame_hdr_obu_size, + size_in_bits_frame_hdr_obu, + tile_group_obu_hdr_info, + number_skip_frames, + skip_frames_reduced_size, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferAV1 { + &mut self.0 + } +} + +pub struct EncTileGroupBufferAV1(Box); + +impl EncTileGroupBufferAV1 { + pub fn new(tg_start: u8, tg_end: u8) -> Self { + Self(Box::new(bindings::VAEncTileGroupBufferAV1 { + tg_start, + tg_end, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncTileGroupBufferAV1 { + &mut self.0 + } +} diff --git a/vendor/cros-libva/src/buffer/enc_misc.rs b/vendor/cros-libva/src/buffer/enc_misc.rs new file mode 100644 index 0000000..5a5001c --- /dev/null +++ b/vendor/cros-libva/src/buffer/enc_misc.rs @@ -0,0 +1,337 @@ +// Copyright 2024 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around `VAEncMisc*` types. + +use crate::bindings; + +#[repr(C)] +#[derive(Default)] +pub struct MiscEncParamBuffer { + hdr: bindings::VAEncMiscParameterBuffer, + value: T, +} + +impl MiscEncParamBuffer { + fn new(type_: bindings::VAEncMiscParameterType::Type, value: T) -> Self { + Self { + hdr: bindings::_VAEncMiscParameterBuffer { + type_, + data: Default::default(), + }, + value, + } + } + + fn new_boxed(type_: bindings::VAEncMiscParameterType::Type, value: T) -> Box { + Box::new(Self::new(type_, value)) + } +} + +#[derive(Default)] +pub struct EncMiscParameterFrameRate( + Box>, +); + +impl EncMiscParameterFrameRate { + pub fn new(framerate: u32, temporal_id: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + temporal_id, + Default::default(), + ); + + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeFrameRate, + bindings::_VAEncMiscParameterFrameRate { + framerate, + framerate_flags: bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct RcFlags(bindings::_VAEncMiscParameterRateControl__bindgen_ty_1); + +impl RcFlags { + pub fn new( + reset: u32, + disable_frame_skip: u32, + disable_bit_stuffing: u32, + mb_rate_control: u32, + temporal_id: u32, + cfs_i_frames: u32, + enable_parallel_brc: u32, + enable_dynamic_scaling: u32, + frame_tolerance_mode: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + reset, + disable_frame_skip, + disable_bit_stuffing, + mb_rate_control, + temporal_id, + cfs_i_frames, + enable_parallel_brc, + enable_dynamic_scaling, + frame_tolerance_mode, + Default::default(), + ); + + Self(bindings::_VAEncMiscParameterRateControl__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct EncMiscParameterRateControl( + Box>, +); + +impl EncMiscParameterRateControl { + pub fn new( + bits_per_second: u32, + target_percentage: u32, + window_size: u32, + initial_qp: u32, + min_qp: u32, + basic_unit_size: u32, + rc_flags: RcFlags, + icq_quality_factor: u32, + max_qp: u32, + quality_factor: u32, + target_frame_size: u32, + ) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeRateControl, + bindings::VAEncMiscParameterRateControl { + bits_per_second, + target_percentage, + window_size, + initial_qp, + min_qp, + basic_unit_size, + rc_flags: rc_flags.0, + ICQ_quality_factor: icq_quality_factor, + max_qp, + quality_factor, + target_frame_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterMaxSliceSize( + Box>, +); + +impl EncMiscParameterMaxSliceSize { + pub fn new(max_slice_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + bindings::VAEncMiscParameterMaxSliceSize { + max_slice_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterBufferMaxFrameSize( + Box>, +); + +impl EncMiscParameterBufferMaxFrameSize { + pub fn new(max_frame_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + bindings::VAEncMiscParameterBufferMaxFrameSize { + type_: bindings::VAEncMiscParameterType::VAEncMiscParameterTypeMaxFrameSize, + max_frame_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterSkipFrame( + Box>, +); + +impl EncMiscParameterSkipFrame { + pub fn new(skip_frame_flag: u8, num_skip_frames: u8, size_skip_frames: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeSkipFrame, + bindings::VAEncMiscParameterSkipFrame { + skip_frame_flag, + num_skip_frames, + size_skip_frames, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterHRD(Box>); + +impl EncMiscParameterHRD { + pub fn new(initial_buffer_fullness: u32, buffer_size: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeHRD, + bindings::VAEncMiscParameterHRD { + initial_buffer_fullness, + buffer_size, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut(&mut self) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterBufferQualityLevel( + Box>, +); + +impl EncMiscParameterBufferQualityLevel { + pub fn new(quality_level: u32) -> Self { + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeQualityLevel, + bindings::VAEncMiscParameterBufferQualityLevel { + quality_level, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} + +#[derive(Default)] +pub struct EncMiscParameterQuantization( + Box>, +); + +impl EncMiscParameterQuantization { + pub fn new( + disable_trellis: bool, + enable_trellis_i: bool, + enable_trellis_p: bool, + enable_trellis_b: bool, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + disable_trellis as u32, + enable_trellis_i as u32, + enable_trellis_p as u32, + enable_trellis_b as u32, + Default::default(), + ); + + Self(MiscEncParamBuffer::new_boxed( + bindings::VAEncMiscParameterType::VAEncMiscParameterTypeQuantization, + bindings::VAEncMiscParameterQuantization { + quantization_flags: bindings::_VAEncMiscParameterQuantization__bindgen_ty_1 { + bits: bindings::_VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }, + ..Default::default() + }, + )) + } + + pub fn inner(&self) -> &MiscEncParamBuffer { + &self.0 + } + + pub(crate) fn inner_mut( + &mut self, + ) -> &mut MiscEncParamBuffer { + &mut self.0 + } +} diff --git a/vendor/cros-libva/src/buffer/h264.rs b/vendor/cros-libva/src/buffer/h264.rs new file mode 100644 index 0000000..883ee10 --- /dev/null +++ b/vendor/cros-libva/src/buffer/h264.rs @@ -0,0 +1,807 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around H264 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `VAPictureH264` FFI type. +pub struct PictureH264(bindings::VAPictureH264); + +impl PictureH264 { + /// Creates the wrapper + pub fn new( + picture_id: bindings::VASurfaceID, + frame_idx: u32, + flags: u32, + top_field_order_cnt: i32, + bottom_field_order_cnt: i32, + ) -> Self { + Self(bindings::VAPictureH264 { + picture_id, + frame_idx, + flags, + TopFieldOrderCnt: top_field_order_cnt, + BottomFieldOrderCnt: bottom_field_order_cnt, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `seq_fields` bindgen field in `VAPictureParameterBufferH264`. +pub struct H264SeqFields(bindings::_VAPictureParameterBufferH264__bindgen_ty_1); + +impl H264SeqFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + residual_colour_transform_flag: u32, + gaps_in_frame_num_value_allowed_flag: u32, + frame_mbs_only_flag: u32, + mb_adaptive_frame_field_flag: u32, + direct_8x8_inference_flag: u32, + min_luma_bi_pred_size8x8: u32, + log2_max_frame_num_minus4: u32, + pic_order_cnt_type: u32, + log2_max_pic_order_cnt_lsb_minus4: u32, + delta_pic_order_always_zero_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + residual_colour_transform_flag, + gaps_in_frame_num_value_allowed_flag, + frame_mbs_only_flag, + mb_adaptive_frame_field_flag, + direct_8x8_inference_flag, + min_luma_bi_pred_size8x8, + log2_max_frame_num_minus4, + pic_order_cnt_type, + log2_max_pic_order_cnt_lsb_minus4, + delta_pic_order_always_zero_flag, + ); + + Self(bindings::_VAPictureParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferH264__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferH264`. +pub struct H264PicFields(bindings::_VAPictureParameterBufferH264__bindgen_ty_2); + +impl H264PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + entropy_coding_mode_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_idc: u32, + transform_8x8_mode_flag: u32, + field_pic_flag: u32, + constrained_intra_pred_flag: u32, + pic_order_present_flag: u32, + deblocking_filter_control_present_flag: u32, + redundant_pic_cnt_present_flag: u32, + reference_pic_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + entropy_coding_mode_flag, + weighted_pred_flag, + weighted_bipred_idc, + transform_8x8_mode_flag, + field_pic_flag, + constrained_intra_pred_flag, + pic_order_present_flag, + deblocking_filter_control_present_flag, + redundant_pic_cnt_present_flag, + reference_pic_flag, + ); + + Self(bindings::_VAPictureParameterBufferH264__bindgen_ty_2 { + bits: bindings::_VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferH264__bindgen_ty_2 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferH264` FFI type +pub struct PictureParameterBufferH264(Box); + +impl PictureParameterBufferH264 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureH264, + reference_frames: [PictureH264; 16], + picture_width_in_mbs_minus1: u16, + picture_height_in_mbs_minus1: u16, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + num_ref_frames: u8, + seq_fields: &H264SeqFields, + num_slice_groups_minus1: u8, + slice_group_map_type: u8, + slice_group_change_rate_minus1: u16, + pic_init_qp_minus26: i8, + pic_init_qs_minus26: i8, + chroma_qp_index_offset: i8, + second_chroma_qp_index_offset: i8, + pic_fields: &H264PicFields, + frame_num: u16, + ) -> Self { + let reference_frames = (0..16usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let seq_fields = seq_fields.0; + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferH264 { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + picture_width_in_mbs_minus1, + picture_height_in_mbs_minus1, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + num_ref_frames, + seq_fields, + num_slice_groups_minus1, + slice_group_map_type, + slice_group_change_rate_minus1, + pic_init_qp_minus26, + pic_init_qs_minus26, + chroma_qp_index_offset, + second_chroma_qp_index_offset, + pic_fields, + frame_num, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferH264 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferH264` FFI type. +pub struct SliceParameterBufferH264(Vec); + +impl SliceParameterBufferH264 { + pub fn new_array() -> Self { + Self(Vec::new()) + } + + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_bit_offset: u16, + first_mb_in_slice: u16, + slice_type: u8, + direct_spatial_mv_pred_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + ) -> Self { + let mut array = Self::new_array(); + + array.add_slice_parameter( + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_bit_offset, + first_mb_in_slice, + slice_type, + direct_spatial_mv_pred_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + ref_pic_list_0, + ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + ); + + array + } + + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn add_slice_parameter( + &mut self, + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_bit_offset: u16, + first_mb_in_slice: u16, + slice_type: u8, + direct_spatial_mv_pred_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + ) { + let ref_pic_list_0 = ref_pic_list_0.map(|pic| pic.0); + let ref_pic_list_1 = ref_pic_list_1.map(|pic| pic.0); + + let buf = bindings::VASliceParameterBufferH264 { + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_bit_offset, + first_mb_in_slice, + slice_type, + direct_spatial_mv_pred_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + RefPicList0: ref_pic_list_0, + RefPicList1: ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + va_reserved: Default::default(), + }; + + self.0.push(buf); + } + + pub(crate) fn inner_mut(&mut self) -> &mut Vec { + &mut self.0 + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &Vec { + &self.0 + } +} + +/// Wrapper over the `VAIQMatrixBufferH264` FFI type +pub struct IQMatrixBufferH264(Box); + +impl IQMatrixBufferH264 { + /// Creates the wrapper. + pub fn new( + scaling_list4x4: [[u8; 16usize]; 6usize], + scaling_list8x8: [[u8; 64usize]; 2usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferH264 { + ScalingList4x4: scaling_list4x4, + ScalingList8x8: scaling_list8x8, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferH264 { + self.0.as_ref() + } +} + +/// Wrapper over the `seq_fields` bindgen field in `VAEncSequenceParameterBufferH264` +pub struct H264EncSeqFields(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1); + +impl H264EncSeqFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + frame_mbs_only_flag: u32, + mb_adaptive_frame_field_flag: u32, + seq_scaling_matrix_present_flag: u32, + direct_8x8_inference_flag: u32, + log2_max_frame_num_minus4: u32, + pic_order_cnt_type: u32, + log2_max_pic_order_cnt_lsb_minus4: u32, + delta_pic_order_always_zero_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + frame_mbs_only_flag, + mb_adaptive_frame_field_flag, + seq_scaling_matrix_present_flag, + direct_8x8_inference_flag, + log2_max_frame_num_minus4, + pic_order_cnt_type, + log2_max_pic_order_cnt_lsb_minus4, + delta_pic_order_always_zero_flag, + ); + + Self(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + pub fn inner(&self) -> &bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_1 { + &self.0 + } +} + +#[derive(Default)] +pub struct H264VuiFields(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2); + +impl H264VuiFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + aspect_ratio_info_present_flag: u32, + timing_info_present_flag: u32, + bitstream_restriction_flag: u32, + log2_max_mv_length_horizontal: u32, + log2_max_mv_length_vertical: u32, + fixed_frame_rate_flag: u32, + low_delay_hrd_flag: u32, + motion_vectors_over_pic_boundaries_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + aspect_ratio_info_present_flag, + timing_info_present_flag, + bitstream_restriction_flag, + log2_max_mv_length_horizontal, + log2_max_mv_length_vertical, + fixed_frame_rate_flag, + low_delay_hrd_flag, + motion_vectors_over_pic_boundaries_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2 { + bits: bindings::_VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct H264EncFrameCropOffsets { + pub left: u32, + pub right: u32, + pub top: u32, + pub bottom: u32, +} + +impl H264EncFrameCropOffsets { + pub fn new( + frame_crop_left_offset: u32, + frame_crop_right_offset: u32, + frame_crop_top_offset: u32, + frame_crop_bottom_offset: u32, + ) -> Self { + Self { + left: frame_crop_left_offset, + right: frame_crop_right_offset, + top: frame_crop_top_offset, + bottom: frame_crop_bottom_offset, + } + } +} + +pub struct EncSequenceParameterBufferH264(Box); + +impl EncSequenceParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + seq_parameter_set_id: u8, + level_idc: u8, + intra_period: u32, + intra_idr_period: u32, + ip_period: u32, + bits_per_second: u32, + max_num_ref_frames: u32, + picture_width_in_mbs: u16, + picture_height_in_mbs: u16, + seq_fields: &H264EncSeqFields, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + num_ref_frames_in_pic_order_cnt_cycle: u8, + offset_for_non_ref_pic: i32, + offset_for_top_to_bottom_field: i32, + offset_for_ref_frame: [i32; 256usize], + frame_crop: Option, + vui_fields: Option, + aspect_ratio_idc: u8, + sar_width: u32, + sar_height: u32, + num_units_in_tick: u32, + time_scale: u32, + ) -> Self { + let seq_fields = seq_fields.0; + + let frame_cropping_flag = if frame_crop.is_some() { 1 } else { 0 }; + let frame_crop = frame_crop.unwrap_or_default(); + + let frame_crop_left_offset = frame_crop.left; + let frame_crop_right_offset = frame_crop.right; + let frame_crop_top_offset = frame_crop.top; + let frame_crop_bottom_offset = frame_crop.bottom; + + let vui_parameters_present_flag = if vui_fields.is_some() { 1 } else { 0 }; + let vui_fields = vui_fields.unwrap_or_default().0; + + Self(Box::new(bindings::VAEncSequenceParameterBufferH264 { + seq_parameter_set_id, + level_idc, + intra_period, + intra_idr_period, + ip_period, + bits_per_second, + max_num_ref_frames, + picture_width_in_mbs, + picture_height_in_mbs, + seq_fields, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + num_ref_frames_in_pic_order_cnt_cycle, + offset_for_non_ref_pic, + offset_for_top_to_bottom_field, + offset_for_ref_frame, + frame_cropping_flag, + frame_crop_left_offset, + frame_crop_right_offset, + frame_crop_top_offset, + frame_crop_bottom_offset, + vui_parameters_present_flag, + vui_fields, + aspect_ratio_idc, + sar_width, + sar_height, + num_units_in_tick, + time_scale, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferH264 { + self.0.as_mut() + } +} + +pub struct H264EncPicFields(bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1); + +impl H264EncPicFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + idr_pic_flag: u32, + reference_pic_flag: u32, + entropy_coding_mode_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_idc: u32, + constrained_intra_pred_flag: u32, + transform_8x8_mode_flag: u32, + deblocking_filter_control_present_flag: u32, + redundant_pic_cnt_present_flag: u32, + pic_order_present_flag: u32, + pic_scaling_matrix_present_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + idr_pic_flag, + reference_pic_flag, + entropy_coding_mode_flag, + weighted_pred_flag, + weighted_bipred_idc, + constrained_intra_pred_flag, + transform_8x8_mode_flag, + deblocking_filter_control_present_flag, + redundant_pic_cnt_present_flag, + pic_order_present_flag, + pic_scaling_matrix_present_flag, + ); + + Self(bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct EncPictureParameterBufferH264(Box); + +impl EncPictureParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureH264, + reference_frames: [PictureH264; 16usize], + coded_buf: bindings::VABufferID, + pic_parameter_set_id: u8, + seq_parameter_set_id: u8, + last_picture: u8, + frame_num: u16, + pic_init_qp: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + chroma_qp_index_offset: i8, + second_chroma_qp_index_offset: i8, + pic_fields: &H264EncPicFields, + ) -> Self { + let reference_frames = (0..16usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::_VAEncPictureParameterBufferH264 { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + coded_buf, + pic_parameter_set_id, + seq_parameter_set_id, + last_picture, + frame_num, + pic_init_qp, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + chroma_qp_index_offset, + second_chroma_qp_index_offset, + pic_fields, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferH264 { + self.0.as_mut() + } +} + +pub struct EncSliceParameterBufferH264(Box); + +impl EncSliceParameterBufferH264 { + #[allow(clippy::too_many_arguments)] + pub fn new( + macroblock_address: u32, + num_macroblocks: u32, + macroblock_info: bindings::VABufferID, + slice_type: u8, + pic_parameter_set_id: u8, + idr_pic_id: u16, + pic_order_cnt_lsb: u16, + delta_pic_order_cnt_bottom: i32, + delta_pic_order_cnt: [i32; 2usize], + direct_spatial_mv_pred_flag: u8, + num_ref_idx_active_override_flag: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + ref_pic_list_0: [PictureH264; 32usize], + ref_pic_list_1: [PictureH264; 32usize], + luma_log2_weight_denom: u8, + chroma_log2_weight_denom: u8, + luma_weight_l0_flag: u8, + luma_weight_l0: [i16; 32usize], + luma_offset_l0: [i16; 32usize], + chroma_weight_l0_flag: u8, + chroma_weight_l0: [[i16; 2usize]; 32usize], + chroma_offset_l0: [[i16; 2usize]; 32usize], + luma_weight_l1_flag: u8, + luma_weight_l1: [i16; 32usize], + luma_offset_l1: [i16; 32usize], + chroma_weight_l1_flag: u8, + chroma_weight_l1: [[i16; 2usize]; 32usize], + chroma_offset_l1: [[i16; 2usize]; 32usize], + cabac_init_idc: u8, + slice_qp_delta: i8, + disable_deblocking_filter_idc: u8, + slice_alpha_c0_offset_div2: i8, + slice_beta_offset_div2: i8, + ) -> Self { + let ref_pic_list_0 = ref_pic_list_0.map(|pic| pic.0); + let ref_pic_list_1 = ref_pic_list_1.map(|pic| pic.0); + + Self(Box::new(bindings::VAEncSliceParameterBufferH264 { + macroblock_address, + num_macroblocks, + macroblock_info, + slice_type, + pic_parameter_set_id, + idr_pic_id, + pic_order_cnt_lsb, + delta_pic_order_cnt_bottom, + delta_pic_order_cnt, + direct_spatial_mv_pred_flag, + num_ref_idx_active_override_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + RefPicList0: ref_pic_list_0, + RefPicList1: ref_pic_list_1, + luma_log2_weight_denom, + chroma_log2_weight_denom, + luma_weight_l0_flag, + luma_weight_l0, + luma_offset_l0, + chroma_weight_l0_flag, + chroma_weight_l0, + chroma_offset_l0, + luma_weight_l1_flag, + luma_weight_l1, + luma_offset_l1, + chroma_weight_l1_flag, + chroma_weight_l1, + chroma_offset_l1, + cabac_init_idc, + slice_qp_delta, + disable_deblocking_filter_idc, + slice_alpha_c0_offset_div2, + slice_beta_offset_div2, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSliceParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncSliceParameterBufferH264 { + self.0.as_ref() + } +} + +pub struct H264EncMacroblockInfo(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1); + +impl H264EncMacroblockInfo { + pub fn new_intra(pred_avail_override_flag: u32, pred_avail_flags: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1::new_bitfield_1(pred_avail_override_flag, pred_avail_flags); + + Self(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + intra_fields: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + bits: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + } + } + }) + } + + pub fn new_inter() -> Self { + Self(bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + inter_fields: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2 { + bits: bindings::_VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2__bindgen_ty_1 { + reserved: Default::default() + } + } + }) + } +} + +pub struct EncMacroblockParameterBufferH264(Box); + +impl EncMacroblockParameterBufferH264 { + pub fn new(qp: u8, info: &H264EncMacroblockInfo) -> Self { + let info = info.0; + + Self(Box::new(bindings::VAEncMacroblockParameterBufferH264 { + qp, + info, + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncMacroblockParameterBufferH264 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAEncMacroblockParameterBufferH264 { + self.0.as_ref() + } +} diff --git a/vendor/cros-libva/src/buffer/hevc.rs b/vendor/cros-libva/src/buffer/hevc.rs new file mode 100644 index 0000000..35a05b4 --- /dev/null +++ b/vendor/cros-libva/src/buffer/hevc.rs @@ -0,0 +1,1154 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around HEVC `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `VAPictureH264` FFI type. +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct PictureHEVC(bindings::VAPictureHEVC); + +impl PictureHEVC { + /// Creates the wrapper + pub fn new(picture_id: bindings::VASurfaceID, pic_order_cnt: i32, flags: u32) -> Self { + Self(bindings::VAPictureHEVC { + picture_id, + pic_order_cnt, + flags, + va_reserved: Default::default(), + }) + } + + /// Returns the `picture_id` field. + pub fn picture_id(&self) -> u32 { + self.0.picture_id + } + + /// Returns the `pic_order_cnt` field. + pub fn pic_order_cnt(&self) -> i32 { + self.0.pic_order_cnt + } + + /// Returns the `flags` field. + pub fn flags(&self) -> u32 { + self.0.flags + } +} + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferHEVC`. +pub struct HevcPicFields(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1); + +impl HevcPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + separate_colour_plane_flag: u32, + pcm_enabled_flag: u32, + scaling_list_enabled_flag: u32, + transform_skip_enabled_flag: u32, + amp_enabled_flag: u32, + strong_intra_smoothing_enabled_flag: u32, + sign_data_hiding_enabled_flag: u32, + constrained_intra_pred_flag: u32, + cu_qp_delta_enabled_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_flag: u32, + transquant_bypass_enabled_flag: u32, + tiles_enabled_flag: u32, + entropy_coding_sync_enabled_flag: u32, + pps_loop_filter_across_slices_enabled_flag: u32, + loop_filter_across_tiles_enabled_flag: u32, + pcm_loop_filter_disabled_flag: u32, + no_pic_reordering_flag: u32, + no_bi_pred_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + separate_colour_plane_flag, + pcm_enabled_flag, + scaling_list_enabled_flag, + transform_skip_enabled_flag, + amp_enabled_flag, + strong_intra_smoothing_enabled_flag, + sign_data_hiding_enabled_flag, + constrained_intra_pred_flag, + cu_qp_delta_enabled_flag, + weighted_pred_flag, + weighted_bipred_flag, + transquant_bypass_enabled_flag, + tiles_enabled_flag, + entropy_coding_sync_enabled_flag, + pps_loop_filter_across_slices_enabled_flag, + loop_filter_across_tiles_enabled_flag, + pcm_loop_filter_disabled_flag, + no_pic_reordering_flag, + no_bi_pred_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVC__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `slice_parsing_fields` bindgen field in `VAPictureParameterBufferHEVC`. +pub struct HevcSliceParsingFields(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2); + +impl HevcSliceParsingFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + lists_modification_present_flag: u32, + long_term_ref_pics_present_flag: u32, + sps_temporal_mvp_enabled_flag: u32, + cabac_init_present_flag: u32, + output_flag_present_flag: u32, + dependent_slice_segments_enabled_flag: u32, + pps_slice_chroma_qp_offsets_present_flag: u32, + sample_adaptive_offset_enabled_flag: u32, + deblocking_filter_override_enabled_flag: u32, + pps_disable_deblocking_filter_flag: u32, + slice_segment_header_extension_present_flag: u32, + rap_pic_flag: u32, + idr_pic_flag: u32, + intra_pic_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + lists_modification_present_flag, + long_term_ref_pics_present_flag, + sps_temporal_mvp_enabled_flag, + cabac_init_present_flag, + output_flag_present_flag, + dependent_slice_segments_enabled_flag, + pps_slice_chroma_qp_offsets_present_flag, + sample_adaptive_offset_enabled_flag, + deblocking_filter_override_enabled_flag, + pps_disable_deblocking_filter_flag, + slice_segment_header_extension_present_flag, + rap_pic_flag, + idr_pic_flag, + intra_pic_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVC__bindgen_ty_2 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferHEVC` FFI type +pub struct PictureParameterBufferHEVC(Box); + +impl PictureParameterBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + curr_pic: PictureHEVC, + reference_frames: [PictureHEVC; 15], + pic_width_in_luma_samples: u16, + pic_height_in_luma_samples: u16, + pic_fields: &HevcPicFields, + sps_max_dec_pic_buffering_minus1: u8, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + pcm_sample_bit_depth_luma_minus1: u8, + pcm_sample_bit_depth_chroma_minus1: u8, + log2_min_luma_coding_block_size_minus3: u8, + log2_diff_max_min_luma_coding_block_size: u8, + log2_min_transform_block_size_minus2: u8, + log2_diff_max_min_transform_block_size: u8, + log2_min_pcm_luma_coding_block_size_minus3: u8, + log2_diff_max_min_pcm_luma_coding_block_size: u8, + max_transform_hierarchy_depth_intra: u8, + max_transform_hierarchy_depth_inter: u8, + init_qp_minus26: i8, + diff_cu_qp_delta_depth: u8, + pps_cb_qp_offset: i8, + pps_cr_qp_offset: i8, + log2_parallel_merge_level_minus2: u8, + num_tile_columns_minus1: u8, + num_tile_rows_minus1: u8, + column_width_minus1: [u16; 19], + row_height_minus1: [u16; 21], + slice_parsing_fields: &HevcSliceParsingFields, + log2_max_pic_order_cnt_lsb_minus4: u8, + num_short_term_ref_pic_sets: u8, + num_long_term_ref_pic_sps: u8, + num_ref_idx_l0_default_active_minus1: u8, + num_ref_idx_l1_default_active_minus1: u8, + pps_beta_offset_div2: i8, + pps_tc_offset_div2: i8, + num_extra_slice_header_bits: u8, + st_rps_bits: u32, + ) -> Self { + let reference_frames = (0..15usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + let slice_parsing_fields = slice_parsing_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVC { + CurrPic: curr_pic.0, + ReferenceFrames: reference_frames, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + pic_fields, + sps_max_dec_pic_buffering_minus1, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + pcm_sample_bit_depth_luma_minus1, + pcm_sample_bit_depth_chroma_minus1, + log2_min_luma_coding_block_size_minus3, + log2_diff_max_min_luma_coding_block_size, + log2_min_transform_block_size_minus2, + log2_diff_max_min_transform_block_size, + log2_min_pcm_luma_coding_block_size_minus3, + log2_diff_max_min_pcm_luma_coding_block_size, + max_transform_hierarchy_depth_intra, + max_transform_hierarchy_depth_inter, + init_qp_minus26, + diff_cu_qp_delta_depth, + pps_cb_qp_offset, + pps_cr_qp_offset, + log2_parallel_merge_level_minus2, + num_tile_columns_minus1, + num_tile_rows_minus1, + column_width_minus1, + row_height_minus1, + slice_parsing_fields, + log2_max_pic_order_cnt_lsb_minus4, + num_short_term_ref_pic_sets, + num_long_term_ref_pic_sps, + num_ref_idx_l0_default_active_minus1, + num_ref_idx_l1_default_active_minus1, + pps_beta_offset_div2, + pps_tc_offset_div2, + num_extra_slice_header_bits, + st_rps_bits, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVC { + self.0.as_ref() + } +} + +/// Wrapper over the `range_extension_pic_fields` bindgen field in `VAPictureParameterBufferHEVCRext`. +pub struct HevcRangeExtensionPicFields(bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1); + +impl HevcRangeExtensionPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + transform_skip_rotation_enabled_flag: u32, + transform_skip_context_enabled_flag: u32, + implicit_rdpcm_enabled_flag: u32, + explicit_rdpcm_enabled_flag: u32, + extended_precision_processing_flag: u32, + intra_smoothing_disabled_flag: u32, + high_precision_offsets_enabled_flag: u32, + persistent_rice_adaptation_enabled_flag: u32, + cabac_bypass_alignment_enabled_flag: u32, + cross_component_prediction_enabled_flag: u32, + chroma_qp_offset_list_enabled_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + transform_skip_rotation_enabled_flag, + transform_skip_context_enabled_flag, + implicit_rdpcm_enabled_flag, + explicit_rdpcm_enabled_flag, + extended_precision_processing_flag, + intra_smoothing_disabled_flag, + high_precision_offsets_enabled_flag, + persistent_rice_adaptation_enabled_flag, + cabac_bypass_alignment_enabled_flag, + cross_component_prediction_enabled_flag, + chroma_qp_offset_list_enabled_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferHEVCRext` FFI type +pub struct PictureParameterBufferHEVCRext(Box); + +impl PictureParameterBufferHEVCRext { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + range_extension_pic_fields: &HevcRangeExtensionPicFields, + diff_cu_chroma_qp_offset_depth: u8, + chroma_qp_offset_list_len_minus1: u8, + log2_sao_offset_scale_luma: u8, + log2_sao_offset_scale_chroma: u8, + log2_max_transform_skip_block_size_minus2: u8, + cb_qp_offset_list: [i8; 6usize], + cr_qp_offset_list: [i8; 6usize], + ) -> Self { + let range_extension_pic_fields = range_extension_pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVCRext { + range_extension_pic_fields, + diff_cu_chroma_qp_offset_depth, + chroma_qp_offset_list_len_minus1, + log2_sao_offset_scale_luma, + log2_sao_offset_scale_chroma, + log2_max_transform_skip_block_size_minus2, + cb_qp_offset_list, + cr_qp_offset_list, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVCRext { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVCRext { + self.0.as_ref() + } +} + +/// Wrapper over the `screen_content_pic_fields` bindgen field in `VAPictureParameterBufferHEVCScc`. +pub struct HevcScreenContentPicFields(bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1); + +impl HevcScreenContentPicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + pps_curr_pic_ref_enabled_flag: u32, + palette_mode_enabled_flag: u32, + motion_vector_resolution_control_idc: u32, + intra_boundary_filtering_disabled_flag: u32, + residual_adaptive_colour_transform_enabled_flag: u32, + pps_slice_act_qp_offsets_present_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + pps_curr_pic_ref_enabled_flag, + palette_mode_enabled_flag, + motion_vector_resolution_control_idc, + intra_boundary_filtering_disabled_flag, + residual_adaptive_colour_transform_enabled_flag, + pps_slice_act_qp_offsets_present_flag, + 0, + ); + + Self(bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VAPictureParameterBufferScc` FFI type +pub struct PictureParameterBufferHEVCScc(Box); + +impl PictureParameterBufferHEVCScc { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + screen_content_pic_fields: &HevcScreenContentPicFields, + palette_max_size: u8, + delta_palette_max_predictor_size: u8, + predictor_palette_size: u8, + predictor_palette_entries: [[u16; 128usize]; 3usize], + pps_act_y_qp_offset_plus5: i8, + pps_act_cb_qp_offset_plus5: i8, + pps_act_cr_qp_offset_plus3: i8, + ) -> Self { + let screen_content_pic_fields = screen_content_pic_fields.0; + + Self(Box::new(bindings::VAPictureParameterBufferHEVCScc { + screen_content_pic_fields, + palette_max_size, + delta_palette_max_predictor_size, + predictor_palette_size, + predictor_palette_entries, + pps_act_y_qp_offset_plus5, + pps_act_cb_qp_offset_plus5, + pps_act_cr_qp_offset_plus3, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferHEVCScc { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferHEVCScc { + self.0.as_ref() + } +} + +/// Wrapper over the `long_slice_flags` bindgen field in `VASliceParameterBufferHEVC`. +pub struct HevcLongSliceFlags(bindings::_VASliceParameterBufferHEVC__bindgen_ty_1); + +impl HevcLongSliceFlags { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + last_slice_of_pic: u32, + dependent_slice_segment_flag: u32, + slice_type: u32, + color_plane_id: u32, + slice_sao_luma_flag: u32, + slice_sao_chroma_flag: u32, + mvd_l1_zero_flag: u32, + cabac_init_flag: u32, + slice_temporal_mvp_enabled_flag: u32, + slice_deblocking_filter_disabled_flag: u32, + collocated_from_l0_flag: u32, + slice_loop_filter_across_slices_enabled_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + last_slice_of_pic, + dependent_slice_segment_flag, + slice_type, + color_plane_id, + slice_sao_luma_flag, + slice_sao_chroma_flag, + mvd_l1_zero_flag, + cabac_init_flag, + slice_temporal_mvp_enabled_flag, + slice_deblocking_filter_disabled_flag, + collocated_from_l0_flag, + slice_loop_filter_across_slices_enabled_flag, + 0, + ); + + Self(bindings::_VASliceParameterBufferHEVC__bindgen_ty_1 { + fields: bindings::_VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASliceParameterBufferHEVC__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VASliceParameterBufferHEVC` FFI type +pub struct SliceParameterBufferHEVC(Box); + +impl SliceParameterBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + slice_data_byte_offset: u32, + slice_segment_address: u32, + ref_pic_list: [[u8; 15usize]; 2usize], + long_slice_flags: &HevcLongSliceFlags, + collocated_ref_idx: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + slice_qp_delta: i8, + slice_cb_qp_offset: i8, + slice_cr_qp_offset: i8, + slice_beta_offset_div2: i8, + slice_tc_offset_div2: i8, + luma_log2_weight_denom: u8, + delta_chroma_log2_weight_denom: i8, + delta_luma_weight_l0: [i8; 15usize], + luma_offset_l0: [i8; 15usize], + delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + chroma_offset_l0: [[i8; 2usize]; 15usize], + delta_luma_weight_l1: [i8; 15usize], + luma_offset_l1: [i8; 15usize], + delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + chroma_offset_l1: [[i8; 2usize]; 15usize], + five_minus_max_num_merge_cand: u8, + num_entry_point_offsets: u16, + entry_offset_to_subset_array: u16, + slice_data_num_emu_prevn_bytes: u16, + ) -> Self { + let long_slice_flags = long_slice_flags.0; + + Self(Box::new(bindings::VASliceParameterBufferHEVC { + slice_data_size, + slice_data_offset, + slice_data_flag, + slice_data_byte_offset, + slice_segment_address, + RefPicList: ref_pic_list, + LongSliceFlags: long_slice_flags, + collocated_ref_idx, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + slice_qp_delta, + slice_cb_qp_offset, + slice_cr_qp_offset, + slice_beta_offset_div2, + slice_tc_offset_div2, + luma_log2_weight_denom, + delta_chroma_log2_weight_denom, + delta_luma_weight_l0, + luma_offset_l0, + delta_chroma_weight_l0, + ChromaOffsetL0: chroma_offset_l0, + delta_luma_weight_l1, + luma_offset_l1, + delta_chroma_weight_l1, + ChromaOffsetL1: chroma_offset_l1, + five_minus_max_num_merge_cand, + num_entry_point_offsets, + entry_offset_to_subset_array, + slice_data_num_emu_prevn_bytes, + va_reserved: Default::default(), + })) + } + + /// Set this slice as the last one after creation. Implementations may only + /// be able to conveniently see if this is the last slice after it has been + /// created. + pub fn set_as_last(&mut self) { + // Safe because we know that both fields are valid at all times (just a + // different view on the data), and we are mutating through the bindgen + // function, respecting the padding in place. + unsafe { self.inner_mut().LongSliceFlags.fields.set_LastSliceOfPic(1) }; + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferHEVC { + self.0.as_ref() + } +} + +/// Wrapper over the `slice_ext_flags` bindgen field in `VASliceParameterBufferHEVCRext`. +pub struct HevcSliceExtFlags(bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1); + +impl HevcSliceExtFlags { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new(cu_chroma_qp_offset_enabled_flag: u32, use_integer_mv_flag: u32) -> Self { + let _bitfield_1 = + bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + cu_chroma_qp_offset_enabled_flag, + use_integer_mv_flag, + 0, + ); + + Self(bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1 { + bits: bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASliceParameterBufferHEVCRext__bindgen_ty_1 { + &self.0 + } +} + +/// A wrapper over `VASliceParameterBufferHEVCRext` FFI type +pub struct SliceParameterBufferHEVCRext(Box); + +impl SliceParameterBufferHEVCRext { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + luma_offset_l0: [i16; 15usize], + chroma_offset_l0: [[i16; 2usize]; 15usize], + luma_offset_l1: [i16; 15usize], + chroma_offset_l1: [[i16; 2usize]; 15usize], + slice_ext_flags: &HevcSliceExtFlags, + slice_act_y_qp_offset: i8, + slice_act_cb_qp_offset: i8, + slice_act_cr_qp_offset: i8, + ) -> Self { + let slice_ext_flags = slice_ext_flags.0; + + Self(Box::new(bindings::VASliceParameterBufferHEVCRext { + luma_offset_l0, + ChromaOffsetL0: chroma_offset_l0, + luma_offset_l1, + ChromaOffsetL1: chroma_offset_l1, + slice_ext_flags, + slice_act_y_qp_offset, + slice_act_cb_qp_offset, + slice_act_cr_qp_offset, + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferHEVCRext { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferHEVCRext { + self.0.as_ref() + } +} + +/// A wrapper over `VAIQMatrixBufferHEVC` FFI type +pub struct IQMatrixBufferHEVC(Box); + +impl IQMatrixBufferHEVC { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + scaling_list4x4: [[u8; 16usize]; 6usize], + scaling_list8x8: [[u8; 64usize]; 6usize], + scaling_list16x16: [[u8; 64usize]; 6usize], + scaling_list32x32: [[u8; 64usize]; 2usize], + scaling_list_dc16x16: [u8; 6usize], + scaling_list_dc32x32: [u8; 2usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferHEVC { + ScalingList4x4: scaling_list4x4, + ScalingList8x8: scaling_list8x8, + ScalingList16x16: scaling_list16x16, + ScalingList32x32: scaling_list32x32, + ScalingListDC16x16: scaling_list_dc16x16, + ScalingListDC32x32: scaling_list_dc32x32, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferHEVC { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferHEVC { + self.0.as_ref() + } +} + +pub struct HEVCEncSeqFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1); + +impl HEVCEncSeqFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + chroma_format_idc: u32, + separate_colour_plane_flag: u32, + bit_depth_luma_minus8: u32, + bit_depth_chroma_minus8: u32, + scaling_list_enabled_flag: u32, + strong_intra_smoothing_enabled_flag: u32, + amp_enabled_flag: u32, + sample_adaptive_offset_enabled_flag: u32, + pcm_enabled_flag: u32, + pcm_loop_filter_disabled_flag: u32, + sps_temporal_mvp_enabled_flag: u32, + low_delay_seq: u32, + hierachical_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + chroma_format_idc, + separate_colour_plane_flag, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + scaling_list_enabled_flag, + strong_intra_smoothing_enabled_flag, + amp_enabled_flag, + sample_adaptive_offset_enabled_flag, + pcm_enabled_flag, + pcm_loop_filter_disabled_flag, + sps_temporal_mvp_enabled_flag, + low_delay_seq, + hierachical_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +#[derive(Default)] +pub struct HevcEncVuiFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2); + +impl HevcEncVuiFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + aspect_ratio_info_present_flag: u32, + neutral_chroma_indication_flag: u32, + field_seq_flag: u32, + vui_timing_info_present_flag: u32, + bitstream_restriction_flag: u32, + tiles_fixed_structure_flag: u32, + motion_vectors_over_pic_boundaries_flag: u32, + restricted_ref_pic_lists_flag: u32, + log2_max_mv_length_horizontal: u32, + log2_max_mv_length_vertical: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + aspect_ratio_info_present_flag, + neutral_chroma_indication_flag, + field_seq_flag, + vui_timing_info_present_flag, + bitstream_restriction_flag, + tiles_fixed_structure_flag, + motion_vectors_over_pic_boundaries_flag, + restricted_ref_pic_lists_flag, + log2_max_mv_length_horizontal, + log2_max_mv_length_vertical, + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct HevcEncSeqSccFields(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3); + +impl HevcEncSeqSccFields { + pub fn new(palette_mode_enabled_flag: u32) -> Self { + let _bitfield_1 = + bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1::new_bitfield_1( + palette_mode_enabled_flag, + Default::default(), + ); + + Self(bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3 { + bits: bindings::_VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncSequenceParameterBufferHEVC(Box); + +impl EncSequenceParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + general_profile_idc: u8, + general_level_idc: u8, + general_tier_flag: u8, + intra_period: u32, + intra_idr_period: u32, + ip_period: u32, + bits_per_second: u32, + pic_width_in_luma_samples: u16, + pic_height_in_luma_samples: u16, + seq_fields: &HEVCEncSeqFields, + log2_min_luma_coding_block_size_minus3: u8, + log2_diff_max_min_luma_coding_block_size: u8, + log2_min_transform_block_size_minus2: u8, + log2_diff_max_min_transform_block_size: u8, + max_transform_hierarchy_depth_inter: u8, + max_transform_hierarchy_depth_intra: u8, + pcm_sample_bit_depth_luma_minus1: u32, + pcm_sample_bit_depth_chroma_minus1: u32, + log2_min_pcm_luma_coding_block_size_minus3: u32, + log2_max_pcm_luma_coding_block_size_minus3: u32, + vui_fields: Option, + aspect_ratio_idc: u8, + sar_width: u32, + sar_height: u32, + vui_num_units_in_tick: u32, + vui_time_scale: u32, + min_spatial_segmentation_idc: u16, + max_bytes_per_pic_denom: u8, + max_bits_per_min_cu_denom: u8, + scc_fields: &HevcEncSeqSccFields, + ) -> Self { + let seq_fields = seq_fields.0; + let vui_parameters_present_flag = vui_fields.is_some() as u8; + let vui_fields = vui_fields.unwrap_or_default().0; + let scc_fields = scc_fields.0; + + Self(Box::new(bindings::VAEncSequenceParameterBufferHEVC { + general_profile_idc, + general_level_idc, + general_tier_flag, + intra_period, + intra_idr_period, + ip_period, + bits_per_second, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + seq_fields, + log2_min_luma_coding_block_size_minus3, + log2_diff_max_min_luma_coding_block_size, + log2_min_transform_block_size_minus2, + log2_diff_max_min_transform_block_size, + max_transform_hierarchy_depth_inter, + max_transform_hierarchy_depth_intra, + pcm_sample_bit_depth_luma_minus1, + pcm_sample_bit_depth_chroma_minus1, + log2_min_pcm_luma_coding_block_size_minus3, + log2_max_pcm_luma_coding_block_size_minus3, + vui_parameters_present_flag, + vui_fields, + aspect_ratio_idc, + sar_width, + sar_height, + vui_num_units_in_tick, + vui_time_scale, + min_spatial_segmentation_idc, + max_bytes_per_pic_denom, + max_bits_per_min_cu_denom, + scc_fields, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferHEVC { + &mut self.0 + } +} + +pub struct HEVCEncPicFields(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1); + +impl HEVCEncPicFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + idr_pic_flag: u32, + coding_type: u32, + reference_pic_flag: u32, + dependent_slice_segments_enabled_flag: u32, + sign_data_hiding_enabled_flag: u32, + constrained_intra_pred_flag: u32, + transform_skip_enabled_flag: u32, + cu_qp_delta_enabled_flag: u32, + weighted_pred_flag: u32, + weighted_bipred_flag: u32, + transquant_bypass_enabled_flag: u32, + tiles_enabled_flag: u32, + entropy_coding_sync_enabled_flag: u32, + loop_filter_across_tiles_enabled_flag: u32, + pps_loop_filter_across_slices_enabled_flag: u32, + scaling_list_data_present_flag: u32, + screen_content_flag: u32, + enable_gpu_weighted_prediction: u32, + no_output_of_prior_pics_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + idr_pic_flag, + coding_type, + reference_pic_flag, + dependent_slice_segments_enabled_flag, + sign_data_hiding_enabled_flag, + constrained_intra_pred_flag, + transform_skip_enabled_flag, + cu_qp_delta_enabled_flag, + weighted_pred_flag, + weighted_bipred_flag, + transquant_bypass_enabled_flag, + tiles_enabled_flag, + entropy_coding_sync_enabled_flag, + loop_filter_across_tiles_enabled_flag, + pps_loop_filter_across_slices_enabled_flag, + scaling_list_data_present_flag, + screen_content_flag, + enable_gpu_weighted_prediction, + no_output_of_prior_pics_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct HevcEncPicSccFields(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2); + +impl HevcEncPicSccFields { + pub fn new(pps_curr_pic_ref_enabled_flag: u16) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + pps_curr_pic_ref_enabled_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferHEVC(Box); + +impl EncPictureParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + decoded_curr_pic: PictureHEVC, + reference_frames: [PictureHEVC; 15usize], + coded_buf: bindings::VABufferID, + collocated_ref_pic_index: u8, + last_picture: u8, + pic_init_qp: u8, + diff_cu_qp_delta_depth: u8, + pps_cb_qp_offset: i8, + pps_cr_qp_offset: i8, + num_tile_columns_minus1: u8, + num_tile_rows_minus1: u8, + column_width_minus1: [u8; 19usize], + row_height_minus1: [u8; 21usize], + log2_parallel_merge_level_minus2: u8, + ctu_max_bitsize_allowed: u8, + num_ref_idx_l0_default_active_minus1: u8, + num_ref_idx_l1_default_active_minus1: u8, + slice_pic_parameter_set_id: u8, + nal_unit_type: u8, + pic_fields: &HEVCEncPicFields, + hierarchical_level_plus1: u8, + va_byte_reserved: u8, + scc_fields: &HevcEncPicSccFields, + ) -> Self { + let decoded_curr_pic = decoded_curr_pic.0; + let reference_frames = (0..15usize) + .map(|i| reference_frames[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let pic_fields = pic_fields.0; + let scc_fields = scc_fields.0; + + Self(Box::new(bindings::VAEncPictureParameterBufferHEVC { + decoded_curr_pic, + reference_frames, + coded_buf, + collocated_ref_pic_index, + last_picture, + pic_init_qp, + diff_cu_qp_delta_depth, + pps_cb_qp_offset, + pps_cr_qp_offset, + num_tile_columns_minus1, + num_tile_rows_minus1, + column_width_minus1, + row_height_minus1, + log2_parallel_merge_level_minus2, + ctu_max_bitsize_allowed, + num_ref_idx_l0_default_active_minus1, + num_ref_idx_l1_default_active_minus1, + slice_pic_parameter_set_id, + nal_unit_type, + pic_fields, + hierarchical_level_plus1, + va_byte_reserved, + scc_fields, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferHEVC { + &mut self.0 + } +} + +pub struct HevcEncSliceFields(bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1); + +impl HevcEncSliceFields { + #[allow(clippy::too_many_arguments)] + pub fn new( + last_slice_of_pic_flag: u32, + dependent_slice_segment_flag: u32, + colour_plane_id: u32, + slice_temporal_mvp_enabled_flag: u32, + slice_sao_luma_flag: u32, + slice_sao_chroma_flag: u32, + num_ref_idx_active_override_flag: u32, + mvd_l1_zero_flag: u32, + cabac_init_flag: u32, + slice_deblocking_filter_disabled_flag: u32, + slice_loop_filter_across_slices_enabled_flag: u32, + collocated_from_l0_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + last_slice_of_pic_flag, + dependent_slice_segment_flag, + colour_plane_id, + slice_temporal_mvp_enabled_flag, + slice_sao_luma_flag, + slice_sao_chroma_flag, + num_ref_idx_active_override_flag, + mvd_l1_zero_flag, + cabac_init_flag, + slice_deblocking_filter_disabled_flag, + slice_loop_filter_across_slices_enabled_flag, + collocated_from_l0_flag, + ); + + Self(bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1 { + bits: bindings::_VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } +} + +pub struct EncSliceParameterBufferHEVC(Box); + +impl EncSliceParameterBufferHEVC { + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_segment_address: u32, + num_ctu_in_slice: u32, + slice_type: u8, + slice_pic_parameter_set_id: u8, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + ref_pic_list0: [PictureHEVC; 15usize], + ref_pic_list1: [PictureHEVC; 15usize], + luma_log2_weight_denom: u8, + delta_chroma_log2_weight_denom: i8, + delta_luma_weight_l0: [i8; 15usize], + luma_offset_l0: [i8; 15usize], + delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + chroma_offset_l0: [[i8; 2usize]; 15usize], + delta_luma_weight_l1: [i8; 15usize], + luma_offset_l1: [i8; 15usize], + delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + chroma_offset_l1: [[i8; 2usize]; 15usize], + max_num_merge_cand: u8, + slice_qp_delta: i8, + slice_cb_qp_offset: i8, + slice_cr_qp_offset: i8, + slice_beta_offset_div2: i8, + slice_tc_offset_div2: i8, + slice_fields: &HevcEncSliceFields, + pred_weight_table_bit_offset: u32, + pred_weight_table_bit_length: u32, + ) -> Self { + let ref_pic_list0 = (0..15usize) + .map(|i| ref_pic_list0[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let ref_pic_list1 = (0..15usize) + .map(|i| ref_pic_list1[i].0) + .collect::>() + .try_into() + // try_into is guaranteed to work because the iterator and target array have the same + // size. + .unwrap(); + + let slice_fields = slice_fields.0; + + Self(Box::new(bindings::VAEncSliceParameterBufferHEVC { + slice_segment_address, + num_ctu_in_slice, + slice_type, + slice_pic_parameter_set_id, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + ref_pic_list0, + ref_pic_list1, + luma_log2_weight_denom, + delta_chroma_log2_weight_denom, + delta_luma_weight_l0, + luma_offset_l0, + delta_chroma_weight_l0, + chroma_offset_l0, + delta_luma_weight_l1, + luma_offset_l1, + delta_chroma_weight_l1, + chroma_offset_l1, + max_num_merge_cand, + slice_qp_delta, + slice_cb_qp_offset, + slice_cr_qp_offset, + slice_beta_offset_div2, + slice_tc_offset_div2, + slice_fields, + pred_weight_table_bit_offset, + pred_weight_table_bit_length, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSliceParameterBufferHEVC { + &mut self.0 + } +} diff --git a/vendor/cros-libva/src/buffer/mpeg2.rs b/vendor/cros-libva/src/buffer/mpeg2.rs new file mode 100644 index 0000000..22df314 --- /dev/null +++ b/vendor/cros-libva/src/buffer/mpeg2.rs @@ -0,0 +1,172 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around MPEG2 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `picture_coding_extension` bindgen field in `VAPictureParameterBufferMPEG2`. +pub struct MPEG2PictureCodingExtension(bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1); + +impl MPEG2PictureCodingExtension { + /// Creates the bindgen field. + #[allow(clippy::too_many_arguments)] + pub fn new( + intra_dc_precision: u32, + picture_structure: u32, + top_field_first: u32, + frame_pred_frame_dct: u32, + concealment_motion_vectors: u32, + q_scale_type: u32, + intra_vlc_format: u32, + alternate_scan: u32, + repeat_first_field: u32, + progressive_frame: u32, + is_first_field: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + intra_dc_precision, + picture_structure, + top_field_first, + frame_pred_frame_dct, + concealment_motion_vectors, + q_scale_type, + intra_vlc_format, + alternate_scan, + repeat_first_field, + progressive_frame, + is_first_field, + ); + + Self(bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VAPictureParameterBufferMPEG2__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `PictureParameterBufferMPEG2` FFI type. +pub struct PictureParameterBufferMPEG2(Box); + +impl PictureParameterBufferMPEG2 { + /// Creates the wrapper. + pub fn new( + horizontal_size: u16, + vertical_size: u16, + forward_reference_picture: bindings::VASurfaceID, + backward_reference_picture: bindings::VASurfaceID, + picture_coding_type: i32, + f_code: i32, + picture_coding_extension: &MPEG2PictureCodingExtension, + ) -> Self { + let picture_coding_extension = picture_coding_extension.0; + + Self(Box::new(bindings::VAPictureParameterBufferMPEG2 { + horizontal_size, + vertical_size, + forward_reference_picture, + backward_reference_picture, + picture_coding_type, + f_code, + picture_coding_extension, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::VAPictureParameterBufferMPEG2 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferMPEG2` FFI type. +pub struct SliceParameterBufferMPEG2(Box); + +impl SliceParameterBufferMPEG2 { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + macroblock_offset: u32, + slice_horizontal_position: u32, + slice_vertical_position: u32, + quantiser_scale_code: i32, + intra_slice_flag: i32, + ) -> Self { + Self(Box::new(bindings::VASliceParameterBufferMPEG2 { + slice_data_size, + slice_data_offset, + slice_data_flag, + macroblock_offset, + slice_horizontal_position, + slice_vertical_position, + quantiser_scale_code, + intra_slice_flag, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferMPEG2 { + self.0.as_ref() + } +} + +/// Wrapper over the `VAIQMatrixBufferMPEG2` FFI type. +pub struct IQMatrixBufferMPEG2(Box); + +impl IQMatrixBufferMPEG2 { + /// Creates the wrapper. + #[allow(clippy::too_many_arguments)] + pub fn new( + load_intra_quantiser_matrix: i32, + load_non_intra_quantiser_matrix: i32, + load_chroma_intra_quantiser_matrix: i32, + load_chroma_non_intra_quantiser_matrix: i32, + intra_quantiser_matrix: [u8; 64usize], + non_intra_quantiser_matrix: [u8; 64usize], + chroma_intra_quantiser_matrix: [u8; 64usize], + chroma_non_intra_quantiser_matrix: [u8; 64usize], + ) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferMPEG2 { + load_intra_quantiser_matrix, + load_non_intra_quantiser_matrix, + load_chroma_intra_quantiser_matrix, + load_chroma_non_intra_quantiser_matrix, + intra_quantiser_matrix, + non_intra_quantiser_matrix, + chroma_intra_quantiser_matrix, + chroma_non_intra_quantiser_matrix, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferMPEG2 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferMPEG2 { + self.0.as_ref() + } +} diff --git a/vendor/cros-libva/src/buffer/vp8.rs b/vendor/cros-libva/src/buffer/vp8.rs new file mode 100644 index 0000000..70989e1 --- /dev/null +++ b/vendor/cros-libva/src/buffer/vp8.rs @@ -0,0 +1,397 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around VP8 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferVP8`. +pub struct VP8PicFields(bindings::_VAPictureParameterBufferVP8__bindgen_ty_1); + +impl VP8PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + key_frame: u32, + version: u32, + segmentation_enabled: u32, + update_mb_segmentation_map: u32, + update_segment_feature_data: u32, + filter_type: u32, + sharpness_level: u32, + loop_filter_adj_enable: u32, + mode_ref_lf_delta_update: u32, + sign_bias_golden: u32, + sign_bias_alternate: u32, + mb_no_coeff_skip: u32, + loop_filter_disable: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + key_frame, + version, + segmentation_enabled, + update_mb_segmentation_map, + update_segment_feature_data, + filter_type, + sharpness_level, + loop_filter_adj_enable, + mode_ref_lf_delta_update, + sign_bias_golden, + sign_bias_alternate, + mb_no_coeff_skip, + loop_filter_disable, + ); + + Self(bindings::_VAPictureParameterBufferVP8__bindgen_ty_1 { + bits: bindings::_VAPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::_VAPictureParameterBufferVP8__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VABoolCoderContextVPX` FFI type. +pub struct BoolCoderContextVPX(bindings::VABoolCoderContextVPX); + +impl BoolCoderContextVPX { + /// Creates the wrapper + pub fn new(range: u8, value: u8, count: u8) -> Self { + Self(bindings::VABoolCoderContextVPX { + range, + value, + count, + }) + } +} + +/// Wrapper over the `PictureParameterBufferVP8` FFI type. +pub struct PictureParameterBufferVP8(Box); + +impl PictureParameterBufferVP8 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u32, + frame_height: u32, + last_ref_frame: bindings::VASurfaceID, + golden_ref_frame: bindings::VASurfaceID, + alt_ref_frame: bindings::VASurfaceID, + pic_fields: &VP8PicFields, + mb_segment_tree_probs: [u8; 3usize], + loop_filter_level: [u8; 4usize], + loop_filter_deltas_ref_frame: [i8; 4usize], + loop_filter_deltas_mode: [i8; 4usize], + prob_skip_false: u8, + prob_intra: u8, + prob_last: u8, + prob_gf: u8, + y_mode_probs: [u8; 4usize], + uv_mode_probs: [u8; 3usize], + mv_probs: [[u8; 19usize]; 2usize], + bool_coder_ctx: &BoolCoderContextVPX, + ) -> Self { + let pic_fields = pic_fields.0; + let bool_coder_ctx = bool_coder_ctx.0; + + Self(Box::new(bindings::VAPictureParameterBufferVP8 { + frame_width, + frame_height, + last_ref_frame, + golden_ref_frame, + alt_ref_frame, + out_of_loop_frame: bindings::VA_INVALID_SURFACE, + pic_fields, + mb_segment_tree_probs, + loop_filter_level, + loop_filter_deltas_ref_frame, + loop_filter_deltas_mode, + prob_skip_false, + prob_intra, + prob_last, + prob_gf, + y_mode_probs, + uv_mode_probs, + mv_probs, + bool_coder_ctx, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAPictureParameterBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAPictureParameterBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the `VASliceParameterBufferVP8` FFI type. +pub struct SliceParameterBufferVP8(Box); + +impl SliceParameterBufferVP8 { + /// Creates the wrapper. + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + macroblock_offset: u32, + num_of_partitions: u8, + partition_size: [u32; 9usize], + ) -> Self { + Self(Box::new(bindings::VASliceParameterBufferVP8 { + slice_data_size, + slice_data_offset, + slice_data_flag, + macroblock_offset, + num_of_partitions, + partition_size, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the `VAIQMatrixBufferVP8` FFI type. +pub struct IQMatrixBufferVP8(Box); + +impl IQMatrixBufferVP8 { + /// Creates the wrapper. + pub fn new(quantization_index: [[u16; 6usize]; 4usize]) -> Self { + Self(Box::new(bindings::VAIQMatrixBufferVP8 { + quantization_index, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAIQMatrixBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAIQMatrixBufferVP8 { + self.0.as_ref() + } +} + +/// Wrapper over the VAProbabilityDataBufferVP8 FFI type. +pub struct ProbabilityDataBufferVP8(Box); + +impl ProbabilityDataBufferVP8 { + /// Creates the wrapper. + pub fn new(dct_coeff_probs: [[[[u8; 11usize]; 3usize]; 8usize]; 4usize]) -> Self { + Self(Box::new(bindings::VAProbabilityDataBufferVP8 { + dct_coeff_probs, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAProbabilityDataBufferVP8 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAProbabilityDataBufferVP8 { + self.0.as_ref() + } +} + +pub struct EncSequenceParameterBufferVP8(Box); + +impl EncSequenceParameterBufferVP8 { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u32, + frame_height: u32, + frame_width_scale: u32, + frame_height_scale: u32, + error_resilient: u32, + kf_auto: u32, + kf_min_dist: u32, + kf_max_dist: u32, + bits_per_second: u32, + intra_period: u32, + reference_frames: [bindings::VASurfaceID; 4usize], + ) -> Self { + Self(Box::new(bindings::VAEncSequenceParameterBufferVP8 { + frame_width, + frame_height, + frame_width_scale, + frame_height_scale, + error_resilient, + kf_auto, + kf_min_dist, + kf_max_dist, + bits_per_second, + intra_period, + reference_frames, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferVP8 { + &mut self.0 + } +} + +pub struct VP8EncRefFlags(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1); + +impl VP8EncRefFlags { + pub fn new( + force_kf: u32, + no_ref_last: u32, + no_ref_gf: u32, + no_ref_arf: u32, + temporal_id: u32, + first_ref: u32, + second_ref: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + force_kf, + no_ref_last, + no_ref_gf, + no_ref_arf, + temporal_id, + first_ref, + second_ref, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct VP8EncPicFlags(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2); + +impl VP8EncPicFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + version: u32, + show_frame: u32, + color_space: u32, + recon_filter_type: u32, + loop_filter_type: u32, + auto_partitions: u32, + num_token_partitions: u32, + clamping_type: u32, + segmentation_enabled: u32, + update_mb_segmentation_map: u32, + update_segment_feature_data: u32, + loop_filter_adj_enable: u32, + refresh_entropy_probs: u32, + refresh_golden_frame: u32, + refresh_alternate_frame: u32, + refresh_last: u32, + copy_buffer_to_golden: u32, + copy_buffer_to_alternate: u32, + sign_bias_golden: u32, + sign_bias_alternate: u32, + mb_no_coeff_skip: u32, + forced_lf_adjustment: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + version, + show_frame, + color_space, + recon_filter_type, + loop_filter_type, + auto_partitions, + num_token_partitions, + clamping_type, + segmentation_enabled, + update_mb_segmentation_map, + update_segment_feature_data, + loop_filter_adj_enable, + refresh_entropy_probs, + refresh_golden_frame, + refresh_alternate_frame, + refresh_last, + copy_buffer_to_golden, + copy_buffer_to_alternate, + sign_bias_golden, + sign_bias_alternate, + mb_no_coeff_skip, + forced_lf_adjustment, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferVP8__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferVP8(Box); + +impl EncPictureParameterBufferVP8 { + #[allow(clippy::too_many_arguments)] + pub fn new( + reconstructed_frame: bindings::VASurfaceID, + ref_last_frame: bindings::VASurfaceID, + ref_gf_frame: bindings::VASurfaceID, + ref_arf_frame: bindings::VASurfaceID, + coded_buf: bindings::VABufferID, + ref_flags: &VP8EncRefFlags, + pic_flags: &VP8EncPicFlags, + loop_filter_level: [i8; 4usize], + ref_lf_delta: [i8; 4usize], + mode_lf_delta: [i8; 4usize], + sharpness_level: u8, + clamp_qindex_high: u8, + clamp_qindex_low: u8, + ) -> Self { + let ref_flags = ref_flags.0; + let pic_flags = pic_flags.0; + + Self(Box::new(bindings::VAEncPictureParameterBufferVP8 { + reconstructed_frame, + ref_last_frame, + ref_gf_frame, + ref_arf_frame, + coded_buf, + ref_flags, + pic_flags, + loop_filter_level, + ref_lf_delta, + mode_lf_delta, + sharpness_level, + clamp_qindex_high, + clamp_qindex_low, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferVP8 { + &mut self.0 + } +} diff --git a/vendor/cros-libva/src/buffer/vp9.rs b/vendor/cros-libva/src/buffer/vp9.rs new file mode 100644 index 0000000..12d1f0b --- /dev/null +++ b/vendor/cros-libva/src/buffer/vp9.rs @@ -0,0 +1,448 @@ +// Copyright 2023 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Wrappers around VP9 `VABuffer` types. + +use crate::bindings; + +/// Wrapper over the `pic_fields` bindgen field in `VAPictureParameterBufferVP9`. +pub struct VP9PicFields(bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1); + +impl VP9PicFields { + /// Creates the bindgen field + #[allow(clippy::too_many_arguments)] + pub fn new( + subsampling_x: u32, + subsampling_y: u32, + frame_type: u32, + show_frame: u32, + error_resilient_mode: u32, + intra_only: u32, + allow_high_precision_mv: u32, + mcomp_filter_type: u32, + frame_parallel_decoding_mode: u32, + reset_frame_context: u32, + refresh_frame_context: u32, + frame_context_idx: u32, + segmentation_enabled: u32, + segmentation_temporal_update: u32, + segmentation_update_map: u32, + last_ref_frame: u32, + last_ref_frame_sign_bias: u32, + golden_ref_frame: u32, + golden_ref_frame_sign_bias: u32, + alt_ref_frame: u32, + alt_ref_frame_sign_bias: u32, + lossless_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + subsampling_x, + subsampling_y, + frame_type, + show_frame, + error_resilient_mode, + intra_only, + allow_high_precision_mv, + mcomp_filter_type, + frame_parallel_decoding_mode, + reset_frame_context, + refresh_frame_context, + frame_context_idx, + segmentation_enabled, + segmentation_temporal_update, + segmentation_update_map, + last_ref_frame, + last_ref_frame_sign_bias, + golden_ref_frame, + golden_ref_frame_sign_bias, + alt_ref_frame, + alt_ref_frame_sign_bias, + lossless_flag, + ); + + Self(bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1 { + bits: bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VADecPictureParameterBufferVP9__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `PictureParameterBufferVP9` FFI type. +pub struct PictureParameterBufferVP9(Box); + +impl PictureParameterBufferVP9 { + /// Creates the wrapper + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width: u16, + frame_height: u16, + reference_frames: [bindings::VASurfaceID; 8], + pic_fields: &VP9PicFields, + filter_level: u8, + sharpness_level: u8, + log2_tile_rows: u8, + log2_tile_columns: u8, + frame_header_length_in_bytes: u8, + first_partition_size: u16, + mb_segment_tree_probs: [u8; 7usize], + segment_pred_probs: [u8; 3usize], + profile: u8, + bit_depth: u8, + ) -> Self { + let pic_fields = pic_fields.0; + + Self(Box::new(bindings::VADecPictureParameterBufferVP9 { + frame_width, + frame_height, + reference_frames, + pic_fields, + filter_level, + sharpness_level, + log2_tile_rows, + log2_tile_columns, + frame_header_length_in_bytes, + first_partition_size, + mb_segment_tree_probs, + segment_pred_probs, + profile, + bit_depth, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VADecPictureParameterBufferVP9 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VADecPictureParameterBufferVP9 { + self.0.as_ref() + } +} + +/// Wrapper over the `segment_flags` bindgen field in `VASegmentParameterVP9`. +pub struct VP9SegmentFlags(bindings::_VASegmentParameterVP9__bindgen_ty_1); + +impl VP9SegmentFlags { + /// Creates the wrapper. + pub fn new( + segment_reference_enabled: u16, + segment_reference: u16, + segment_reference_skipped: u16, + ) -> Self { + let _bitfield_1 = + bindings::_VASegmentParameterVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + segment_reference_enabled, + segment_reference, + segment_reference_skipped, + ); + + Self(bindings::_VASegmentParameterVP9__bindgen_ty_1 { + fields: bindings::_VASegmentParameterVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + __bindgen_padding_0: Default::default(), + }, + }) + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&mut self) -> &bindings::_VASegmentParameterVP9__bindgen_ty_1 { + &self.0 + } +} + +/// Wrapper over the `VASegmentParameterVP9` FFI type. +pub struct SegmentParameterVP9(bindings::VASegmentParameterVP9); + +impl SegmentParameterVP9 { + /// Creates the wrapper. + pub fn new( + segment_flags: &VP9SegmentFlags, + filter_level: [[u8; 2usize]; 4usize], + luma_ac_quant_scale: i16, + luma_dc_quant_scale: i16, + chroma_ac_quant_scale: i16, + chroma_dc_quant_scale: i16, + ) -> Self { + let segment_flags = segment_flags.0; + + Self(bindings::VASegmentParameterVP9 { + segment_flags, + filter_level, + luma_ac_quant_scale, + luma_dc_quant_scale, + chroma_ac_quant_scale, + chroma_dc_quant_scale, + va_reserved: Default::default(), + }) + } +} + +/// Wrapper over the `VASliceParameterBufferVP9` FFI type. +pub struct SliceParameterBufferVP9(Box); + +impl SliceParameterBufferVP9 { + /// Creates the wrapper. + pub fn new( + slice_data_size: u32, + slice_data_offset: u32, + slice_data_flag: u32, + seg_param: [SegmentParameterVP9; 8usize], + ) -> Self { + let seg_param = seg_param.map(|param| param.0); + + Self(Box::new(bindings::VASliceParameterBufferVP9 { + slice_data_size, + slice_data_offset, + slice_data_flag, + seg_param, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VASliceParameterBufferVP9 { + self.0.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VASliceParameterBufferVP9 { + self.0.as_ref() + } +} + +pub struct CodedBufferVP9Status(Box); + +impl CodedBufferVP9Status { + pub fn new( + base_qp_index: u16, + loop_filter_level: u8, + long_term_indication: u8, + next_frame_width: u16, + next_frame_height: u16, + ) -> Self { + Self(Box::new(bindings::VACodedBufferVP9Status { + base_qp_index, + loop_filter_level, + long_term_indication, + next_frame_width, + next_frame_height, + va_reserved: Default::default(), + })) + } +} + +pub struct EncSequenceParameterBufferVP9(Box); + +impl EncSequenceParameterBufferVP9 { + pub fn new( + max_frame_width: u32, + max_frame_height: u32, + kf_auto: u32, + kf_min_dist: u32, + kf_max_dist: u32, + bits_per_second: u32, + intra_period: u32, + ) -> Self { + Self(Box::new(bindings::VAEncSequenceParameterBufferVP9 { + max_frame_width, + max_frame_height, + kf_auto, + kf_min_dist, + kf_max_dist, + bits_per_second, + intra_period, + va_reserved: Default::default(), + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncSequenceParameterBufferVP9 { + &mut self.0 + } +} + +pub struct VP9EncRefFlags(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1); + +impl VP9EncRefFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + force_kf: u32, + ref_frame_ctrl_l0: u32, + ref_frame_ctrl_l1: u32, + ref_last_idx: u32, + ref_last_sign_bias: u32, + ref_gf_idx: u32, + ref_gf_sign_bias: u32, + ref_arf_idx: u32, + ref_arf_sign_bias: u32, + temporal_id: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1::new_bitfield_1( + force_kf, + ref_frame_ctrl_l0, + ref_frame_ctrl_l1, + ref_last_idx, + ref_last_sign_bias, + ref_gf_idx, + ref_gf_sign_bias, + ref_arf_idx, + ref_arf_sign_bias, + temporal_id, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1 { + bits: bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_1__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct VP9EncPicFlags(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2); + +impl VP9EncPicFlags { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_type: u32, + show_frame: u32, + error_resilient_mode: u32, + intra_only: u32, + allow_high_precision_mv: u32, + mcomp_filter_type: u32, + frame_parallel_decoding_mode: u32, + reset_frame_context: u32, + refresh_frame_context: u32, + frame_context_idx: u32, + segmentation_enabled: u32, + segmentation_temporal_update: u32, + segmentation_update_map: u32, + lossless_mode: u32, + comp_prediction_mode: u32, + auto_segmentation: u32, + super_frame_flag: u32, + ) -> Self { + let _bitfield_1 = + bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2__bindgen_ty_1::new_bitfield_1( + frame_type, + show_frame, + error_resilient_mode, + intra_only, + allow_high_precision_mv, + mcomp_filter_type, + frame_parallel_decoding_mode, + reset_frame_context, + refresh_frame_context, + frame_context_idx, + segmentation_enabled, + segmentation_temporal_update, + segmentation_update_map, + lossless_mode, + comp_prediction_mode, + auto_segmentation, + super_frame_flag, + Default::default(), + ); + + Self(bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2 { + bits: bindings::_VAEncPictureParameterBufferVP9__bindgen_ty_2__bindgen_ty_1 { + _bitfield_align_1: Default::default(), + _bitfield_1, + }, + }) + } +} + +pub struct EncPictureParameterBufferVP9(Box); + +impl EncPictureParameterBufferVP9 { + #[allow(clippy::too_many_arguments)] + pub fn new( + frame_width_src: u32, + frame_height_src: u32, + frame_width_dst: u32, + frame_height_dst: u32, + reconstructed_frame: bindings::VASurfaceID, + reference_frames: [bindings::VASurfaceID; 8usize], + coded_buf: bindings::VABufferID, + ref_flags: &VP9EncRefFlags, + pic_flags: &VP9EncPicFlags, + refresh_frame_flags: u8, + luma_ac_qindex: u8, + luma_dc_qindex_delta: i8, + chroma_ac_qindex_delta: i8, + chroma_dc_qindex_delta: i8, + filter_level: u8, + sharpness_level: u8, + ref_lf_delta: [i8; 4usize], + mode_lf_delta: [i8; 2usize], + bit_offset_ref_lf_delta: u16, + bit_offset_mode_lf_delta: u16, + bit_offset_lf_level: u16, + bit_offset_qindex: u16, + bit_offset_first_partition_size: u16, + bit_offset_segmentation: u16, + bit_size_segmentation: u16, + log2_tile_rows: u8, + log2_tile_columns: u8, + skip_frame_flag: u8, + number_skip_frames: u8, + skip_frames_size: u32, + ) -> Self { + let ref_flags = ref_flags.0; + let pic_flags = pic_flags.0; + + Self(Box::new(bindings::VAEncPictureParameterBufferVP9 { + frame_width_src, + frame_height_src, + frame_width_dst, + frame_height_dst, + reconstructed_frame, + reference_frames, + coded_buf, + ref_flags, + pic_flags, + refresh_frame_flags, + luma_ac_qindex, + luma_dc_qindex_delta, + chroma_ac_qindex_delta, + chroma_dc_qindex_delta, + filter_level, + sharpness_level, + ref_lf_delta, + mode_lf_delta, + bit_offset_ref_lf_delta, + bit_offset_mode_lf_delta, + bit_offset_lf_level, + bit_offset_qindex, + bit_offset_first_partition_size, + bit_offset_segmentation, + bit_size_segmentation, + log2_tile_rows, + log2_tile_columns, + skip_frame_flag, + number_skip_frames, + skip_frames_size, + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): libva 1.23 carved + // `seg_id_block_size` + `va_reserved8` out of this struct's reserved + // space, so an exhaustive literal no longer compiles. Upstream is + // only aware of libva <= 1.21. + ..Default::default() + })) + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAEncPictureParameterBufferVP9 { + &mut self.0 + } +} diff --git a/vendor/cros-libva/src/config.rs b/vendor/cros-libva/src/config.rs new file mode 100644 index 0000000..7755062 --- /dev/null +++ b/vendor/cros-libva/src/config.rs @@ -0,0 +1,137 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use log::error; +use thiserror::Error; + +use crate::bindings; +use crate::display::Display; +use crate::generic_value::GenericValue; +use crate::va_check; +use crate::GenericValueError; +use crate::VaError; + +/// A configuration for a given [`Display`]. +pub struct Config { + display: Rc, + id: bindings::VAConfigID, +} + +#[derive(Debug, Error)] +pub enum QuerySurfaceAttributesError { + #[error("error while calling vaQuerySurfaceAttributes: {0}")] + VaError(#[from] VaError), + #[error("error while converting attribute: {0}")] + GenericValueError(#[from] GenericValueError), +} + +impl Config { + /// Creates a Config by wrapping around the `vaCreateConfig` call. This is just a helper for + /// [`Display::create_config`]. + pub(crate) fn new( + display: Rc, + mut attrs: Vec, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + ) -> Result { + let mut config_id = 0u32; + + // Safe because `self` represents a valid `VADisplay`. + // + // The `attrs` vector is also properly initialized and its actual size is passed to + // `vaCreateConfig`, so it is impossible to write past the end of its storage by mistake. + va_check(unsafe { + bindings::vaCreateConfig( + display.handle(), + profile, + entrypoint, + attrs.as_mut_ptr(), + attrs.len() as i32, + &mut config_id, + ) + })?; + + Ok(Self { + display, + id: config_id, + }) + } + + /// Returns the ID of this config. + pub(crate) fn id(&self) -> bindings::VAConfigID { + self.id + } + + // Queries surface attributes for this config. + // + // This function queries for all supported attributes for this configuration. In particular, if + // the underlying hardware supports the creation of VA surfaces in various formats, then this + // function will enumerate all pixel formats that are supported. + fn query_surface_attributes(&mut self) -> Result, VaError> { + // Safe because `self` represents a valid VAConfig. We first query how + // much space is needed by the C API by passing in NULL in the first + // call to `vaQuerySurfaceAttributes`. + let attrs_len: std::os::raw::c_uint = 0; + va_check(unsafe { + bindings::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + std::ptr::null_mut(), + &attrs_len as *const _ as *mut std::os::raw::c_uint, + ) + })?; + + let mut attrs = Vec::with_capacity(attrs_len as usize); + // Safe because we allocate a vector with the required capacity as + // returned by the initial call to vaQuerySurfaceAttributes. We then + // pass a valid pointer to it. + va_check(unsafe { + bindings::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + attrs.as_mut_ptr(), + &attrs_len as *const _ as *mut std::os::raw::c_uint, + ) + })?; + + // Safe because vaQuerySurfaceAttributes will have written to + // exactly attrs_len entries in the vector. + unsafe { + attrs.set_len(attrs_len as usize); + } + + Ok(attrs) + } + + /// Query the surface attributes of type `attr_type`. The attribute may or may not be defined by + /// the driver. + pub fn query_surface_attributes_by_type( + &mut self, + attr_type: bindings::VASurfaceAttribType::Type, + ) -> Result, QuerySurfaceAttributesError> { + let surface_attributes = self.query_surface_attributes()?; + + surface_attributes + .into_iter() + .filter(|attr| attr.type_ == attr_type) + .map(|attr| { + GenericValue::try_from(attr.value) + .map_err(QuerySurfaceAttributesError::GenericValueError) + }) + .collect() + } +} + +impl Drop for Config { + fn drop(&mut self) { + // Safe because `self` represents a valid Config. + let status = va_check(unsafe { bindings::vaDestroyConfig(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyConfig failed: {}", status.unwrap_err()); + } + } +} diff --git a/vendor/cros-libva/src/context.rs b/vendor/cros-libva/src/context.rs new file mode 100644 index 0000000..1d7414d --- /dev/null +++ b/vendor/cros-libva/src/context.rs @@ -0,0 +1,102 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use log::error; + +use crate::bindings; +use crate::buffer::Buffer; +use crate::buffer::BufferType; +use crate::display::Display; +use crate::va_check; +use crate::Config; +use crate::EncCodedBuffer; +use crate::Surface; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +/// A VA context for a particular [`Display`]. +pub struct Context { + display: Rc, + id: bindings::VAContextID, +} + +impl Context { + /// Creates a Context by wrapping around a `vaCreateContext` call. This is just a helper for + /// [`Display::create_context`]. + pub(crate) fn new( + display: Rc, + config: &Config, + coded_width: u32, + coded_height: u32, + surfaces: Option<&Vec>>, + progressive: bool, + ) -> Result, VaError> { + let mut context_id = 0; + let flags = if progressive { + bindings::VA_PROGRESSIVE as i32 + } else { + 0 + }; + + let mut render_targets = match surfaces { + Some(surfaces) => Surface::as_id_vec(surfaces), + None => Default::default(), + }; + + // Safe because `self` represents a valid VADisplay and render_targets + // and ntargets are properly initialized. Note that render_targets==NULL + // is valid so long as ntargets==0. + va_check(unsafe { + bindings::vaCreateContext( + display.handle(), + config.id(), + coded_width as i32, + coded_height as i32, + flags, + render_targets.as_mut_ptr(), + render_targets.len() as i32, + &mut context_id, + ) + })?; + + Ok(Rc::new(Self { + display, + id: context_id, + })) + } + + /// Returns a shared reference to the [`Display`] used by this context. + pub fn display(&self) -> &Rc { + &self.display + } + + /// Returns the ID of this context. + pub(crate) fn id(&self) -> bindings::VAContextID { + self.id + } + + /// Create a new buffer of type `type_`. + pub fn create_buffer(self: &Rc, type_: BufferType) -> Result { + Buffer::new(Rc::clone(self), type_) + } + + /// Create a new buffer of type `type_`. + pub fn create_enc_coded(self: &Rc, size: usize) -> Result { + EncCodedBuffer::new(Rc::clone(self), size) + } +} + +impl Drop for Context { + fn drop(&mut self) { + // Safe because `self` represents a valid VAContext. + let status = + va_check(unsafe { bindings::vaDestroyContext(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyContext failed: {}", status.unwrap_err()); + } + } +} diff --git a/vendor/cros-libva/src/display.rs b/vendor/cros-libva/src/display.rs new file mode 100644 index 0000000..ef9eef6 --- /dev/null +++ b/vendor/cros-libva/src/display.rs @@ -0,0 +1,362 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::ffi::CStr; +use std::fs::File; +use std::io; +use std::os::unix::io::AsRawFd; +use std::path::Path; +use std::path::PathBuf; +use std::rc::Rc; + +use thiserror::Error; + +use crate::bindings; +use crate::config::Config; +use crate::context::Context; +use crate::surface::Surface; +use crate::va_check; +use crate::SurfaceMemoryDescriptor; +use crate::UsageHint; +use crate::VaError; + +/// Iterates over existing DRM devices. +/// +/// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on +/// that device. +pub struct DrmDeviceIterator { + cur_idx: usize, +} + +const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD"; +const DRM_NUM_NODES: usize = 64; +const DRM_RENDER_NODE_START: usize = 128; + +impl Default for DrmDeviceIterator { + fn default() -> Self { + Self { + cur_idx: DRM_RENDER_NODE_START, + } + } +} + +impl Iterator for DrmDeviceIterator { + type Item = PathBuf; + + fn next(&mut self) -> Option { + match self.cur_idx { + idx if idx >= DRM_RENDER_NODE_START + DRM_NUM_NODES => None, + idx => { + let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, idx)); + if !path.exists() { + None + } else { + self.cur_idx += 1; + Some(path) + } + } + } + } +} + +/// A VADisplay opened over DRM. +/// +/// A Display is the starting point to using libva. This struct is essentially a safe wrapper over +/// `VADisplay`, from which [`Surface`]s and [`Context`]s can be allocated in order to perform +/// actual work using [`Display::create_surfaces`] and [`Display::create_context`], respectively. +/// +/// Although libva offers several ways to create a display, this struct currently only supports +/// opening through DRM. It may be extended to support other display types (X11, Wayland) in the +/// future. +pub struct Display { + /// Handle to interact with the underlying `VADisplay`. + handle: bindings::VADisplay, + /// DRM file that must be kept open while the display is in use. + #[allow(dead_code)] + drm_file: File, +} + +/// Error type for `Display::open_drm_display`. +#[derive(Debug, Error)] +pub enum OpenDrmDisplayError { + #[error("cannot open DRM device: {0}")] + DeviceOpen(io::Error), + #[error("vaGetDisplayDRM returned NULL")] + VaGetDisplayDrm, + #[error("call to vaInitialize failed: {0}")] + VaInitialize(VaError), +} + +impl Display { + /// Opens and initializes a specific DRM `Display`. + /// + /// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`. + pub fn open_drm_display>(path: P) -> Result, OpenDrmDisplayError> { + let file = std::fs::File::options() + .read(true) + .write(true) + .open(path.as_ref()) + .map_err(OpenDrmDisplayError::DeviceOpen)?; + + // Safe because fd represents a valid file descriptor and the pointer is checked for + // NULL afterwards. + let display = unsafe { bindings::vaGetDisplayDRM(file.as_raw_fd()) }; + if display.is_null() { + return Err(OpenDrmDisplayError::VaGetDisplayDrm); + } + + let mut major = 0i32; + let mut minor = 0i32; + // Safe because we ensure that the display is valid (i.e not NULL) before calling + // vaInitialize. The File will close the DRM fd on drop. + va_check(unsafe { bindings::vaInitialize(display, &mut major, &mut minor) }) + .map(|()| { + Rc::new(Self { + handle: display, + drm_file: file, + }) + }) + .map_err(OpenDrmDisplayError::VaInitialize) + } + + /// Opens the first device that succeeds and returns its `Display`. + /// + /// If an error occurs on a given device, it is ignored and the next one is tried until one + /// succeeds or we reach the end of the iterator. + pub fn open() -> Option> { + let devices = DrmDeviceIterator::default(); + + // Try all the DRM devices until one succeeds. + for device in devices { + if let Ok(display) = Self::open_drm_display(device) { + return Some(display); + } + } + + None + } + + /// Returns the handle of this display. + pub(crate) fn handle(&self) -> bindings::VADisplay { + self.handle + } + + /// Queries supported profiles by this display by wrapping `vaQueryConfigProfiles`. + pub fn query_config_profiles(&self) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut max_num_profiles = unsafe { bindings::vaMaxNumProfiles(self.handle) }; + let mut profiles = Vec::with_capacity(max_num_profiles as usize); + + // Safe because `self` represents a valid `VADisplay` and the vector has `max_num_profiles` + // as capacity. + va_check(unsafe { + bindings::vaQueryConfigProfiles( + self.handle, + profiles.as_mut_ptr(), + &mut max_num_profiles, + ) + })?; + + // Safe because `profiles` is allocated with a `max_num_profiles` capacity and + // `vaQueryConfigProfiles` wrote the actual number of profiles to `max_num_entrypoints`. + unsafe { + profiles.set_len(max_num_profiles as usize); + }; + + Ok(profiles) + } + + /// Returns a string describing some aspects of the VA implemenation on the specific hardware + /// accelerator used by this display. Wrapper over `vaQueryVendorString`. + /// + /// The format of the returned string is vendor specific and at the discretion of the + /// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 - + /// 2.0.0.32L.0005`. + pub fn query_vendor_string(&self) -> std::result::Result { + // Safe because `self` represents a valid VADisplay. + let vendor_string = unsafe { bindings::vaQueryVendorString(self.handle) }; + + if vendor_string.is_null() { + return Err("vaQueryVendorString() returned NULL"); + } + + // Safe because we check the whether the vendor_String pointer is NULL + Ok(unsafe { CStr::from_ptr(vendor_string) } + .to_string_lossy() + .to_string()) + } + + /// Query supported entrypoints for a given profile by wrapping `vaQueryConfigEntrypoints`. + pub fn query_config_entrypoints( + &self, + profile: bindings::VAProfile::Type, + ) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut max_num_entrypoints = unsafe { bindings::vaMaxNumEntrypoints(self.handle) }; + let mut entrypoints = Vec::with_capacity(max_num_entrypoints as usize); + + // Safe because `self` represents a valid VADisplay and the vector has `max_num_entrypoints` + // as capacity. + va_check(unsafe { + bindings::vaQueryConfigEntrypoints( + self.handle, + profile, + entrypoints.as_mut_ptr(), + &mut max_num_entrypoints, + ) + })?; + + // Safe because `entrypoints` is allocated with a `max_num_entrypoints` capacity, and + // `vaQueryConfigEntrypoints` wrote the actual number of entrypoints to + // `max_num_entrypoints` + unsafe { + entrypoints.set_len(max_num_entrypoints as usize); + } + + Ok(entrypoints) + } + + /// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`. Wrapper over + /// `vaGetConfigAttributes`. + /// + /// Entries of `attributes` must have their `type_` member initialized to the desired attribute + /// to retrieve. + pub fn get_config_attributes( + &self, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + attributes: &mut [bindings::VAConfigAttrib], + ) -> Result<(), VaError> { + // Safe because `self` represents a valid VADisplay. The slice length is passed to the C + // function, so it is impossible to write past the end of the slice's storage by mistake. + va_check(unsafe { + bindings::vaGetConfigAttributes( + self.handle, + profile, + entrypoint, + attributes.as_mut_ptr(), + attributes.len() as i32, + ) + }) + } + + /// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call. + /// + /// The number of surfaces created will be equal to the length of `descriptors`. + /// + /// # Arguments + /// + /// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*` + /// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*` + /// * `width` - Width for the create surfaces + /// * `height` - Height for the created surfaces + /// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling) + /// * `num_surfaces` - Number of surfaces to create + /// * `descriptors` - Memory descriptors used as surface memory backing. + /// + /// # Return value + /// + /// Returns as many surfaces as the length of `descriptors`. + /// + /// Note that the `descriptors`'s ownership is irrevocably given to the surfaces, and that in + /// case of error the `descriptors` will be destroyed. Make sure to duplicate the descriptors + /// if you need something outside of libva to access them. + pub fn create_surfaces( + self: &Rc, + rt_format: u32, + va_fourcc: Option, + width: u32, + height: u32, + usage_hint: Option, + descriptors: Vec, + ) -> Result>, VaError> { + Surface::new( + Rc::clone(self), + rt_format, + va_fourcc, + width, + height, + usage_hint, + descriptors, + ) + } + + /// Creates a `Context` by wrapping around a `vaCreateContext` call. + /// + /// # Arguments + /// + /// * `config` - The configuration for the context + /// * `coded_width` - The coded picture width + /// * `coded_height` - The coded picture height + /// * `surfaces` - Optional hint for the amount of surfaces tied to the context + /// * `progressive` - Whether only progressive frame pictures are present in the sequence + pub fn create_context( + self: &Rc, + config: &Config, + coded_width: u32, + coded_height: u32, + surfaces: Option<&Vec>>, + progressive: bool, + ) -> Result, VaError> { + Context::new( + Rc::clone(self), + config, + coded_width, + coded_height, + surfaces, + progressive, + ) + } + + /// Creates a `Config` by wrapping around the `vaCreateConfig` call. + /// + /// `attrs` describe the attributes to set for this config. A list of the supported attributes + /// for a given profile/entrypoint pair can be retrieved using + /// [`Display::get_config_attributes`]. Other attributes will take their default values, and + /// `attrs` can be empty in order to obtain a default configuration. + pub fn create_config( + self: &Rc, + attrs: Vec, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + ) -> Result { + Config::new(Rc::clone(self), attrs, profile, entrypoint) + } + + /// Returns available image formats for this display by wrapping around `vaQueryImageFormats`. + pub fn query_image_formats(&self) -> Result, VaError> { + // Safe because `self` represents a valid VADisplay. + let mut num_image_formats = unsafe { bindings::vaMaxNumImageFormats(self.handle) }; + let mut image_formats = Vec::with_capacity(num_image_formats as usize); + + // Safe because `self` represents a valid VADisplay. The `image_formats` vector is properly + // initialized and a valid size is passed to the C function, so it is impossible to write + // past the end of their storage by mistake. + va_check(unsafe { + bindings::vaQueryImageFormats( + self.handle, + image_formats.as_mut_ptr(), + &mut num_image_formats, + ) + })?; + + // Safe because the C function will have written exactly `num_image_format` entries, which + // is known to be within the vector's capacity. + unsafe { + image_formats.set_len(num_image_formats as usize); + } + + Ok(image_formats) + } +} + +impl Drop for Display { + fn drop(&mut self) { + // Safe because `self` represents a valid VADisplay. + unsafe { + bindings::vaTerminate(self.handle); + // The File will close the DRM fd on drop. + } + } +} diff --git a/vendor/cros-libva/src/generic_value.rs b/vendor/cros-libva/src/generic_value.rs new file mode 100644 index 0000000..621d0b0 --- /dev/null +++ b/vendor/cros-libva/src/generic_value.rs @@ -0,0 +1,50 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use thiserror::Error; + +use crate::bindings; + +/// A wrapper over `VAGenericValue` giving us safe access to the underlying union members. +#[derive(Debug)] +pub enum GenericValue { + /// A wrapper over VAGenericValueTypeInteger + Integer(i32), + /// A wrapper over VAGenericValueTypeFloat + Float(f32), + /// A wrapper over VAGenericValueTypePointer + Pointer(*mut std::os::raw::c_void), + /// A wrapper over VAGenericValueTypeFunc + Func(bindings::VAGenericFunc), +} + +#[derive(Debug, Error)] +pub enum GenericValueError { + #[error("unexpected VAGenericValueType {0}")] + UnexpectedType(u32), +} + +impl TryFrom for GenericValue { + type Error = GenericValueError; + + fn try_from(value: bindings::VAGenericValue) -> Result { + // Safe because we check the type before accessing the union. + match value.type_ { + // Safe because we check the type before accessing the union. + bindings::VAGenericValueType::VAGenericValueTypeInteger => { + Ok(Self::Integer(unsafe { value.value.i })) + } + bindings::VAGenericValueType::VAGenericValueTypeFloat => { + Ok(Self::Float(unsafe { value.value.f })) + } + bindings::VAGenericValueType::VAGenericValueTypePointer => { + Ok(Self::Pointer(unsafe { value.value.p })) + } + bindings::VAGenericValueType::VAGenericValueTypeFunc => { + Ok(Self::Func(unsafe { value.value.fn_ })) + } + _ => Err(GenericValueError::UnexpectedType(value.type_)), + } + } +} diff --git a/vendor/cros-libva/src/image.rs b/vendor/cros-libva/src/image.rs new file mode 100644 index 0000000..255a44e --- /dev/null +++ b/vendor/cros-libva/src/image.rs @@ -0,0 +1,235 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::rc::Rc; + +use crate::bindings; +use crate::va_check; +use crate::Display; +use crate::Surface; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +/// Wrapper around `VAImage` that is tied to the lifetime of a given `Picture`. +/// +/// An image is used to either get the surface data to client memory, or to copy image data in +/// client memory to a surface. +pub struct Image<'a> { + /// The display from which the image was created, so we can unmap it upon destruction. + display: Rc, + /// The `VAImage` returned by libva. + image: bindings::VAImage, + /// The mapped surface data. + /// + /// The lifetime also allows us to ensure that the `Surface` we have been created from + /// does not drop or get changed while we exist. + data: &'a mut [u8], + /// Whether the image was derived using the `vaDeriveImage` API or created using the + /// `vaCreateImage` API. + derived: bool, + /// The display resolution requested by the client. The implementation is + /// free to enlarge this value as needed. In any case, we guarantee that an + /// image at least as large is returned. + display_resolution: (u32, u32), + /// Tracks whether the underlying data has possibly been written to, i.e. an encoder will create + /// an image and map its buffer in order to write to it, so we must writeback later. + dirty: bool, + /// The ID of the `Surface` we have been created from. + surface_id: u32, +} + +impl<'a> Image<'a> { + /// Helper method to map a `VAImage` using `vaMapBuffer` and return an `Image`. + /// + /// Returns an error if the mapping failed. + fn new( + surface: &'a Surface, + image: bindings::VAImage, + derived: bool, + display_resolution: (u32, u32), + ) -> Result { + let mut addr = std::ptr::null_mut(); + + // Safe since `picture.inner.context` represents a valid `VAContext` and `image` has been + // successfully created at this point. + match va_check(unsafe { + bindings::vaMapBuffer(surface.display().handle(), image.buf, &mut addr) + }) { + Ok(_) => { + // Assert that libva provided us with a coded resolution that is + // at least as large as `display_resolution`. + assert!(u32::from(image.width) >= display_resolution.0); + assert!(u32::from(image.height) >= display_resolution.1); + + // Safe since `addr` points to data mapped onto our address space since we called + // `vaMapBuffer` above, which also guarantees that the data is valid for + // `image.data_size`. + let data = + unsafe { std::slice::from_raw_parts_mut(addr as _, image.data_size as usize) }; + Ok(Image { + display: Rc::clone(surface.display()), + image, + data, + derived, + display_resolution, + dirty: false, + surface_id: surface.id(), + }) + } + Err(e) => { + // Safe because `picture.inner.context` represents a valid `VAContext` and `image` + // represents a valid `VAImage`. + unsafe { + bindings::vaDestroyImage(surface.display().handle(), image.image_id); + } + + Err(e) + } + } + } + + /// Create a new derived image from this `surface` using `vaDeriveImage`. + /// + /// Derived images are a direct view (i.e. without any copy) on the buffer content of + /// `surface`. On the other hand, not all `Surface`s can be derived. + /// + /// `visible_rect` is the visible rectangle inside `surface` that we want to access. + pub fn derive_from( + surface: &'a Surface, + visible_rect: (u32, u32), + ) -> Result { + // An all-zero byte-pattern is a valid initial value for `VAImage`. + let mut image: bindings::VAImage = Default::default(); + + // Safe because `self` has a valid display handle and ID. + va_check(unsafe { + bindings::vaDeriveImage(surface.display().handle(), surface.id(), &mut image) + })?; + + Self::new(surface, image, true, visible_rect) + } + + /// Create new image from `surface` using `vaCreateImage` and `vaGetImage`. + /// + /// `visible_rect` is the visible rectangle inside `surface` that we want to access. + /// + /// The image will contain a copy of `surface`'s data' in the desired `format` and + /// `coded_resolution`, meaning the data can be scaled if `coded_resolution` and `visible_rect` + /// differ. + pub fn create_from( + surface: &'a Surface, + mut format: bindings::VAImageFormat, + coded_resolution: (u32, u32), + visible_rect: (u32, u32), + ) -> Result { + // An all-zero byte-pattern is a valid initial value for `VAImage`. + let mut image: bindings::VAImage = Default::default(); + let dpy = surface.display().handle(); + + // Safe because `dpy` is a valid display handle. + va_check(unsafe { + bindings::vaCreateImage( + dpy, + &mut format, + coded_resolution.0 as i32, + coded_resolution.1 as i32, + &mut image, + ) + })?; + + // Safe because `dpy` is a valid display handle, `picture.surface` is a valid VASurface and + // `image` is a valid `VAImage`. + match va_check(unsafe { + bindings::vaGetImage( + dpy, + surface.id(), + 0, + 0, + coded_resolution.0, + coded_resolution.1, + image.image_id, + ) + }) { + Ok(()) => Self::new(surface, image, false, visible_rect), + + Err(e) => { + // Safe because `image` is a valid `VAImage`. + unsafe { + bindings::vaDestroyImage(dpy, image.image_id); + } + + Err(e) + } + } + } + + /// Get a reference to the underlying `VAImage` that describes this image. + pub fn image(&self) -> &bindings::VAImage { + &self.image + } + + /// Returns whether this image is directly derived from its underlying `Picture`, as opposed to + /// being a view/copy of said `Picture` in a guaranteed pixel format. + pub fn is_derived(&self) -> bool { + self.derived + } + + /// Returns the display resolution as passed in by the client. This is a + /// value that is less than or equal to the coded resolution. + pub fn display_resolution(&self) -> (u32, u32) { + self.display_resolution + } + + /// Returns the coded resolution. This value can be larger than the value + /// passed in when the image was created if the driver needs to. + pub fn coded_resolution(&self) -> (u32, u32) { + (self.image.width.into(), self.image.height.into()) + } +} + +impl<'a> AsRef<[u8]> for Image<'a> { + fn as_ref(&self) -> &[u8] { + self.data + } +} + +impl<'a> AsMut<[u8]> for Image<'a> { + fn as_mut(&mut self) -> &mut [u8] { + self.dirty = true; + self.data + } +} + +impl<'a> Drop for Image<'a> { + fn drop(&mut self) { + if !self.derived && self.dirty { + // Safe because `picture.inner.context` represents a valid `VAContext`, + // `picture.surface` represents a valid `VASurface` and `image` represents a valid + // `VAImage`. + unsafe { + bindings::vaPutImage( + self.display.handle(), + self.surface_id, + self.image.image_id, + 0, + 0, + self.image.width as u32, + self.image.height as u32, + 0, + 0, + self.image.width as u32, + self.image.height as u32, + ); + } + } + + unsafe { + // Safe since the buffer is mapped in `Image::new`, so `self.image.buf` points to a + // valid `VABufferID`. + bindings::vaUnmapBuffer(self.display.handle(), self.image.buf); + // Safe since `self.image` represents a valid `VAImage`. + bindings::vaDestroyImage(self.display.handle(), self.image.image_id); + } + } +} diff --git a/vendor/cros-libva/src/lib.rs b/vendor/cros-libva/src/lib.rs new file mode 100644 index 0000000..c49dcc0 --- /dev/null +++ b/vendor/cros-libva/src/lib.rs @@ -0,0 +1,540 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// LOCAL PATCH: vendored verbatim, so its warnings are upstream's business and +// would otherwise drown out this workspace's own. +#![allow(warnings)] + +//! Implements a lightweight and safe interface over `libva`. +//! +//! The starting point to using this crate is to open a [`Display`], from which a [`Context`] and +//! [`Surface`]s can be allocated and used for doing actual work. + +mod bindings; +pub mod buffer; +mod config; +mod context; +mod display; +mod generic_value; +mod image; +mod picture; +mod surface; +mod usage_hint; + +pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_1 as VADRMPRIMESurfaceDescriptorObject; +pub use bindings::_VADRMPRIMESurfaceDescriptor__bindgen_ty_2 as VADRMPRIMESurfaceDescriptorLayer; +pub use bindings::*; +pub use buffer::*; +pub use config::*; +pub use context::*; +pub use display::*; +pub use generic_value::*; +pub use image::*; +pub use picture::*; +pub use surface::*; +pub use usage_hint::*; + +use std::num::NonZeroI32; + +/// A `VAStatus` that is guaranteed to not be `VA_STATUS_SUCCESS`. +#[derive(Debug)] +pub struct VaError(NonZeroI32); + +impl VaError { + /// Returns the `VAStatus` of this error. + pub fn va_status(&self) -> VAStatus { + self.0.get() as VAStatus + } +} + +impl std::fmt::Display for VaError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use std::ffi::CStr; + + // Safe because `vaErrorStr` will return a pointer to a statically allocated, null + // terminated C string. The pointer is guaranteed to never be null. + let err_str = unsafe { CStr::from_ptr(bindings::vaErrorStr(self.0.get())) } + .to_str() + .unwrap(); + f.write_str(err_str) + } +} + +impl std::error::Error for VaError {} + +/// Checks a VA return value and returns a `VaError` if it is not `VA_STATUS_SUCCESS`. +/// +/// This can be used on the return value of any VA function returning `VAStatus` in order to +/// convert it to a proper Rust `Result`. +fn va_check(code: VAStatus) -> Result<(), VaError> { + match code as u32 { + bindings::VA_STATUS_SUCCESS => Ok(()), + _ => Err(VaError(unsafe { NonZeroI32::new_unchecked(code) })), + } +} + +#[cfg(test)] +mod tests { + use std::io::Write; + use std::rc::Rc; + + use super::*; + + /// Returns a 32-bit CRC for the visible part of `image`, which must be in NV12 format. + fn crc_nv12_image(image: &Image) -> u32 { + let data = image.as_ref(); + let va_image = image.image(); + let offsets = &va_image.offsets; + let pitches = &va_image.pitches; + let width = va_image.width as usize; + let height = va_image.height as usize; + + // We only support NV12 images + assert_eq!(va_image.format.fourcc, u32::from_ne_bytes(*b"NV12")); + // Consistency check + assert_eq!(va_image.num_planes, 2); + + let mut hasher = crc32fast::Hasher::new(); + + let offset = offsets[0] as usize; + let pitch = pitches[0] as usize; + let y_plane = data[offset..(offset + pitch * height)] + .chunks(pitch) + .map(|line| &line[0..width]); + + let offset = offsets[1] as usize; + let pitch = pitches[1] as usize; + let uv_plane = data[offset..(offset + pitch * ((height + 1) / 2))] + .chunks(pitch) + .map(|line| &line[0..width]); + + for line in y_plane.chain(uv_plane) { + hasher.update(line); + } + + hasher.finalize() + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn libva_utils_mpeg2vldemo() { + // Adapted from + let display = Display::open().unwrap(); + + assert!(!display.query_vendor_string().unwrap().is_empty()); + let profiles = display.query_config_profiles().unwrap(); + assert!(!profiles.is_empty()); + + let profile = bindings::VAProfile::VAProfileMPEG2Main; + let entrypoints = display.query_config_entrypoints(profile).unwrap(); + assert!(!entrypoints.is_empty()); + assert!(entrypoints + .iter() + .any(|e| *e == bindings::VAEntrypoint::VAEntrypointVLD)); + + let format = bindings::VA_RT_FORMAT_YUV420; + let width = 16u32; + let height = 16u32; + + let mut attrs = vec![bindings::VAConfigAttrib { + type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat, + value: 0, + }]; + + let entrypoint = bindings::VAEntrypoint::VAEntrypointVLD; + display + .get_config_attributes(profile, entrypoint, &mut attrs) + .unwrap(); + assert!(attrs[0].value != bindings::VA_ATTRIB_NOT_SUPPORTED); + assert!(attrs[0].value & bindings::VA_RT_FORMAT_YUV420 != 0); + + let config = display.create_config(attrs, profile, entrypoint).unwrap(); + + let mut surfaces = display + .create_surfaces( + format, + None, + width, + height, + Some(UsageHint::USAGE_HINT_DECODER), + vec![()], + ) + .unwrap(); + let context = display + .create_context( + &config, + width, + ((height + 15) / 16) * 16, + Some(&surfaces), + true, + ) + .unwrap(); + + // The picture data is adapted from libva-utils at decode/mpeg2vldemo.cpp + // Data dump of a 16x16 MPEG2 video clip,it has one I frame + let mut mpeg2_clip: Vec = vec![ + 0x00, 0x00, 0x01, 0xb3, 0x01, 0x00, 0x10, 0x13, 0xff, 0xff, 0xe0, 0x18, 0x00, 0x00, + 0x01, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0xb8, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0x00, 0x00, 0x01, 0xb5, + 0x8f, 0xff, 0xf3, 0x41, 0x80, 0x00, 0x00, 0x01, 0x01, 0x13, 0xe1, 0x00, 0x15, 0x81, + 0x54, 0xe0, 0x2a, 0x05, 0x43, 0x00, 0x2d, 0x60, 0x18, 0x01, 0x4e, 0x82, 0xb9, 0x58, + 0xb1, 0x83, 0x49, 0xa4, 0xa0, 0x2e, 0x05, 0x80, 0x4b, 0x7a, 0x00, 0x01, 0x38, 0x20, + 0x80, 0xe8, 0x05, 0xff, 0x60, 0x18, 0xe0, 0x1d, 0x80, 0x98, 0x01, 0xf8, 0x06, 0x00, + 0x54, 0x02, 0xc0, 0x18, 0x14, 0x03, 0xb2, 0x92, 0x80, 0xc0, 0x18, 0x94, 0x42, 0x2c, + 0xb2, 0x11, 0x64, 0xa0, 0x12, 0x5e, 0x78, 0x03, 0x3c, 0x01, 0x80, 0x0e, 0x80, 0x18, + 0x80, 0x6b, 0xca, 0x4e, 0x01, 0x0f, 0xe4, 0x32, 0xc9, 0xbf, 0x01, 0x42, 0x69, 0x43, + 0x50, 0x4b, 0x01, 0xc9, 0x45, 0x80, 0x50, 0x01, 0x38, 0x65, 0xe8, 0x01, 0x03, 0xf3, + 0xc0, 0x76, 0x00, 0xe0, 0x03, 0x20, 0x28, 0x18, 0x01, 0xa9, 0x34, 0x04, 0xc5, 0xe0, + 0x0b, 0x0b, 0x04, 0x20, 0x06, 0xc0, 0x89, 0xff, 0x60, 0x12, 0x12, 0x8a, 0x2c, 0x34, + 0x11, 0xff, 0xf6, 0xe2, 0x40, 0xc0, 0x30, 0x1b, 0x7a, 0x01, 0xa9, 0x0d, 0x00, 0xac, + 0x64, + ]; + + let picture_coding_extension = + MPEG2PictureCodingExtension::new(0, 3, 0, 1, 0, 0, 0, 0, 0, 1, 1); + let pic_param = PictureParameterBufferMPEG2::new( + 16, + 16, + 0xffffffff, + 0xffffffff, + 1, + 0xffff, + &picture_coding_extension, + ); + + let pic_param = BufferType::PictureParameter(PictureParameter::MPEG2(pic_param)); + + let iq_matrix = IQMatrixBufferMPEG2::new( + 1, + 1, + 0, + 0, + [ + 8, 16, 16, 19, 16, 19, 22, 22, 22, 22, 22, 22, 26, 24, 26, 27, 27, 27, 26, 26, 26, + 26, 27, 27, 27, 29, 29, 29, 34, 34, 34, 29, 29, 29, 27, 27, 29, 29, 32, 32, 34, 34, + 37, 38, 37, 35, 35, 34, 35, 38, 38, 40, 40, 40, 48, 48, 46, 46, 56, 56, 58, 69, 69, + 83, + ], + [ + 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, + ], + [0; 64], + [0; 64], + ); + + let iq_matrix = BufferType::IQMatrix(IQMatrix::MPEG2(iq_matrix)); + + let slice_param = SliceParameterBufferMPEG2::new(150, 0, 0, 38, 0, 0, 2, 0); + + let slice_param = BufferType::SliceParameter(SliceParameter::MPEG2(slice_param)); + + let test_data_offset = 47; + let slice_data = BufferType::SliceData(mpeg2_clip.drain(test_data_offset..).collect()); + + let buffers = vec![ + context.create_buffer(pic_param).unwrap(), + context.create_buffer(slice_param).unwrap(), + context.create_buffer(iq_matrix).unwrap(), + context.create_buffer(slice_data).unwrap(), + ]; + + let mut picture = Picture::new(0, Rc::clone(&context), surfaces.remove(0)); + for buffer in buffers { + picture.add_buffer(buffer); + } + + // Actual client code can just chain the calls. + let picture = picture.begin().unwrap(); + let picture = picture.render().unwrap(); + let picture = picture.end().unwrap(); + let picture = picture.sync().map_err(|(e, _)| e).unwrap(); + + // Test whether we can map the resulting surface to obtain the raw yuv + // data + let image_fmts = display.query_image_formats().unwrap(); + let image_fmt = image_fmts + .into_iter() + .find(|f| f.fourcc == bindings::VA_FOURCC_NV12) + .expect("No valid VAImageFormat found for NV12"); + + let resolution = (width, height); + let image = picture + .create_image(image_fmt, resolution, resolution) + .unwrap(); + + assert_eq!(crc_nv12_image(&image), 0xa5713e52); + } + + #[test] + // Ignore this test by default as it requires libva-compatible hardware. + #[ignore] + fn enc_h264_demo() { + // Based on `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! vaapih264enc ! filesink location=frame.h264` + // Frame created using `gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,width=64,height=64,format=NV12 ! filesink location=src/test_frame.nv12` + let raw_frame_nv12 = include_bytes!("test_frame.nv12"); + + let display = Display::open().unwrap(); + + let format = bindings::VA_RT_FORMAT_YUV420; + let entrypoint = bindings::VAEntrypoint::VAEntrypointEncSliceLP; + let profile = bindings::VAProfile::VAProfileH264ConstrainedBaseline; + let width = 64u32; + let height = 64u32; + + let mut attrs = vec![bindings::VAConfigAttrib { + type_: bindings::VAConfigAttribType::VAConfigAttribRTFormat, + value: 0, + }]; + + display + .get_config_attributes(profile, entrypoint, &mut attrs) + .unwrap(); + + let config = display.create_config(attrs, profile, entrypoint).unwrap(); + + let mut surfaces = display + .create_surfaces( + format, + None, + width, + height, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .unwrap(); + + let context = display + .create_context(&config, width, height, Some(&surfaces), true) + .unwrap(); + + let seq_fields = H264EncSeqFields::new( + 1, // 4:2:0 + 1, // Only frames + 0, 0, 0, 1, 0, 2, 0, + ); + + let image_fmts = display.query_image_formats().unwrap(); + let image_fmt = image_fmts + .into_iter() + .find(|f| f.fourcc == bindings::VA_FOURCC_NV12) + .expect("No valid VAImageFormat found for NV12"); + + let surface = surfaces.pop().unwrap(); + let surface_id = surface.id(); + + let coded_buffer = context.create_enc_coded(raw_frame_nv12.len()).unwrap(); + + let mut image = + Image::create_from(&surface, image_fmt, (width, height), (width, height)).unwrap(); + + let va_image = *image.image(); + let dest = image.as_mut(); + let data = &raw_frame_nv12[..]; + let width = width as usize; + let height = height as usize; + + let mut src = data; + let mut dst = &mut dest[va_image.offsets[0] as usize..]; + + // Copy luma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[0] as usize..]; + src = &src[width..]; + } + + // Advance to the offset of the chroma plane + let mut src = &data[width * height..]; + let mut dst = &mut dest[va_image.offsets[1] as usize..]; + + let height = height / 2; + + // Copy chroma + for _ in 0..height { + dst[..width].copy_from_slice(&src[..width]); + dst = &mut dst[va_image.pitches[1] as usize..]; + src = &src[width..]; + } + drop(image); + + let sps = BufferType::EncSequenceParameter(EncSequenceParameter::H264( + EncSequenceParameterBufferH264::new( + 0, + 10, + 10, + 30, + 1, + 0, + 1, + (width / 16) as u16, // width / 16 + (height / 16) as u16, // height / 16 + &seq_fields, + 0, + 0, + 0, + 0, + 0, + [0; 256], + None, + Some(H264VuiFields::new(1, 1, 0, 0, 0, 1, 0, 0)), + 255, + 1, + 1, + 1, + 60, + ), + )); + + let sps = context.create_buffer(sps).unwrap(); + + let ref_frames: [PictureH264; 16] = (0..16) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let pps = BufferType::EncPictureParameter(EncPictureParameter::H264( + EncPictureParameterBufferH264::new( + PictureH264::new(surface_id, 0, 0, 0, 0), + ref_frames, + coded_buffer.id(), + 0, + 0, + 0, + 0, + 26, + 0, + 0, + 0, + 0, + &H264EncPicFields::new(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0), + ), + )); + + let pps = context.create_buffer(pps).unwrap(); + + let ref_pic_list_0: [PictureH264; 32] = (0..32) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let ref_pic_list_1: [PictureH264; 32] = (0..32) + .map(|_| { + PictureH264::new( + bindings::VA_INVALID_ID, + 0, + bindings::VA_INVALID_SURFACE, + 0, + 0, + ) + }) + .collect::>() + .try_into() + .unwrap_or_else(|_| { + panic!(); + }); + + let slice = BufferType::EncSliceParameter(EncSliceParameter::H264( + EncSliceParameterBufferH264::new( + 0, + ((width / 16) * (height / 16)) as u32, + bindings::VA_INVALID_ID, + 2, // I + 0, + 1, + 0, + 0, + [0, 0], + 1, + 0, + 0, + 0, + ref_pic_list_0, + ref_pic_list_1, + 0, + 0, + 0, + [0; 32], + [0; 32], + 0, + [[0; 2]; 32], + [[0; 2]; 32], + 0, + [0; 32], + [0; 32], + 0, + [[0; 2]; 32], + [[0; 2]; 32], + 0, + 0, + 0, + 2, + 2, + ), + )); + + let slice = context.create_buffer(slice).unwrap(); + + let mut picture = Picture::new(0, Rc::clone(&context), surface); + picture.add_buffer(pps); + picture.add_buffer(sps); + picture.add_buffer(slice); + + let picture = picture.begin().unwrap(); + let picture = picture.render().unwrap(); + let picture = picture.end().unwrap(); + let _ = picture.sync().map_err(|(e, _)| e).unwrap(); + + let coded_buf = MappedCodedBuffer::new(&coded_buffer).unwrap(); + assert_ne!(coded_buf.segments().len(), 0); + + for segment in coded_buf.iter() { + assert_ne!(segment.buf.len(), 0); + } + + const WRITE_TO_FILE: bool = false; + if WRITE_TO_FILE { + let raw_sps_bitstream: Vec = vec![ + 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x0a, 0xab, 0x42, 0x12, 0x7f, 0xe0, 0x00, + 0x20, 0x00, 0x22, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x79, 0x28, + ]; + + let raw_pps_bitstream: Vec = vec![0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x3c, 0x80]; + + let mut raw_file = std::fs::File::create("libva_utils_enc_h264_demo.h264").unwrap(); + raw_file.write_all(&raw_sps_bitstream).unwrap(); + raw_file.write_all(&raw_pps_bitstream).unwrap(); + + for segment in coded_buf.segments() { + raw_file.write_all(segment.buf).unwrap(); + } + + raw_file.flush().unwrap(); + } + } +} diff --git a/vendor/cros-libva/src/picture.rs b/vendor/cros-libva/src/picture.rs new file mode 100644 index 0000000..ea9a8d9 --- /dev/null +++ b/vendor/cros-libva/src/picture.rs @@ -0,0 +1,307 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::borrow::Borrow; +use std::marker::PhantomData; +use std::rc::Rc; + +use crate::bindings; +use crate::buffer::Buffer; +use crate::context::Context; +use crate::surface::Surface; +use crate::va_check; +use crate::Image; +use crate::SurfaceMemoryDescriptor; +use crate::VaError; + +// Use the sealed trait pattern to make sure that new states are not created in caller code. More +// information about the sealed trait pattern can be found at +// +mod private { + pub trait Sealed {} +} + +/// A `Picture` will only have valid YUV data after a sequence of operations are performed in a +/// particular order. This order correspond to the following VA-API calls: `vaBeginPicture`, +/// `vaRenderPicture`, `vaEndPicture` and `vaSyncSurface`. This trait enforces this ordering by +/// implementing the Typestate pattern to constrain what operations are available in what particular +/// states. +/// +/// The states for the state machine are: +/// +/// * PictureNew -> PictureBegin +/// * PictureBegin -> PictureRender +/// * PictureRender ->PictureEnd +/// * PictureEnd -> PictureSync +/// +/// Where the surface can be reclaimed in both `PictureNew` and `PictureSync`, as either no +/// operation took place (as in `PictureNew`), or it is guaranteed that the operation has already +/// completed (as in `PictureSync`). +/// +/// More information about the Typestate pattern can be found at +/// +pub trait PictureState: private::Sealed {} + +/// Represents a `Picture` that has just been created. +pub enum PictureNew {} +impl PictureState for PictureNew {} +impl private::Sealed for PictureNew {} + +/// Represents a `Picture` after `vaBeginPicture` has been called. +pub enum PictureBegin {} +impl PictureState for PictureBegin {} +impl private::Sealed for PictureBegin {} + +/// Represents a `Picture` after `vaRenderPicture` has been called. +pub enum PictureRender {} +impl PictureState for PictureRender {} +impl private::Sealed for PictureRender {} + +/// Represents a `Picture` after `vaEndPicture` has been called. +pub enum PictureEnd {} +impl PictureState for PictureEnd {} +impl private::Sealed for PictureEnd {} + +/// Represents a `Picture` after `vaSyncSurface` has been called on the underlying surface. +pub enum PictureSync {} +impl PictureState for PictureSync {} +impl private::Sealed for PictureSync {} + +/// Represents a state where one can reclaim the underlying `Surface` for this `Picture`. This is +/// true when either no decoding has been initiated or, alternatively, when the decoding operation +/// has completed for the underlying `vaSurface` +pub trait PictureReclaimableSurface: PictureState + private::Sealed {} +impl PictureReclaimableSurface for PictureNew {} +impl PictureReclaimableSurface for PictureSync {} + +/// Inner type for [`Picture`], that is, the part that exists in all states. +struct PictureInner { + /// Timestamp of the picture. + timestamp: u64, + /// A context associated with this picture. + context: Rc, + /// Contains the buffers used to decode the data. + buffers: Vec, + /// Contains the actual decoded data. Note that the surface may be shared in + /// interlaced decoding. + surface: Rc, +} + +/// A `Surface` that is being rendered into. +/// +/// This struct abstracts the decoding flow using `vaBeginPicture`, `vaRenderPicture`, +/// `vaEndPicture` and `vaSyncSurface` in a type-safe way. +/// +/// The surface will have valid picture data after all the stages of decoding are called. +/// +/// The `T` generic parameter must be `Borrow>`, i.e. it can be [`Surface`] directly or +/// some other type that contains one. +/// +/// No constraint on `T` is specified in this declaration because specifying it here would force us +/// to add the generic argument of [`Surface`] to this type as well, turning it into a type with 3 +/// generics, one of which is redundant. To avoid that we leave `T` unconstrained and instead +/// constrain the methods that require to act on it as a [`Surface`]. +pub struct Picture { + inner: Box>, + phantom: std::marker::PhantomData, +} + +impl Picture { + /// Creates a new Picture with a given `timestamp`. `surface` is the underlying surface that + /// libva will render to. + pub fn new(timestamp: u64, context: Rc, surface: T) -> Self + where + T: Borrow>, + { + Self { + inner: Box::new(PictureInner { + timestamp, + context, + buffers: Default::default(), + surface: Rc::new(surface), + }), + + phantom: PhantomData, + } + } + + /// Creates a new Picture with a given `timestamp` to identify it, + /// reusing the Surface from `picture`. This is useful for interlaced + /// decoding as one can render both fields to the same underlying surface. + pub fn new_from_same_surface(timestamp: u64, picture: &Picture) -> Self { + let context = Rc::clone(&picture.inner.context); + Picture { + inner: Box::new(PictureInner { + timestamp, + context, + buffers: Default::default(), + surface: Rc::clone(&picture.inner.surface), + }), + + phantom: PhantomData, + } + } + + /// Add `buffer` to the picture. + pub fn add_buffer(&mut self, buffer: Buffer) { + self.inner.buffers.push(buffer); + } + + /// Wrapper around `vaBeginPicture`. + pub fn begin(self) -> Result, VaError> + where + T: Borrow>, + { + // Safe because `self.inner.context` represents a valid VAContext and + // `self.inner.surface` represents a valid VASurface. + let res = va_check(unsafe { + bindings::vaBeginPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + self.surface().id(), + ) + }); + + res.map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Wrapper around `vaRenderPicture`. + pub fn render(self) -> Result, VaError> { + // Safe because `self.inner.context` represents a valid `VAContext` and `self.inner.surface` + // represents a valid `VASurface`. `buffers` point to a Rust struct and the vector length is + // passed to the C function, so it is impossible to write past the end of the vector's + // storage by mistake. + va_check(unsafe { + bindings::vaRenderPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + Buffer::as_id_vec(&self.inner.buffers).as_mut_ptr(), + self.inner.buffers.len() as i32, + ) + }) + .map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Wrapper around `vaEndPicture`. + pub fn end(self) -> Result, VaError> { + // Safe because `self.inner.context` represents a valid `VAContext`. + va_check(unsafe { + bindings::vaEndPicture( + self.inner.context.display().handle(), + self.inner.context.id(), + ) + }) + .map(|()| Picture { + inner: self.inner, + phantom: PhantomData, + }) + } +} + +impl Picture { + /// Syncs the picture, ensuring that all pending operations are complete when this call returns. + pub fn sync( + self, + ) -> Result, (VaError, Self)> + where + T: Borrow>, + { + let res = self.surface().sync(); + + match res { + Ok(()) => Ok(Picture { + inner: self.inner, + phantom: PhantomData, + }), + Err(e) => Err((e, self)), + } + } +} + +impl Picture { + /// Returns the timestamp of this picture. + pub fn timestamp(&self) -> u64 { + self.inner.timestamp + } + + /// Returns a reference to the underlying `Surface`. + /// + /// If you are interested in obtaining the container of the `Surface`, use `as_ref()` instead. + /// This is a convenience method to avoid having to call `borrow()` every time the surface is + /// needed. + pub fn surface(&self) -> &Surface + where + T: Borrow>, + { + self.as_ref().borrow() + } +} + +impl Picture { + /// Reclaim ownership of the Surface this picture has been created from, consuming the picture + /// in the process. Useful if the Surface is part of a pool. + /// + /// This will fail and return the passed object if there are more than one reference to the + /// underlying surface. + pub fn take_surface(self) -> Result { + let inner = self.inner; + match Rc::try_unwrap(inner.surface) { + Ok(surface) => Ok(surface), + Err(surface) => Err(Self { + inner: Box::new(PictureInner { + surface, + context: inner.context, + buffers: inner.buffers, + timestamp: inner.timestamp, + }), + phantom: PhantomData, + }), + } + } + + /// Create a new derived image from this `Picture` using `vaDeriveImage`. + /// + /// Derived images are a direct view (i.e. without any copy) on the buffer content of the + /// `Picture`. On the other hand, not all `Pictures` can be derived. + pub fn derive_image<'a, D: SurfaceMemoryDescriptor + 'a>( + &'a self, + visible_rect: (u32, u32), + ) -> Result + where + T: Borrow>, + { + Image::derive_from(self.surface(), visible_rect) + } + + /// Create new image from the `Picture` using `vaCreateImage` and `vaGetImage`. + /// + /// The image will contain a copy of the `Picture` in the desired `format` and `coded_resolution`. + pub fn create_image<'a, D: SurfaceMemoryDescriptor + 'a>( + &'a self, + format: bindings::VAImageFormat, + coded_resolution: (u32, u32), + visible_rect: (u32, u32), + ) -> Result + where + T: Borrow>, + { + Image::create_from(self.surface(), format, coded_resolution, visible_rect) + } +} + +impl AsRef for Picture { + fn as_ref(&self) -> &T { + (*self.inner.surface).borrow() + } +} diff --git a/vendor/cros-libva/src/surface.rs b/vendor/cros-libva/src/surface.rs new file mode 100644 index 0000000..3597409 --- /dev/null +++ b/vendor/cros-libva/src/surface.rs @@ -0,0 +1,452 @@ +// Copyright 2022 The ChromiumOS Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use std::any::Any; +use std::os::fd::FromRawFd; +use std::os::fd::OwnedFd; +use std::os::raw::c_void; +use std::rc::Rc; + +use crate::bindings; +use crate::display::Display; +use crate::va_check; +use crate::UsageHint; +use crate::VASurfaceID; +use crate::VaError; + +/// Trait describing a memory backing for surfaces. +/// +/// Using external memory for backing a VA surface is done in two steps: +/// +/// 1. Build the descriptor specific to the memory type we want to use, +/// 2. Mention this descriptor as an attribute to be passed to `vaDeriveImage`. +/// +/// This trait allows to do that in a as-safe-as-possible way, by adding the required attributes +/// and returning a heap-allocated object containing the data pointed to by the attributes. That +/// way, the caller can keep that object alive until `vaCreateSurfaces` has returned. +pub trait SurfaceMemoryDescriptor { + /// Add the required attributes to `attr` in order to attach the memory of this descriptor to + /// the surface when it is created. + /// + /// The returned object, if any, is the descriptor pointed to by the attributes. The caller + /// must keep it around and unmoved until `vaCreateSurfaces` has returned. + fn add_attrs(&mut self, attrs: &mut Vec) -> Option>; +} + +/// VA memory types, aka `VA_SURFACE_ATTRIB_MEM_TYPE_*`. +#[repr(u32)] +pub enum MemoryType { + Va = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_VA, + V4L2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_V4L2, + UserPtr = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_USER_PTR, + DrmPrime2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, +} + +/// Used when we want the VA driver to allocate surface memory for us. In this case we don't need +/// to add any specific attribute for surface creation. +impl SurfaceMemoryDescriptor for () { + fn add_attrs(&mut self, _: &mut Vec) -> Option> { + None + } +} + +/// Sealed trait pattern to avoid reimplementation of our local traits. +mod private { + pub trait Sealed {} +} + +/// Trait for types that can be used as a `VASurfaceAttribExternalBufferDescriptor`. +pub trait SurfaceExternalDescriptor: private::Sealed {} +impl private::Sealed for bindings::VASurfaceAttribExternalBuffers {} +impl SurfaceExternalDescriptor for bindings::VASurfaceAttribExternalBuffers {} +impl private::Sealed for bindings::VADRMPRIMESurfaceDescriptor {} +impl SurfaceExternalDescriptor for bindings::VADRMPRIMESurfaceDescriptor {} + +/// Trait allowing to import an external memory source to use with a surface by setting the +/// `VASurfaceAttribMemoryType` and `VASurfaceAttribExternalBuffers` attributes. +pub trait ExternalBufferDescriptor { + /// Memory type to set for `VASurfaceAttribMemoryType`. + const MEMORY_TYPE: MemoryType; + /// Type of the descriptor to be set with `VASurfaceAttribExternalBuffers`. + type DescriptorAttribute: SurfaceExternalDescriptor; + + /// Returns the `Self::DescriptorAttribute` instance allowing this memory to be imported + /// into VAAPI. + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute; +} + +impl SurfaceMemoryDescriptor for T +where + T: ExternalBufferDescriptor, + ::DescriptorAttribute: 'static, +{ + fn add_attrs(&mut self, attrs: &mut Vec) -> Option> { + let mut desc = Box::new(self.va_surface_attribute()); + + attrs.push(bindings::VASurfaceAttrib::new_memory_type( + Self::MEMORY_TYPE, + )); + attrs.push(bindings::VASurfaceAttrib::new_buffer_descriptor( + desc.as_mut(), + )); + + Some(desc) + } +} + +/// Decode error type aka `VADecodeErrorType` +#[repr(u32)] +#[derive(Debug)] +pub enum DecodeErrorType { + SliceMissing = bindings::VADecodeErrorType::VADecodeSliceMissing, + MBError = bindings::VADecodeErrorType::VADecodeMBError, + #[cfg(libva_1_20_or_higher)] + Reset = bindings::VADecodeErrorType::VADecodeReset, +} + +/// Decode error details extracted from `VASurfaceDecodeMBErrors`, result of vaQuerySurfaceError. +#[derive(Debug)] +pub struct SurfaceDecodeMBError { + /// Start mb address with errors + pub start_mb: u32, + + /// End mb address with errors + pub end_mb: u32, + + pub decode_error_type: DecodeErrorType, + + /// Number of mbs with errors + pub num_mb: u32, +} + +/// An owned VA surface that is tied to a particular `Display`. +pub struct Surface { + display: Rc, + id: bindings::VASurfaceID, + descriptor: D, + width: u32, + height: u32, +} + +impl From for bindings::VAGenericValue { + fn from(i: i32) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypeInteger, + value: bindings::_VAGenericValue__bindgen_ty_1 { i }, + } + } +} + +impl From for bindings::VAGenericValue { + fn from(f: f32) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypeFloat, + value: bindings::_VAGenericValue__bindgen_ty_1 { f }, + } + } +} + +impl From<*mut c_void> for bindings::VAGenericValue { + fn from(p: *mut c_void) -> Self { + Self { + type_: bindings::VAGenericValueType::VAGenericValueTypePointer, + value: bindings::_VAGenericValue__bindgen_ty_1 { p }, + } + } +} + +/// Helpers to build valid `VASurfaceAttrib`s. +impl bindings::VASurfaceAttrib { + pub fn new_pixel_format(fourcc: u32) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribPixelFormat, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(fourcc as i32), + } + } + + pub fn new_usage_hint(usage_hint: UsageHint) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribUsageHint, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(usage_hint.bits() as i32), + } + } + + pub fn new_memory_type(mem_type: MemoryType) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribMemoryType, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(mem_type as i32), + } + } + + pub fn new_buffer_descriptor(desc: &mut T) -> Self { + Self { + type_: bindings::VASurfaceAttribType::VASurfaceAttribExternalBufferDescriptor, + flags: bindings::VA_SURFACE_ATTRIB_SETTABLE, + value: bindings::VAGenericValue::from(desc as *mut _ as *mut c_void), + } + } +} + +impl Surface { + /// Create `Surfaces` by wrapping around a `vaCreateSurfaces` call. This is just a helper for + /// [`Display::create_surfaces`]. + pub(crate) fn new( + display: Rc, + rt_format: u32, + va_fourcc: Option, + width: u32, + height: u32, + usage_hint: Option, + descriptors: Vec, + ) -> Result, VaError> { + let mut surfaces = vec![]; + + for mut descriptor in descriptors { + let mut attrs = vec![]; + + if let Some(usage_hint) = usage_hint { + attrs.push(bindings::VASurfaceAttrib::new_usage_hint(usage_hint)); + } + + if let Some(fourcc) = va_fourcc { + attrs.push(bindings::VASurfaceAttrib::new_pixel_format(fourcc)); + } + + // Just to be kept alive until we call `vaCreateSurfaces`... + let mut _va_desc = descriptor.add_attrs(&mut attrs); + let mut surface_id: VASurfaceID = 0; + + // Safe because `self` represents a valid VADisplay. The `surface` and `attrs` vectors are + // properly initialized and valid sizes are passed to the C function, so it is impossible to + // write past the end of their storage by mistake. + // + // Also all the pointers in `attrs` are pointing to valid objects that haven't been + // moved or destroyed. + match va_check(unsafe { + bindings::vaCreateSurfaces( + display.handle(), + rt_format, + width, + height, + &mut surface_id, + 1, + attrs.as_mut_ptr(), + attrs.len() as u32, + ) + }) { + Ok(()) => surfaces.push(Self { + display: Rc::clone(&display), + id: surface_id, + descriptor, + width, + height, + }), + Err(e) => return Err(e), + } + } + + Ok(surfaces) + } + + pub(crate) fn display(&self) -> &Rc { + &self.display + } + + /// Wrapper around `vaSyncSurface` that blocks until all pending operations on the render + /// target have been completed. + /// + /// Upon return it + /// is safe to use the render target for a different picture. + pub fn sync(&self) -> Result<(), VaError> { + // Safe because `self` represents a valid VASurface. + va_check(unsafe { bindings::vaSyncSurface(self.display.handle(), self.id) }) + } + + /// Convenience function to return a VASurfaceID vector. Useful to interface with the C API + /// where a surface array might be needed. + pub fn as_id_vec(surfaces: &[Self]) -> Vec { + surfaces.iter().map(|surface| surface.id).collect() + } + + /// Wrapper over `vaQuerySurfaceStatus` to find out any pending ops on the render target. + pub fn query_status(&self) -> Result { + let mut status: bindings::VASurfaceStatus::Type = 0; + // Safe because `self` represents a valid VASurface. + va_check(unsafe { + bindings::vaQuerySurfaceStatus(self.display.handle(), self.id, &mut status) + })?; + + Ok(status) + } + + pub fn query_error(&self) -> Result, VaError> { + let mut raw: *const bindings::VASurfaceDecodeMBErrors = std::ptr::null(); + + // Safe because `self` represents a valid VASurface. + va_check(unsafe { + bindings::vaQuerySurfaceError( + self.display.handle(), + self.id, + bindings::VA_STATUS_ERROR_DECODING_ERROR as i32, + (&mut raw) as *mut _ as *mut _, + ) + })?; + + let mut errors = vec![]; + + while !raw.is_null() { + // Safe because raw is a valid pointer + let error = unsafe { *raw }; + if error.status == -1 { + break; + } + + let type_ = match error.decode_error_type { + bindings::VADecodeErrorType::VADecodeSliceMissing => DecodeErrorType::SliceMissing, + bindings::VADecodeErrorType::VADecodeMBError => DecodeErrorType::MBError, + #[cfg(libva_1_20_or_higher)] + bindings::VADecodeErrorType::VADecodeReset => DecodeErrorType::Reset, + _ => { + log::warn!( + "Unrecognized `decode_error_type` value ({})", + error.decode_error_type + ); + + // Safe because status != -1 + raw = unsafe { raw.offset(1) }; + continue; + } + }; + + errors.push(SurfaceDecodeMBError { + start_mb: error.start_mb, + end_mb: error.end_mb, + decode_error_type: type_, + num_mb: error.num_mb, + }); + + // Safe because status != -1 + raw = unsafe { raw.offset(1) }; + } + + Ok(errors) + } + + /// Returns the ID of this surface. + pub fn id(&self) -> bindings::VASurfaceID { + self.id + } + + /// Returns the dimensions of this surface. + pub fn size(&self) -> (u32, u32) { + (self.width, self.height) + } + + /// Returns a PRIME descriptor for this surface. + pub fn export_prime(&self) -> Result { + let mut desc: bindings::VADRMPRIMESurfaceDescriptor = Default::default(); + + va_check(unsafe { + bindings::vaExportSurfaceHandle( + self.display.handle(), + self.id(), + bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + bindings::VA_EXPORT_SURFACE_READ_ONLY | bindings::VA_EXPORT_SURFACE_COMPOSED_LAYERS, + &mut desc as *mut _ as *mut c_void, + ) + })?; + + // We do not use a `From` implementation as this would allow + // to create "safe" descriptors outside of this method and thus from made up values, + // violating the safety guarantee that our FDs are legit. + + let objects = (0..desc.num_objects as usize) + // Make sure we don't go out of bounds. + .take(4) + .map(|i| desc.objects[i]) + .map(|o| { + DrmPrimeSurfaceDescriptorObject { + // Safe because `o.fd` is a valid file descriptor returned by + // `vaExportSurfaceHandle`. + fd: unsafe { OwnedFd::from_raw_fd(o.fd) }, + size: o.size, + drm_format_modifier: o.drm_format_modifier, + } + }) + .collect(); + + let layers = (0..desc.num_layers as usize) + // Make sure we don't go out of bounds. + .take(4) + .map(|i| desc.layers[i]) + .map(|l| DrmPrimeSurfaceDescriptorLayer { + drm_format: l.drm_format, + num_planes: l.num_planes, + object_index: [ + l.object_index[0] as u8, + l.object_index[1] as u8, + l.object_index[2] as u8, + l.object_index[3] as u8, + ], + offset: l.offset, + pitch: l.pitch, + }) + .collect(); + + Ok(DrmPrimeSurfaceDescriptor { + fourcc: desc.fourcc, + width: desc.width, + height: desc.height, + objects, + layers, + }) + } +} + +impl AsRef for Surface { + fn as_ref(&self) -> &D { + &self.descriptor + } +} + +impl AsMut for Surface { + fn as_mut(&mut self) -> &mut D { + &mut self.descriptor + } +} + +impl Drop for Surface { + fn drop(&mut self) { + // Safe because `self` represents a valid VASurface. + unsafe { bindings::vaDestroySurfaces(self.display.handle(), &mut self.id, 1) }; + } +} + +/// Safe wrapper for the `object` member of `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptorObject { + pub fd: OwnedFd, + pub size: u32, + pub drm_format_modifier: u64, +} + +/// Safe wrapper for the `layers` member of `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptorLayer { + pub drm_format: u32, + pub num_planes: u32, + pub object_index: [u8; 4], + pub offset: [u32; 4], + pub pitch: [u32; 4], +} + +/// Safe wrapper around `VADRMPRIMESurfaceDescriptor`. +pub struct DrmPrimeSurfaceDescriptor { + pub fourcc: u32, + pub width: u32, + pub height: u32, + pub objects: Vec, + pub layers: Vec, +} diff --git a/vendor/cros-libva/src/test_frame.nv12 b/vendor/cros-libva/src/test_frame.nv12 new file mode 100644 index 0000000000000000000000000000000000000000..c4e20156136e29109852b74653a43055505f6a57 GIT binary patch literal 6144 zcmaF;8VWAKz$zG+2m@I#5C{XBZ~)Ujsvibm!8aOyFaS$Fqv;0*;Mr$1|G)q&`;6uv z7=UG;(fk7guQC8K2r7jO<29Z%~<}m=$aIZ3og&>NY(!`pxtK-h5Q?xOwKSKEo?1@}$~- zTzcQCGNtTnr_2pqXG+9v>bv zUF51r)&HdYMD3-#r}DkVHGLEI$?qgpfAqoF`^S`3PpWPdj;ooRexFqRv-=Bom@LU& z=&++?_fl&IAyV~gi#VH2R(o+v>HMM04Hv35lB)lN)+F^QlG8U&Nzr76!Rwf|>_bl)punS3U=jo_6M(=xNi!t~JarEOCq0k)0D&L!U~p7F1dN8? zX!;q=KcEm8S>*?;9NbY3D+ytx<