diff --git a/Cargo.lock b/Cargo.lock index 9201bbed1e2..7aa7d9729c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5233,15 +5233,14 @@ dependencies = [ [[package]] name = "moq-vaapi" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b175d0632ae90ceaa88ff0c2a6ad949ae227f39d35ea1dd5019beff278d967f" +version = "0.2.1" dependencies = [ "anyhow", "bitflags 2.13.2", - "libloading 0.8.9", - "log", - "thiserror 1.0.69", + "libloading 0.9.0", + "thiserror 2.0.21", + "tracing", + "workspace-hack", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1ee715bc17f..970cb4f8a12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ default-members = [ "rs/moq-transcode", "rs/moq-uring", "rs/moq-v4l", + "rs/moq-vaapi", "rs/moq-video", "rs/moq-webrtc", "rs/qmux", @@ -172,9 +173,9 @@ moq-uring = { version = "0.0.12", path = "rs/moq-uring", default-features = fals # `capture` and `v4l2` need no libclang or kernel headers. Linux only; an empty # stub elsewhere. moq-v4l = { version = "0.1.0", path = "rs/moq-v4l" } -# Standalone crate (moq-dev/vaapi); vendored from cros-libva + cros-codecs. +# In-tree fork of cros-libva + cros-codecs with the libva bindings checked in. # dlopen's libva at runtime (no libva-dev at build, no NEEDED libva in the binary). -moq-vaapi = "0.2.0" +moq-vaapi = { version = "0.2.1", path = "rs/moq-vaapi" } # `default-features = false` is here for `capture` (V4L2, libclang), which the # cross-compiled Python, Swift, Kotlin, and Go builds have no use for: adding # `features = ["capture"]` to a consumer that ships in those bindings pulls the diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index c6da36759f1..86c2c9c425e 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -34,6 +34,7 @@ missing required CPU feature before starting transport cryptography. | [moq-archive](https://docs.rs/moq-archive) | [Record and serve broadcasts](/concept/archives) on any `object_store` backend. | | [moq-video](/lib/rs/moq-video) | Native capture, hardware encode/decode (Apple, Windows, NVIDIA, VAAPI, V4L2, Android), and GPU rendering. | | [moq-v4l](https://docs.rs/moq-v4l) | Safe Video4Linux 2 bindings. | +| [moq-vaapi](https://docs.rs/moq-vaapi) | VA-API H.264 and H.265 hardware encode and decode, loading libva at runtime. | | [moq-audio](/lib/rs/moq-audio) | Microphone and speaker, Opus/PCM/AAC codecs, echo cancellation. | | [moq-transcode](https://docs.rs/moq-transcode) | Just-in-time rendition ladders, GPU-resident on NVIDIA. | | [moq-auth](/lib/rs/moq-auth) | Relay authorization: JWT signing and verification, and the auth server contract. | diff --git a/quest/m1/README.md b/quest/m1/README.md index 897602cde36..f29543e988c 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -54,7 +54,6 @@ moves what remains of them once their claims merge. - [Push-to-talk's press-to-audible latency fits a budget on the defaults](/quest/m1/push-to-talk-latency.md) - press to audible on the browser defaults, excluding device output, stays under a kixtop-measured budget that `just test push-to-talk` enforces - [TS fidelity and recovery](/quest/m1/ts-reliability/README.md) - both modes have explicit profiles, automated validation, loss tests, and a dedicated guide - [MoQ on rind](/quest/m1/rind/README.md) - every MoQ crate takes its crypto from rind, a pure-Rust graviola fork, so no build compiles C crypto -- [VA-API encode is correct on radeonsi](/quest/m1/vaapi-radeonsi.md) - AMD's VA-API H.264 encode decodes, once moq takes moq-vaapi 0.2.1 - [Tests run on a mocked clock](/quest/m1/mock-clock-tests/README.md) - about 300 tests stop proving nothing happened by waiting, sleeping to settle, or asserting on elapsed time - [moq-mux reads only the base layer's H.265 SPS](/quest/m1/h265-base-layer-sps.md) - a layered MV-HEVC or SHVC stream imports as its base layer instead of misreading an enhancement-layer SPS, which still reaches the track - [A cancelled dispatch lane stops its phase promptly](/quest/m1/dispatch-cancel-race.md) - a TERM landing just before a lane forks its phase's command still stops that command, instead of waiting out the phase diff --git a/quest/m1/vaapi-radeonsi.md b/quest/m1/vaapi-radeonsi.md deleted file mode 100644 index 7fac16a0bb0..00000000000 --- a/quest/m1/vaapi-radeonsi.md +++ /dev/null @@ -1,39 +0,0 @@ -# [S] VA-API encode is correct on radeonsi - -## Goal - -On an AMD RX 9070 (radeonsi), moq-video's VA-API H.264 encoder produces a -stream that ffmpeg decodes, its VPP NV12 conversion matches the space it -labels, and its rate control stays near the target bitrate. The VA-API -tests in `rs/moq-video/src/encode/backend/vaapi.rs`, ignored ones included, -pass on that card with `MOQ_VAAPI_DEVICE` naming its node. - -## Plan - -The causes were in moq-vaapi and are fixed in -[moq-dev/vaapi#13](https://github.com/moq-dev/vaapi/pull/13). With it patched -in, all 19 of moq-video's VA-API tests pass on the RX 9070 (`renderD129`, -Mesa 26.2.5); on moq-vaapi 0.2.0, 7 fail. That PR's body has the evidence. - -- H.264 bytes: radeonsi writes the packed SPS and PPS, and the slice's NAL - header, only from a packed slice header, which moq-vaapi did not send. -- Bitrate: moq-vaapi's QP ceiling of 36 set a smallest picture on both iHD - and radeonsi; it is now 51. -- Chroma: not an offset. Mesa's VPP reads the BT.601 standard as SMPTE 170M - primaries and gamut-maps; moq-vaapi now names each side explicitly on Mesa. - -Decided 2026-11-07 (maintainer, /quest-unblock): an agent merged #13 and -published it as moq-vaapi 0.2.1 (a patch: `cargo semver-checks` against 0.2.0 -needs no bump), tagged `v0.2.1`. - -What remains here: bump `moq-vaapi` in the root `Cargo.toml` to 0.2.1, refresh `Cargo.lock` with it, and say in the module docs of -`rs/moq-video/src/encode/backend/vaapi.rs` that the tests pass on radeonsi. -Then delete this quest. - -Public API: none. Wire: none. - -## Related - -- [Vulkan Video encode on AMD](/quest/m3/vulkan-encode.md) - AMD's long-term encode path -- [VA-API renderer tests](/quest/m4/vaapi-render-tests.md) - runs the VA-API tests on each render node -- [moq-vaapi vendor sync](/quest/m3/vendor-sync/vaapi.md) - the crate's upstream record diff --git a/quest/m3/audit-deps.md b/quest/m3/audit-deps.md index 01b5e8c20d1..df4c0371c81 100644 --- a/quest/m3/audit-deps.md +++ b/quest/m3/audit-deps.md @@ -124,8 +124,7 @@ Most duplicates still come from upstream ecosystem transitions: RustCrypto's older generation through rsa/jsonwebtoken/STUN/SRT; retina's h264-reader 0.8 and bitstream-io 2; srt-tokio's older rand/socket2/derive_more; rustls-acme's rcgen 0.13 and web client; winit's older platform stack; and libspa's -system-deps 7 beside GStreamer's 9. moq-vaapi still holds bindgen 0.70, -libloading 0.8 and thiserror 1; mp4-atom also holds thiserror 1. Do not treat +system-deps 7 beside GStreamer's 9. mp4-atom still holds thiserror 1. Do not treat all 117 extras as locally removable without checking those consumers. Bun's same-major duplicates can persist until a parent re-resolves. diff --git a/quest/m3/h265-min-width.md b/quest/m3/h265-min-width.md index 20f547e334f..72dc11ad530 100644 --- a/quest/m3/h265-min-width.md +++ b/quest/m3/h265-min-width.md @@ -25,8 +25,7 @@ is 320 wide for a 4:3 source), and a failed rung probe must fail only that rung: today `Pipeline::new` propagates it and aborts the whole transcode. Decided 2026-11-06 (maintainer, /quest-unblock): ✅ an S quest in m3. Not -chosen: folding it into [the radeonsi quest](/quest/m1/vaapi-radeonsi.md), -or dropping it. +chosen: folding it into the radeonsi quest (since completed), or dropping it. Decided 2026-11-07 (maintainer, /quest-complete): ✅ narrowed to the capture encode (`moq import capture --codec h265`), an S in m3, with H.265 @@ -43,5 +42,4 @@ none. ## Related -- [VA-API encode is correct on radeonsi](/quest/m1/vaapi-radeonsi.md) - the same AMD hardware run - [Vulkan Video encode on AMD](/quest/m3/vulkan-encode.md) - may report a different minimum diff --git a/quest/m3/vendor-sync/README.md b/quest/m3/vendor-sync/README.md index ca36c3071e6..df81b08ee45 100644 --- a/quest/m3/vendor-sync/README.md +++ b/quest/m3/vendor-sync/README.md @@ -3,7 +3,7 @@ ## Goal Once per release cycle, every library vendored into moq-dev/moq, plus -moq-dev/vaapi and the UniFFI generator forks, is compared against its upstream +the UniFFI generator forks, is compared against its upstream from the last checked commit. Useful fixes and features are ported or planned, each library records the newest upstream commit checked, and code vendored since the last run gets its own child. @@ -76,7 +76,7 @@ behavior follows quinn's fixes. - [moq-rtmp's rml has every upstream fix it needs](/quest/m3/vendor-sync/rml.md) - rust-media-libs fixes to rml_rtmp and rml_amf0 are ported or ruled out - [moq-v4l has every libv4l-rs fix it needs](/quest/m3/vendor-sync/v4l.md) - libv4l-rs fixes are ported or ruled out - [moq-nvenc has every upstream fix it needs](/quest/m3/vendor-sync/nvenc.md) - nvidia-video-codec-sdk fixes and NVIDIA SDK releases are ported or ruled out -- [moq-vaapi has every ChromeOS fix it needs](/quest/m3/vendor-sync/vaapi.md) - cros-libva and cros-codecs fixes are ported, released, and adopted +- [moq-vaapi has every ChromeOS fix it needs](/quest/m3/vendor-sync/vaapi.md) - cros-libva and cros-codecs fixes are ported or ruled out - [UniFFI generator forks are current](/quest/m3/vendor-sync/uniffi.md) - the four `kixelated/uniffi-*` forks carry the upstream fixes moq's bindings need ## Related diff --git a/quest/m3/vendor-sync/vaapi.md b/quest/m3/vendor-sync/vaapi.md index fda8fdeb9f8..7ca3e739bae 100644 --- a/quest/m3/vendor-sync/vaapi.md +++ b/quest/m3/vendor-sync/vaapi.md @@ -2,41 +2,22 @@ ## Goal -[moq-dev/vaapi](https://github.com/moq-dev/vaapi) carries every fix that +`rs/moq-vaapi` carries every fix that [chromeos/cros-libva](https://github.com/chromeos/cros-libva) and [chromeos/cros-codecs](https://github.com/chromeos/cros-codecs) have landed since the last check, for the code it vendors, each ported with its test or -recorded as not applying, and released to crates.io if anything changed, with -moq's `moq-vaapi` dependency bumped to that release. +recorded as not applying. ## Plan Recurring child of the [vendor sync](/quest/m3/vendor-sync/README.md), which -says how each run works and recurs. moq-vaapi lives in its own repository and -ships from crates.io for build reasons; its README's `Upstream` section is the -record. +says how each run works and recurs. The crate's README `Upstream` section is +the record: the Discord baselines it forked from, the ChromeOS heads last +checked, and what was ruled out. Track the ChromeOS default branches against +those diverged baselines, without undoing Discord's additions. -moq-vaapi vendors Discord's forks: cros-libva branch `discord-0.0.13` -([`896a248e`](https://github.com/discord/cros-libva/commit/896a248e003caae7a7120812f7eaa423c93a920d)) -and cros-codecs branch `discord-0.0.5` -([`9cdecb19`](https://github.com/discord/cros-codecs/commit/9cdecb192ee3682950d02bd80a7f106163531b76)). -Track the ChromeOS default branches against these diverged baselines, without -undoing Discord's additions. - -Last checked (2026-10-31), per [moq-vaapi 0.1.1's Upstream -audit](https://github.com/moq-dev/vaapi/blob/v0.1.1/README.md#upstream): -cros-libva through -[`59384456`](https://github.com/chromeos/cros-libva/commit/59384456ac2ae78c0c3e5515f41ef1efd9b802cf) -and cros-codecs through -[`a050c6cd`](https://github.com/chromeos/cros-codecs/commit/a050c6cde530e563197ee9e3e72ab01f48a0c41f). -That cycle ported the `log/release_max_level_debug` removal -([moq-dev/vaapi#5](https://github.com/moq-dev/vaapi/pull/5)), made the repo's -CI read-only ([moq-dev/vaapi#6](https://github.com/moq-dev/vaapi/pull/6)), -and moq adopted `moq-vaapi 0.1.1`. Ruled out: protected-content headers and -borrowed input buffers have no consumer; the VP9 wrapper already zero-fills -libva 2.23's fields. Advisory checks cover both ChromeOS repositories, both -Discord forks, and the global Rust advisories for `cros-libva` and -`cros-codecs`. +The crate moved in-tree from moq-dev/vaapi after its 0.2.1 release; the +previous cycle's audit lives in that README unchanged. ## Required diff --git a/rs/moq-vaapi/CHANGELOG.md b/rs/moq-vaapi/CHANGELOG.md new file mode 100644 index 00000000000..3b27f786eb3 --- /dev/null +++ b/rs/moq-vaapi/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Changed + +- Moved into [moq-dev/moq](https://github.com/moq-dev/moq) from [moq-dev/vaapi](https://github.com/moq-dev/vaapi), whose history covers 0.2.1 and earlier. +- Logs through `tracing` instead of `log`. diff --git a/rs/moq-vaapi/Cargo.toml b/rs/moq-vaapi/Cargo.toml new file mode 100644 index 00000000000..19c0565ce86 --- /dev/null +++ b/rs/moq-vaapi/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "moq-vaapi" +version = "0.2.1" +edition = "2021" +license = "BSD-3-Clause" +rust-version.workspace = true + +description = "(AI GENERATED) VA-API H.264/H.265 hardware encoder and decoder, forked from discord/cros-libva and discord/cros-codecs with libva dlopen'd at runtime" +authors = ["The ChromiumOS Authors", "Discord", "Luke Curley "] +repository = "https://github.com/moq-dev/moq" +readme = "README.md" + +keywords = ["vaapi", "h264", "encoder", "decoder", "hardware"] +categories = ["multimedia::encoding", "hardware-support", "external-ffi-bindings"] + +# Only bindgen.sh reads the headers; the bindings it generates are checked in. +exclude = ["bindgen.sh", "libva/", "libva-wrapper.h"] + +[dependencies] +anyhow = { workspace = true } +bitflags = { workspace = true } +# dlopen libva at runtime: the bindings' `Va` struct is built on libloading. +libloading = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +workspace-hack = { path = "../workspace-hack" } + +[lints] +workspace = true diff --git a/rs/moq-vaapi/LICENSE b/rs/moq-vaapi/LICENSE new file mode 100644 index 00000000000..9c1f839470d --- /dev/null +++ b/rs/moq-vaapi/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/rs/moq-vaapi/LICENSE.cros-codecs b/rs/moq-vaapi/LICENSE.cros-codecs new file mode 100644 index 00000000000..9c1f839470d --- /dev/null +++ b/rs/moq-vaapi/LICENSE.cros-codecs @@ -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/rs/moq-vaapi/LICENSE.libva b/rs/moq-vaapi/LICENSE.libva new file mode 100644 index 00000000000..900e77549f2 --- /dev/null +++ b/rs/moq-vaapi/LICENSE.libva @@ -0,0 +1,19 @@ + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sub license, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice (including the + next paragraph) shall be included in all copies or substantial portions + of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/rs/moq-vaapi/MIGRATE.md b/rs/moq-vaapi/MIGRATE.md new file mode 100644 index 00000000000..55e2f6ea11c --- /dev/null +++ b/rs/moq-vaapi/MIGRATE.md @@ -0,0 +1,5 @@ +# Migrating moq-vaapi + +How to update your code for each breaking change, newest first. + +## Unreleased diff --git a/rs/moq-vaapi/README.md b/rs/moq-vaapi/README.md new file mode 100644 index 00000000000..a27d938ab61 --- /dev/null +++ b/rs/moq-vaapi/README.md @@ -0,0 +1,127 @@ +# moq-vaapi + +> **⚠️ AI GENERATED.** This crate was written by an AI agent (Claude), using the +> repositories below as references. How closely individual files track upstream +> varies, so treat the whole thing as derived work and review before relying on +> it. The encoder and the decoder have both been checked against ffmpeg's +> software codecs on Intel hardware (see below). + +A small, self-contained **VA-API H.264 / H.265 hardware codec** for Linux (Intel / AMD), +derived from +[discord/cros-libva @ discord-0.0.13](https://github.com/discord/cros-libva/tree/discord-0.0.13) +and +[discord/cros-codecs @ discord-0.0.5](https://github.com/discord/cros-codecs/tree/discord-0.0.5) +(both BSD-3-Clause), themselves forks of Intel's +[cros-libva](https://github.com/intel/cros-libva) (ChromiumOS). + +It gives `moq-video` a thin VA-API codec instead of a multi-backend framework. +It lived in [moq-dev/vaapi](https://github.com/moq-dev/vaapi) through 0.2.1. + +## What it does + +- **H.264 and H.265 encode** over VA-API: an Annex-B elementary stream out + (packed parameter sets, low-latency IPPP, CBR rate control whose bitrate can + change between frames, the color space labelled in the VUI). H.265 is Main + profile with its VPS, SPS, PPS, and slice headers written here, its coding + tools following what the driver reports, and its coded size following the + driver's surface alignment, so the crop holds on radeonsi, which rewrites the + SPS at that alignment. Three inputs: + tightly-packed NV12 from the CPU, an NV12 DMA-BUF at the encoder's size + encoded in place, and any other importable DMA-BUF (packed RGB, YUYV, NV12 + at another size or in another color space) converted and scaled into the + encoder's surface on the GPU. NV12 and BGRX input are tested; the other + formats go through the same video processor call untested. + Checked on Intel Meteor Lake (iHD 26.1.5) by decoding with ffmpeg: luma + above 35 dB PSNR against the source, and RGB converted to BT.601 and BT.709 + to within a few code values. These run as tests, for both codecs, wherever + ffmpeg and a VA-API device are both present. Both codecs pass them on Intel + Arrow Lake (iHD 26.3.5) and AMD Radeon RX 9070 (radeonsi, Mesa 26.2.5), + where the stream also holds within a quarter of its bitrate from 2 Mbps down + to 250 kbps. +- **DMA-BUF import and video post-processing.** `dmabuf` wraps a DRM PRIME + buffer as a surface without copying it; `vpp` blits one surface into another + through `VAEntrypointVideoProc`, scaling, converting, and re-tiling on the + way. `Processor::resize` scales into NV12 surfaces it recycles per size, so a + stream of resizes costs no allocation per frame. +- **H.264 and H.265 decode** over VA-API: one Annex-B access unit in, + tightly-packed NV12 out, with in-stream parameter sets, a conformant DPB, and + mid-stream resolution changes. H.264 covers reference marking, reordering, + and frame\_num gaps; H.265 covers reference picture sets, long-term + references, open-GOP CRA pictures, and dependent slice segments, and puts a + picture out as soon as the SPS's reorder limit allows, so a stream without + B-frames comes out with no delay. H.265 is the Main profile, plus Main 10 and + Main Still Picture streams that hold 8-bit samples. Progressive 8-bit 4:2:0 + only, with right/bottom cropping supported and left/top cropping rejected. + H.264 was verified bit-exact against ffmpeg's software decoder on Intel + Meteor Lake (iHD 26.1.5) for constrained baseline, main with B-frames, high at + 720p, and a cropped non-macroblock-aligned size. Both codecs, coded by x264 + and x265 with B-frames at 320x240 and cropped at 852x478, run bit-exact as a + test wherever ffmpeg and a VA-API device are both present, and pass on Intel + Arrow Lake (iHD 26.1.2) and AMD Radeon RX 9070 (radeonsi, Mesa 26.0.8). +- **Checked-in bindings from pinned headers.** libva's headers are vendored + into [`libva/`](./libva), and [`bindgen.sh`](./bindgen.sh) generates + [`src/bindings/libva.rs`](./src/bindings/libva.rs) from them. The output is + checked in, so building the crate needs **no libclang, no libva-dev, and no + build script**, and the pinned version means a system libva bump can't drift + the bindings. The file is portable: fixed-width C types, no layout tests, and + the two VPP structs whose padding libva sizes by pointer width carry both + layouts under a `cfg`. +- **Loads system libva at runtime on Linux.** The generated `Va` function table + loads `libva` / `libva-drm` with `libloading`. Building needs no system libva, + and a binary can start without it; opening a display reports a missing driver + or library. The crate also compiles on macOS for development. + +## Upstream + +Last checked **2026-10-31**, starting from the Discord vendor baselines: + +| Source | Vendored baseline | ChromeOS default branch checked | +| --- | --- | --- | +| cros-libva | [`discord-0.0.13`, `896a248e`](https://github.com/discord/cros-libva/commit/896a248e003caae7a7120812f7eaa423c93a920d) | [`59384456ac2ae78c0c3e5515f41ef1efd9b802cf`](https://github.com/chromeos/cros-libva/commit/59384456ac2ae78c0c3e5515f41ef1efd9b802cf) | +| cros-codecs | [`discord-0.0.5`, `9cdecb19`](https://github.com/discord/cros-codecs/commit/9cdecb192ee3682950d02bd80a7f106163531b76) | [`a050c6cde530e563197ee9e3e72ab01f48a0c41f`](https://github.com/chromeos/cros-codecs/commit/a050c6cde530e563197ee9e3e72ab01f48a0c41f) | + +The forks diverge, so compare commits reachable from the checked head but not +the baseline, rather than replacing Discord's additions with the upstream tree. +This run checked all five cros-libva commits and the one cros-codecs commit: + +| Commit | Disposition | +| --- | --- | +| cros-libva [`838808ce`](https://github.com/chromeos/cros-libva/commit/838808cebfeff64f5c3543c873dbc604857b3702), protected-content headers | Not needed: no protected-content consumer or Android build in this crate. | +| cros-libva [`89454d66`](https://github.com/chromeos/cros-libva/commit/89454d660411627a4a463116fdea00ac1ac888bc), explicit image lifetimes | Already present in `Image::create_from` and `Picture::{derive_image,create_image}`. | +| cros-libva [`9f3c0d92`](https://github.com/chromeos/cros-libva/commit/9f3c0d9264ec04b4fa792764178b879341ce33b1), packed-header bindings | Already present in the `bindgen` allowlist, `buffer.rs`, and the H.264 encoder. | +| cros-libva [`ed9c63b7`](https://github.com/chromeos/cros-libva/commit/ed9c63b743ce9490e1079a8b0c1a24b8e879324f), borrowed input buffers | Optional copy avoidance, not a correctness fix. Keep the existing owned-buffer API; no new public API or optimization without measurement. | +| cros-libva [`59384456`](https://github.com/chromeos/cros-libva/commit/59384456ac2ae78c0c3e5515f41ef1efd9b802cf), libva 2.23 VP9 fields | Not applicable: the codec drivers support only H.264 and H.265, and the VP9 buffers were since removed. | +| cros-codecs [`a050c6cd`](https://github.com/chromeos/cros-codecs/commit/a050c6cde530e563197ee9e3e72ab01f48a0c41f), release log filtering | Ported: remove `log/release_max_level_debug`, which conflicts with a consumer selecting another release level. The crate now logs through `tracing`. | + +GitHub's published security-advisory endpoints for +[chromeos/cros-libva](https://github.com/chromeos/cros-libva/security/advisories), +[chromeos/cros-codecs](https://github.com/chromeos/cros-codecs/security/advisories), +[discord/cros-libva](https://github.com/discord/cros-libva/security/advisories), and +[discord/cros-codecs](https://github.com/discord/cros-codecs/security/advisories) +all returned empty lists on this date. GitHub's global Rust advisory queries for +`cros-libva` and `cros-codecs` also returned none. This records the published +advisories checked, not a guarantee that no undisclosed vulnerabilities exist. + +## Layout + +- `src/`: libva bindings (`bindings`, `display`, `surface`, `buffer`, ...), the + H.264 and H.265 bitstream layers (`bitstream_utils`, `codec::h264`, + `codec::h265`), the H.265 header writer (`encode/h265.rs`), the thin encode + and decode drivers (`encode`, `decode`), DMA-BUF import (`dmabuf`), video + post-processing (`vpp`), and the color space both share (`color`). +- `libva/`: vendored libva headers. +- `libva-wrapper.h` and [`bindgen.sh`](./bindgen.sh): what generates + `src/bindings/libva.rs`. + +Regenerate the bindings with bindgen-cli on the PATH: + +```sh +nix shell nixpkgs#rust-bindgen --command ./bindgen.sh # from libva/ +nix shell nixpkgs#rust-bindgen --command ./bindgen.sh 2.23.0 # refresh libva/ from that release first +``` + +## Licensing + +BSD-3-Clause (see [`LICENSE`](./LICENSE)). Vendored upstreams keep their notices: +[`LICENSE.cros-codecs`](./LICENSE.cros-codecs) and the vendored libva headers +under [`LICENSE.libva`](./LICENSE.libva) (MIT). diff --git a/rs/moq-vaapi/bindgen.sh b/rs/moq-vaapi/bindgen.sh new file mode 100755 index 00000000000..e1c8aa63bf6 --- /dev/null +++ b/rs/moq-vaapi/bindgen.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Regenerates src/bindings/libva.rs from the vendored headers in libva/. Needs +# bindgen-cli on the PATH (`nix shell nixpkgs#rust-bindgen --command ./bindgen.sh`). +# Passing a libva release tag (e.g. `./bindgen.sh 2.23.0`) first refreshes +# libva/ and LICENSE.libva from that release. +# +# The C types the bindings use are fixed-width or symbolic (`c_char`), so one +# file serves every target. The exception is libva's own: two VPP structs pad to +# a constant size with a reserved array whose length depends on the pointer +# width, so both layouts are generated and the lines that differ go under a cfg. +set -euo pipefail +cd "$(dirname "$0")" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +if [ $# -gt 0 ]; then + # Only what bindgen reads: meson.build (version), va/*.h{,.in}, va/drm/va_drm.h. + git clone --depth 1 --branch "$1" https://github.com/intel/libva.git "$work/libva" + rm -rf libva + mkdir -p libva/va/drm + cp "$work/libva/meson.build" libva/meson.build + cp "$work"/libva/va/*.h "$work"/libva/va/*.h.in libva/va/ + cp "$work/libva/va/drm/va_drm.h" libva/va/drm/va_drm.h + cp "$work/libva/COPYING" LICENSE.libva +fi + +# libva generates va_version.h from a template at build time, and installs +# va_drm.h beside va.h; stage both where `#include ` finds them. +mkdir -p "$work/va" +version() { sed -nE "s/^$1\s*=\s*([0-9]+).*/\1/p" libva/meson.build; } +major=$(version va_api_major_version) +minor=$(version va_api_minor_version) +micro=$(version va_api_micro_version) +sed -e "s/@VA_API_MAJOR_VERSION@/$major/" -e "s/@VA_API_MINOR_VERSION@/$minor/" \ + -e "s/@VA_API_MICRO_VERSION@/$micro/" -e "s/@VA_API_VERSION@/$major.$minor.$micro/" \ + libva/va/va_version.h.in >"$work/va/va_version.h" +cp libva/va/drm/va_drm.h "$work/va/va_drm.h" + +# `--dynamic-loading` emits a `Va` struct of function pointers that libloading +# resolves at runtime, rather than link-time externs, so libva is dlopen'd. A +# symbol a system libva older than these headers lacks errors only when called, +# not when the library loads. Freestanding, so the host's C library cannot +# change the output. +generate() { + bindgen libva-wrapper.h \ + --rust-target 1.85 \ + --rust-edition 2021 \ + --no-layout-tests \ + --with-derive-default \ + --with-derive-eq \ + --constified-enum-module 'VA.*' \ + --allowlist-var 'VA.*' \ + --allowlist-function 'va.*' \ + --allowlist-type '.*ExternalBuffers.*|.*PRIME.*|.*H264.*|.*HEVC.*|VACodedBufferSegment|VAEncMisc.*|VASurfaceDecodeMBErrors|VADecodeErrorType|.*VAProc.*|VAEncPacked.*' \ + --dynamic-loading Va \ + --output "$2" \ + -- -Ilibva -I"$work" -ffreestanding --target="$1" +} +generate x86_64-unknown-linux-gnu "$work/wide.rs" +generate i686-unknown-linux-gnu "$work/narrow.rs" + +# Only the reserved padding may differ; anything else needs a look before it is +# papered over with a cfg. +unexpected=$(diff "$work/wide.rs" "$work/narrow.rs" | grep -E '^[<>]' | grep -vE '^[<>]\s*pub va_reserved: \[u(16|32); [0-9]+usize\],$' || true) +if [ -n "$unexpected" ]; then + printf 'the bindings differ by pointer width in more than libva'"'"'s reserved padding:\n%s\n' "$unexpected" >&2 + exit 1 +fi +# The condition libva's headers pad on: x86_64, or LP64. +wide='any(target_arch = "x86_64", all(target_pointer_width = "64", not(windows)))' +diff --unchanged-line-format='%L' \ + --old-line-format=$'\t#[cfg('"$wide"$')]\n%L' \ + --new-line-format=$'\t#[cfg(not('"$wide"$'))]\n%L' \ + "$work/wide.rs" "$work/narrow.rs" >"$work/merged.rs" || [ $? -eq 1 ] +# bindgen bounds `Va::new` by `AsRef`, which libloading 0.9's +# `Library::new` no longer accepts. +grep -qF 'P: AsRef<::std::ffi::OsStr>,' "$work/merged.rs" +sed 's/P: AsRef<::std::ffi::OsStr>,$/P: ::libloading::AsFilename,/' "$work/merged.rs" >src/bindings/libva.rs diff --git a/rs/moq-vaapi/libva-wrapper.h b/rs/moq-vaapi/libva-wrapper.h new file mode 100644 index 00000000000..2e5ba38956d --- /dev/null +++ b/rs/moq-vaapi/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/rs/moq-vaapi/libva/meson.build b/rs/moq-vaapi/libva/meson.build new file mode 100644 index 00000000000..26190d6a5b5 --- /dev/null +++ b/rs/moq-vaapi/libva/meson.build @@ -0,0 +1,160 @@ +# libva package version number, (as distinct from shared library version) +# XXX: we want the package version to remain at 1.0.x for VA-API 0.32.y +# +# - major version is automatically generated from VA-API major version +# - minor version is automatically generated from VA-API minor version +# - increment micro for any library release +# - reset micro version to zero when VA-API major or minor version is changed +project( + 'libva', 'c', + version : '2.23.0', + meson_version : '>= 0.53.0', + default_options : [ 'warning_level=1', + 'buildtype=debugoptimized' ]) + +# VA-API version +# - increment major for any ABI change +# - increment minor for any interface change (e.g. new/modified function) +# - increment micro for any other change (new flag, new codec definition, etc.) +# - reset micro version to zero when minor version is incremented +# - reset minor version to zero when major version is incremented +va_api_major_version = 1 +va_api_minor_version = 23 +va_api_micro_version = 0 + +va_api_version = '@0@.@1@.@2@'.format(va_api_major_version, + va_api_minor_version, + va_api_micro_version) + +version_arr = meson.project_version().split('.') +libva_major_version = version_arr[0] +libva_minor_version = version_arr[1] +libva_micro_version = version_arr[2] +libva_version = '@0@.@1@.@2@'.format(libva_major_version, + libva_minor_version, + libva_micro_version) +if version_arr.length() == 4 + libva_version = '@0@.pre@1@'.format(libva_version, version_arr[3]) +endif + + +# libva library version number (generated, do not change) +# XXX: we want the SONAME to remain at libva.so.1 for VA-API major == 0 +# +# The library name is generated libva...0 where +# = VA-API major version + 1 +# = 100 * VA-API minor version + VA-API micro version +# +# For example: +# VA-API 0.32.0 generates libva.so.1.3200.0 +# VA-API 0.34.1 generates libva.so.1.3401.0 +# VA-API 1.2.13 generates libva.so.2.213.0 +libva_interface_bias = va_api_major_version + 1 +libva_interface_age = 0 +libva_binary_age = 100 * va_api_minor_version + va_api_micro_version - libva_interface_age + +libva_lt_current = 100 * va_api_minor_version + va_api_micro_version + libva_interface_bias +libva_lt_revision = libva_interface_age +libva_lt_age = libva_binary_age - libva_interface_age + +libva_lt_current = libva_lt_current - libva_lt_age + +libva_lt_version = '@0@.@1@.@2@'.format(libva_lt_current, + libva_lt_age, + libva_lt_revision) + +sysconfdir = join_paths(get_option('prefix'), get_option('sysconfdir')) + +driverdir = get_option('driverdir') +if driverdir == '' + # "libdir" on Windows is essentially only for static and import libraries, + # while "bindir" is the actual runtime directory - containing both + # executable and dynamic libraries. During install meson uses correct install + # location depending on the type of library, requiring zero user intervention + # in the common case. + if host_machine.system() == 'windows' + driverdir = join_paths(get_option('prefix'), get_option('bindir')) + else + driverdir = join_paths(get_option('prefix'), get_option('libdir'), 'dri') + endif +endif + +configinc = include_directories('.') + +cc = meson.get_compiler('c') +dl_dep = cc.find_library('dl', required : false) + +WITH_DRM = not get_option('disable_drm') and (host_machine.system() != 'windows') +libdrm_dep = dependency('libdrm', version : '>= 2.4.75', required : (host_machine.system() != 'windows')) + +WITH_X11 = false +if get_option('with_x11') != 'no' + x11_dep = dependency('x11', required : get_option('with_x11') == 'yes') + xext_dep = dependency('xext', required : get_option('with_x11') == 'yes') + xfixes_dep = dependency('xfixes', required : get_option('with_x11') == 'yes') + + WITH_X11 = (x11_dep.found() and xext_dep.found() and xfixes_dep.found()) + + x11_xcb_dep = dependency('x11-xcb', required : get_option('with_x11') == 'yes') + xcb_dep = dependency('xcb', required : get_option('with_x11') == 'yes') + xcb_dri3_dep = dependency('xcb-dri3', required : get_option('with_x11') == 'yes') + WITH_X11 = (WITH_X11 and x11_xcb_dep.found() and xcb_dep.found() and xcb_dri3_dep.found()) +endif + +if not WITH_X11 and get_option('with_glx') == 'yes' + error('VA/GLX explicitly enabled, but VA/X11 isn\'t built') +endif + +WITH_GLX = false +if WITH_X11 and get_option('with_glx') != 'no' + gl_dep = dependency('gl', required : get_option('with_glx') == 'yes') + WITH_GLX = gl_dep.found() +endif + +WITH_WAYLAND = false +if get_option('with_wayland') != 'no' + wayland_dep = dependency('wayland-client', version : '>= 1.11.0', + required : get_option('with_wayland') == 'yes') + wayland_scanner_dep = dependency('wayland-scanner', version : '>= 1.15', + required : get_option('with_wayland') == 'yes', + native : true) + if wayland_scanner_dep.found() + wl_scanner = find_program(wayland_scanner_dep.get_variable(pkgconfig: 'wayland_scanner')) + endif + WITH_WAYLAND = wayland_dep.found() and wayland_scanner_dep.found() +endif + +WITH_WIN32 = false +libwin32_dep = [] +if get_option('with_win32') != 'no' + WITH_WIN32 = (host_machine.system() == 'windows') +endif + +if (not WITH_DRM and not WITH_X11 and not WITH_WAYLAND and not WITH_WIN32) + error('Please install at least one backend dev files (DRM, X11, Wayland, WIN32)') +endif + +c_args = [] +if get_option('with_legacy').contains('emgd') + c_args += ['-DHAVE_EMGD'] +elif get_option('with_legacy').contains('nvctrl') + c_args += ['-DHAVE_NVCTRL'] +elif get_option('with_legacy').contains('fglrx') + c_args += ['-DHAVE_FGLRX'] +endif + +if cc.has_function('secure_getenv') + c_args += ['-DHAVE_SECURE_GETENV'] +endif + +add_project_arguments(c_args, language: ['c']) + +subdir('va') +subdir('pkgconfig') + +doxygen = find_program('doxygen', required: false) + +if get_option('enable_docs') and doxygen.found() + subdir('doc') +endif + diff --git a/rs/moq-vaapi/libva/va/compat_win32.h b/rs/moq-vaapi/libva/va/compat_win32.h new file mode 100644 index 00000000000..8294f2fcb7e --- /dev/null +++ b/rs/moq-vaapi/libva/va/compat_win32.h @@ -0,0 +1,213 @@ +/* + * Copyright © Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef _COMPAT_WIN32_H_ +#define _COMPAT_WIN32_H_ + +#include +#include +#include +#include + +// Include stdlib.h here to make sure we +// always replace MSVC getenv definition +// with the macro / _getenv inline below +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define F_OK 0 +#define RTLD_NOW 0 +#define RTLD_GLOBAL 0 + +#ifndef NTSTATUS +typedef LONG NTSTATUS; +#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) +#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023) +#define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0) +#endif + +typedef unsigned int __uid_t; + +#if _MSC_VER +#define getenv _getenv +#define secure_getenv _getenv +#define HAVE_SECURE_GETENV +inline char* _getenv(const char *varname) +{ + static char _getenv_buf[32767]; + return GetEnvironmentVariableA(varname, &_getenv_buf[0], sizeof(_getenv_buf)) ? &_getenv_buf[0] : NULL; +} +#endif + +#ifdef _MSC_VER +inline char* strtok_r(char *s, const char *delim, char **save_ptr) +{ + return strtok_s(s, delim, save_ptr); +} +#endif + +inline void* dlopen(const char *file, int mode) +{ + return LoadLibrary(file); +} + +inline int dlclose(void *handle) +{ + return FreeLibrary(handle); +} + +inline void *dlsym(void *handle, const char *name) +{ + return GetProcAddress(handle, name); +} + +inline static char* dlerror() +{ + static char last_err_string[512]; + memset(last_err_string, '\0', 512); + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), last_err_string, (512 - 1), NULL); + return last_err_string; +} + +inline __uid_t geteuid() +{ + return 0; +}; + +inline __uid_t getuid() +{ + return 0; +}; + +typedef DWORD pid_t; +typedef CRITICAL_SECTION pthread_mutex_t; + +inline void pthread_mutex_lock(pthread_mutex_t* a) +{ + EnterCriticalSection(a); +} + +inline void pthread_mutex_unlock(pthread_mutex_t* a) +{ + LeaveCriticalSection(a); +} + +inline void pthread_mutex_init(pthread_mutex_t* a, void* attr) +{ + InitializeCriticalSection(a); +} + +inline void pthread_mutex_destroy(pthread_mutex_t* a) +{ + DeleteCriticalSection(a); +} + +inline int gettimeofday(struct timeval *tv, struct timezone* tz) +{ + SYSTEMTIME st; + GetSystemTime(&st); + tv->tv_sec = st.wSecond; + tv->tv_usec = st.wMilliseconds * 1000; /* milli to micro sec */ + return 0; +} + +#ifdef _MSC_VER +#include +#include +#else +// +// DDI level handle that represents a kernel mode object (allocation, device, etc) +// +typedef UINT D3DKMT_HANDLE; + +typedef struct _D3DKMT_CLOSEADAPTER { + D3DKMT_HANDLE hAdapter; // in: adapter handle +} D3DKMT_CLOSEADAPTER; + +typedef struct _D3DKMT_OPENADAPTERFROMLUID { + LUID AdapterLuid; + D3DKMT_HANDLE hAdapter; +} D3DKMT_OPENADAPTERFROMLUID; + +typedef enum _KMTQUERYADAPTERINFOTYPE { + KMTQAITYPE_QUERYREGISTRY = 48, +} KMTQUERYADAPTERINFOTYPE; + +typedef struct _D3DKMT_QUERYADAPTERINFO { + D3DKMT_HANDLE hAdapter; + KMTQUERYADAPTERINFOTYPE Type; + VOID* pPrivateDriverData; + UINT PrivateDriverDataSize; +} D3DKMT_QUERYADAPTERINFO; + +typedef struct _D3DDDI_QUERYREGISTRY_FLAGS { + union { + struct { + UINT TranslatePath : 1; + UINT MutableValue : 1; + UINT Reserved : 30; + }; + UINT Value; + }; +} D3DDDI_QUERYREGISTRY_FLAGS; + +typedef enum _D3DDDI_QUERYREGISTRY_TYPE { + D3DDDI_QUERYREGISTRY_ADAPTERKEY = 1, +} D3DDDI_QUERYREGISTRY_TYPE; + +typedef enum _D3DDDI_QUERYREGISTRY_STATUS { + D3DDDI_QUERYREGISTRY_STATUS_SUCCESS = 0, + D3DDDI_QUERYREGISTRY_STATUS_BUFFER_OVERFLOW = 1, +} D3DDDI_QUERYREGISTRY_STATUS; + +typedef struct _D3DDDI_QUERYREGISTRY_INFO { + D3DDDI_QUERYREGISTRY_TYPE QueryType; // In + D3DDDI_QUERYREGISTRY_FLAGS QueryFlags; // In + WCHAR ValueName[MAX_PATH]; // In + ULONG ValueType; // In + ULONG PhysicalAdapterIndex; // In + ULONG OutputValueSize; // Out. Number of bytes written to the output value or required in case of D3DDDI_QUERYREGISTRY_STATUS_BUFFER_OVERFLOW. + D3DDDI_QUERYREGISTRY_STATUS Status; // Out + union { + DWORD OutputDword; // Out + UINT64 OutputQword; // Out + WCHAR OutputString[1]; // Out. Dynamic array + BYTE OutputBinary[1]; // Out. Dynamic array + }; +} D3DDDI_QUERYREGISTRY_INFO; + +typedef _Check_return_ NTSTATUS(APIENTRY *PFND3DKMT_CLOSEADAPTER)(_In_ CONST D3DKMT_CLOSEADAPTER*); +typedef _Check_return_ NTSTATUS(APIENTRY *PFND3DKMT_OPENADAPTERFROMLUID)(_Inout_ D3DKMT_OPENADAPTERFROMLUID*); +typedef _Check_return_ NTSTATUS(APIENTRY *PFND3DKMT_QUERYADAPTERINFO)(_Inout_ CONST D3DKMT_QUERYADAPTERINFO*); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _COMPAT_WIN32_H_ */ diff --git a/rs/moq-vaapi/libva/va/drm/va_drm.h b/rs/moq-vaapi/libva/va/drm/va_drm.h new file mode 100644 index 00000000000..a39c5a2e32f --- /dev/null +++ b/rs/moq-vaapi/libva/va/drm/va_drm.h @@ -0,0 +1,61 @@ +/* + * va_drm.h - Raw DRM API + * + * Copyright (c) 2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_DRM_H +#define VA_DRM_H + +#include + +/** + * \file va_drm.h + * \brief The raw DRM API + * + * This file contains the \ref api_drm "Raw DRM API". + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Returns a VA display derived from the specified DRM connection. + * + * This function returns a (possibly cached) VA display from the + * specified DRM connection @fd. + * + * @param[in] fd the DRM connection descriptor + * @return the VA display + */ +VADisplay +vaGetDisplayDRM(int fd); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DRM_H */ diff --git a/rs/moq-vaapi/libva/va/sysdeps.h b/rs/moq-vaapi/libva/va/sysdeps.h new file mode 100644 index 00000000000..3f9b439c5e7 --- /dev/null +++ b/rs/moq-vaapi/libva/va/sysdeps.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2007-2009 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef SYSDEPS_H +#define SYSDEPS_H + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include +#include + +// Defines for visibility attribute +// based on https://gcc.gnu.org/wiki/Visibility +#if defined _WIN32 || defined __CYGWIN__ +# define DLL_EXPORT __declspec(dllexport) +# define DLL_HIDDEN +#else +#if __GNUC__ >= 4 +# define DLL_HIDDEN __attribute__((visibility("hidden"))) +# define DLL_EXPORT __attribute__((visibility("default"))) +#else +# define DLL_HIDDEN +# define DLL_EXPORT +#endif +#endif + +#endif /* SYSDEPS_H */ diff --git a/rs/moq-vaapi/libva/va/va.h b/rs/moq-vaapi/libva/va/va.h new file mode 100644 index 00000000000..928703ee4f5 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va.h @@ -0,0 +1,5445 @@ +/* + * Copyright (c) 2007-2009 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +/* + * Video Acceleration (VA) API Specification + * + * Rev. 0.30 + * + * + * Revision History: + * rev 0.10 (12/10/2006 Jonathan Bian) - Initial draft + * rev 0.11 (12/15/2006 Jonathan Bian) - Fixed some errors + * rev 0.12 (02/05/2007 Jonathan Bian) - Added VC-1 data structures for slice level decode + * rev 0.13 (02/28/2007 Jonathan Bian) - Added GetDisplay() + * rev 0.14 (04/13/2007 Jonathan Bian) - Fixed MPEG-2 PictureParameter structure, cleaned up a few funcs. + * rev 0.15 (04/20/2007 Jonathan Bian) - Overhauled buffer management + * rev 0.16 (05/02/2007 Jonathan Bian) - Added error codes and fixed some issues with configuration + * rev 0.17 (05/07/2007 Jonathan Bian) - Added H.264/AVC data structures for slice level decode. + * rev 0.18 (05/14/2007 Jonathan Bian) - Added data structures for MPEG-4 slice level decode + * and MPEG-2 motion compensation. + * rev 0.19 (08/06/2007 Jonathan Bian) - Removed extra type for bitplane data. + * rev 0.20 (08/08/2007 Jonathan Bian) - Added missing fields to VC-1 PictureParameter structure. + * rev 0.21 (08/20/2007 Jonathan Bian) - Added image and subpicture support. + * rev 0.22 (08/27/2007 Jonathan Bian) - Added support for chroma-keying and global alpha. + * rev 0.23 (09/11/2007 Jonathan Bian) - Fixed some issues with images and subpictures. + * rev 0.24 (09/18/2007 Jonathan Bian) - Added display attributes. + * rev 0.25 (10/18/2007 Jonathan Bian) - Changed to use IDs only for some types. + * rev 0.26 (11/07/2007 Waldo Bastian) - Change vaCreateBuffer semantics + * rev 0.27 (11/19/2007 Matt Sottek) - Added DeriveImage + * rev 0.28 (12/06/2007 Jonathan Bian) - Added new versions of PutImage and AssociateSubpicture + * to enable scaling + * rev 0.29 (02/07/2008 Jonathan Bian) - VC1 parameter fixes, + * added VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED + * rev 0.30 (03/01/2009 Jonathan Bian) - Added encoding support for H.264 BP and MPEG-4 SP and fixes + * for ISO C conformance. + * rev 0.31 (09/02/2009 Gwenole Beauchesne) - VC-1/H264 fields change for VDPAU and XvBA backend + * Application needs to relink with the new library. + * + * rev 0.31.1 (03/29/2009) - Data structure for JPEG encode + * rev 0.31.2 (01/13/2011 Anthony Pabon)- Added a flag to indicate Subpicture coordinates are screen + * screen relative rather than source video relative. + * rev 0.32.0 (01/13/2011 Xiang Haihao) - Add profile into VAPictureParameterBufferVC1 + * update VAAPI to 0.32.0 + * + * Acknowledgements: + * Some concepts borrowed from XvMC and XvImage. + * Waldo Bastian (Intel), Matt Sottek (Intel), Austin Yuan (Intel), and Gwenole Beauchesne (SDS) + * contributed to various aspects of the API. + */ + +/** + * \file va.h + * \brief The Core API + * + * This file contains the \ref api_core "Core API". + */ + +#ifndef _VA_H_ +#define _VA_H_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__GNUC__) && !defined(__COVERITY__) +#define va_deprecated __attribute__((deprecated)) +#if __GNUC__ >= 6 +#define va_deprecated_enum va_deprecated +#else +#define va_deprecated_enum +#endif +#else +#define va_deprecated +#define va_deprecated_enum +#endif + +/** + * \mainpage Video Acceleration (VA) API + * + * \section intro Introduction + * + * The main motivation for VA-API (Video Acceleration API) is to + * enable hardware accelerated video decode and encode at various + * entry-points (VLD, IDCT, Motion Compensation etc.) for the + * prevailing coding standards today (MPEG-2, MPEG-4 ASP/H.263, MPEG-4 + * AVC/H.264, VC-1/VMW3, and JPEG, HEVC/H265, VP8, VP9) and video pre/post + * processing + * + * VA-API is split into several modules: + * - \ref api_core + * - Encoder (H264, HEVC, JPEG, MPEG2, VP8, VP9) + * - \ref api_enc_h264 + * - \ref api_enc_hevc + * - \ref api_enc_jpeg + * - \ref api_enc_mpeg2 + * - \ref api_enc_vp8 + * - \ref api_enc_vp9 + * - \ref api_enc_av1 + * - Decoder (HEVC, JPEG, VP8, VP9, AV1, VVC) + * - \ref api_dec_hevc + * - \ref api_dec_jpeg + * - \ref api_dec_vp8 + * - \ref api_dec_vp9 + * - \ref api_dec_av1 + * - \ref api_dec_vvc + * - \ref api_vpp + * - \ref api_prot + * - FEI (H264, HEVC) + * - \ref api_fei + * - \ref api_fei_h264 + * - \ref api_fei_hevc + * + * \section threading Multithreading Guide + * All VAAPI functions implemented in libva are thread-safe. For any VAAPI + * function that requires the implementation of a backend (e.g. hardware driver), + * the backend must ensure that its implementation is also thread-safe. If the + * backend implementation of a VAAPI function is not thread-safe then this should + * be considered as a bug against the backend implementation. + * + * It is assumed that none of the VAAPI functions will be called from signal + * handlers. + * + * Thread-safety in this context means that when VAAPI is being called by multiple + * concurrent threads, it will not crash or hang the OS, and VAAPI internal + * data structures will not be corrupted. When multiple threads are operating on + * the same VAAPI objects, it is the application's responsibility to synchronize + * these operations in order to generate the expected results. For example, using + * a single VAContext from multiple threads may generate unexpected results. + * + * Following pseudo code illustrates a multithreaded transcoding scenario, where + * one thread is handling the decoding operation and another thread is handling + * the encoding operation, while synchronizing the use of a common pool of + * surfaces. + * + * \code + * // Initialization + * dpy = vaGetDisplayDRM(fd); + * vaInitialize(dpy, ...); + * + * // Create surfaces required for decoding and subsequence encoding + * vaCreateSurfaces(dpy, VA_RT_FORMAT_YUV420, width, height, &surfaces[0], ...); + * + * // Set up a queue for the surfaces shared between decode and encode threads + * surface_queue = queue_create(); + * + * // Create decode_thread + * pthread_create(&decode_thread, NULL, decode, ...); + * + * // Create encode_thread + * pthread_create(&encode_thread, NULL, encode, ...); + * + * // Decode thread function + * decode() { + * // Find the decode entrypoint for H.264 + * vaQueryConfigEntrypoints(dpy, h264_profile, entrypoints, ...); + * + * // Create a config for H.264 decode + * vaCreateConfig(dpy, h264_profile, VAEntrypointVLD, ...); + * + * // Create a context for decode + * vaCreateContext(dpy, config, width, height, VA_PROGRESSIVE, surfaces, + * num_surfaces, &decode_context); + * + * // Decode frames in the bitstream + * for (;;) { + * // Parse one frame and decode + * vaBeginPicture(dpy, decode_context, surfaces[surface_index]); + * vaRenderPicture(dpy, decode_context, buf, ...); + * vaEndPicture(dpy, decode_context); + * // Poll the decoding status and enqueue the surface in display order after + * // decoding is complete + * vaQuerySurfaceStatus(); + * enqueue(surface_queue, surface_index); + * } + * } + * + * // Encode thread function + * encode() { + * // Find the encode entrypoint for HEVC + * vaQueryConfigEntrypoints(dpy, hevc_profile, entrypoints, ...); + * + * // Create a config for HEVC encode + * vaCreateConfig(dpy, hevc_profile, VAEntrypointEncSlice, ...); + * + * // Create a context for encode + * vaCreateContext(dpy, config, width, height, VA_PROGRESSIVE, surfaces, + * num_surfaces, &encode_context); + * + * // Encode frames produced by the decoder + * for (;;) { + * // Dequeue the surface enqueued by the decoder + * surface_index = dequeue(surface_queue); + * // Encode using this surface as the source + * vaBeginPicture(dpy, encode_context, surfaces[surface_index]); + * vaRenderPicture(dpy, encode_context, buf, ...); + * vaEndPicture(dpy, encode_context); + * } + * } + * \endcode + */ + +/** + * \defgroup api_core Core API + * + * @{ + */ + +/** +Overview + +The VA API is intended to provide an interface between a video decode/encode/processing +application (client) and a hardware accelerator (server), to off-load +video decode/encode/processing operations from the host to the hardware accelerator at various +entry-points. + +The basic operation steps are: + +- Negotiate a mutually acceptable configuration with the server to lock + down profile, entrypoints, and other attributes that will not change on + a frame-by-frame basis. +- Create a video decode, encode or processing context which represents a + "virtualized" hardware device +- Get and fill the render buffers with the corresponding data (depending on + profiles and entrypoints) +- Pass the render buffers to the server to handle the current frame + +Initialization & Configuration Management + +- Find out supported profiles +- Find out entrypoints for a given profile +- Find out configuration attributes for a given profile/entrypoint pair +- Create a configuration for use by the application + +*/ + +typedef void* VADisplay; /* window system dependent */ + +typedef int VAStatus; /** Return status type from functions */ +/** Values for the return status */ +#define VA_STATUS_SUCCESS 0x00000000 +#define VA_STATUS_ERROR_OPERATION_FAILED 0x00000001 +#define VA_STATUS_ERROR_ALLOCATION_FAILED 0x00000002 +#define VA_STATUS_ERROR_INVALID_DISPLAY 0x00000003 +#define VA_STATUS_ERROR_INVALID_CONFIG 0x00000004 +#define VA_STATUS_ERROR_INVALID_CONTEXT 0x00000005 +#define VA_STATUS_ERROR_INVALID_SURFACE 0x00000006 +#define VA_STATUS_ERROR_INVALID_BUFFER 0x00000007 +#define VA_STATUS_ERROR_INVALID_IMAGE 0x00000008 +#define VA_STATUS_ERROR_INVALID_SUBPICTURE 0x00000009 +#define VA_STATUS_ERROR_ATTR_NOT_SUPPORTED 0x0000000a +#define VA_STATUS_ERROR_MAX_NUM_EXCEEDED 0x0000000b +#define VA_STATUS_ERROR_UNSUPPORTED_PROFILE 0x0000000c +#define VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT 0x0000000d +#define VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT 0x0000000e +#define VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE 0x0000000f +#define VA_STATUS_ERROR_SURFACE_BUSY 0x00000010 +#define VA_STATUS_ERROR_FLAG_NOT_SUPPORTED 0x00000011 +#define VA_STATUS_ERROR_INVALID_PARAMETER 0x00000012 +#define VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED 0x00000013 +#define VA_STATUS_ERROR_UNIMPLEMENTED 0x00000014 +#define VA_STATUS_ERROR_SURFACE_IN_DISPLAYING 0x00000015 +#define VA_STATUS_ERROR_INVALID_IMAGE_FORMAT 0x00000016 +#define VA_STATUS_ERROR_DECODING_ERROR 0x00000017 +#define VA_STATUS_ERROR_ENCODING_ERROR 0x00000018 +/** + * \brief An invalid/unsupported value was supplied. + * + * This is a catch-all error code for invalid or unsupported values. + * e.g. value exceeding the valid range, invalid type in the context + * of generic attribute values. + */ +#define VA_STATUS_ERROR_INVALID_VALUE 0x00000019 +/** \brief An unsupported filter was supplied. */ +#define VA_STATUS_ERROR_UNSUPPORTED_FILTER 0x00000020 +/** \brief An invalid filter chain was supplied. */ +#define VA_STATUS_ERROR_INVALID_FILTER_CHAIN 0x00000021 +/** \brief Indicate HW busy (e.g. run multiple encoding simultaneously). */ +#define VA_STATUS_ERROR_HW_BUSY 0x00000022 +/** \brief An unsupported memory type was supplied. */ +#define VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE 0x00000024 +/** \brief Indicate allocated buffer size is not enough for input or output. */ +#define VA_STATUS_ERROR_NOT_ENOUGH_BUFFER 0x00000025 +/** \brief Indicate an operation isn't completed because time-out interval elapsed. */ +#define VA_STATUS_ERROR_TIMEDOUT 0x00000026 +#define VA_STATUS_ERROR_UNKNOWN 0xFFFFFFFF + +/** + * 1. De-interlacing flags for vaPutSurface() + * 2. Surface sample type for input/output surface flag + * - Progressive: VA_FRAME_PICTURE + * - Interleaved: VA_TOP_FIELD_FIRST, VA_BOTTOM_FIELD_FIRST + * - Field: VA_TOP_FIELD, VA_BOTTOM_FIELD +*/ +#define VA_FRAME_PICTURE 0x00000000 +#define VA_TOP_FIELD 0x00000001 +#define VA_BOTTOM_FIELD 0x00000002 +#define VA_TOP_FIELD_FIRST 0x00000004 +#define VA_BOTTOM_FIELD_FIRST 0x00000008 + +/** + * Enabled the positioning/cropping/blending feature: + * 1, specify the video playback position in the isurface + * 2, specify the cropping info for video playback + * 3, encoded video will blend with background color + */ +#define VA_ENABLE_BLEND 0x00000004 /* video area blend with the constant color */ + +/** + * Clears the drawable with background color. + * for hardware overlay based implementation this flag + * can be used to turn off the overlay + */ +#define VA_CLEAR_DRAWABLE 0x00000008 + +/** Color space conversion flags for vaPutSurface() */ +#define VA_SRC_COLOR_MASK 0x000000f0 +#define VA_SRC_BT601 0x00000010 +#define VA_SRC_BT709 0x00000020 +#define VA_SRC_SMPTE_240 0x00000040 + +/** Scaling flags for vaPutSurface() */ +#define VA_FILTER_SCALING_DEFAULT 0x00000000 +#define VA_FILTER_SCALING_FAST 0x00000100 +#define VA_FILTER_SCALING_HQ 0x00000200 +#define VA_FILTER_SCALING_NL_ANAMORPHIC 0x00000300 +#define VA_FILTER_SCALING_MASK 0x00000f00 + +/** Interpolation method for scaling */ +#define VA_FILTER_INTERPOLATION_DEFAULT 0x00000000 +#define VA_FILTER_INTERPOLATION_NEAREST_NEIGHBOR 0x00001000 +#define VA_FILTER_INTERPOLATION_BILINEAR 0x00002000 +#define VA_FILTER_INTERPOLATION_ADVANCED 0x00003000 +#define VA_FILTER_INTERPOLATION_MASK 0x0000f000 + +/** Padding size in 4-bytes */ +#define VA_PADDING_LOW 4 +#define VA_PADDING_MEDIUM 8 +#define VA_PADDING_HIGH 16 +#define VA_PADDING_LARGE 32 + +/** operation options */ +/** synchronization, block call, output should be ready after execution function return*/ +#define VA_EXEC_SYNC 0x0 +/** asynchronization,application should call additonal sync operation to access output */ +#define VA_EXEC_ASYNC 0x1 + +/** operation mode */ +#define VA_EXEC_MODE_DEFAULT 0x0 +#define VA_EXEC_MODE_POWER_SAVING 0x1 +#define VA_EXEC_MODE_PERFORMANCE 0x2 + +/* Values used to describe device features. */ +/** The feature is not supported by the device. + * + * Any corresponding feature flag must not be set. + */ +#define VA_FEATURE_NOT_SUPPORTED 0 +/** The feature is supported by the device. + * + * The user may decide whether or not to use this feature. + * + * Note that support for a feature only indicates that the hardware + * is able to use it; whether it is actually a positive change to + * enable it in a given situation will depend on other factors + * including the input provided by the user. + */ +#define VA_FEATURE_SUPPORTED 1 +/** The feature is required by the device. + * + * The device does not support not enabling this feature, so any + * corresponding feature flag must be set and any additional + * configuration needed by the feature must be supplied. + */ +#define VA_FEATURE_REQUIRED 2 + +/** + * Returns a short english description of error_status + */ +const char *vaErrorStr(VAStatus error_status); + +/** \brief Structure to describe rectangle. */ +typedef struct _VARectangle { + int16_t x; + int16_t y; + uint16_t width; + uint16_t height; +} VARectangle; + +/** \brief Generic motion vector data structure. */ +typedef struct _VAMotionVector { + /** \brief Past reference + * + * - \c [0]: horizontal motion vector for past reference + * - \c [1]: vertical motion vector for past reference + */ + int16_t mv0[2]; + /** \brief Future reference + * + * - \c [0]: horizontal motion vector for future reference + * - \c [1]: vertical motion vector for future reference + */ + int16_t mv1[2]; +} VAMotionVector; + +/** Type of a message callback, used for both error and info log. */ +typedef void (*VAMessageCallback)(void *user_context, const char *message); + +/** + * Set the callback for error messages, or NULL for no logging. + * Returns the previous one, or NULL if it was disabled. + */ +VAMessageCallback vaSetErrorCallback(VADisplay dpy, VAMessageCallback callback, void *user_context); + +/** + * Set the callback for info messages, or NULL for no logging. + * Returns the previous one, or NULL if it was disabled. + */ +VAMessageCallback vaSetInfoCallback(VADisplay dpy, VAMessageCallback callback, void *user_context); + +/** + * Initialization: + * A display must be obtained by calling vaGetDisplay() before calling + * vaInitialize() and other functions. This connects the API to the + * native window system. + * For X Windows, native_dpy would be from XOpenDisplay() + */ +typedef void* VANativeDisplay; /* window system dependent */ + +int vaDisplayIsValid(VADisplay dpy); + +/** + * Set the override driver name instead of queried driver driver. + */ +VAStatus vaSetDriverName(VADisplay dpy, + char *driver_name + ); + +/** + * Initialize the library + */ +VAStatus vaInitialize( + VADisplay dpy, + int *major_version, /* out */ + int *minor_version /* out */ +); + +/** + * After this call, all library internal resources will be cleaned up + */ +VAStatus vaTerminate( + VADisplay dpy +); + +/** + * vaQueryVendorString returns a pointer to a zero-terminated string + * describing some aspects of the VA implemenation on a specific + * hardware accelerator. 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" + */ +const char *vaQueryVendorString( + VADisplay dpy +); + +typedef int (*VAPrivFunc)(void); + +/** + * Return a function pointer given a function name in the library. + * This allows private interfaces into the library + */ +VAPrivFunc vaGetLibFunc( + VADisplay dpy, + const char *func +); + +/** Currently defined profiles */ +typedef enum { + /** \brief Profile ID used for video processing. */ + VAProfileNone = -1, + VAProfileMPEG2Simple = 0, + VAProfileMPEG2Main = 1, + VAProfileMPEG4Simple = 2, + VAProfileMPEG4AdvancedSimple = 3, + VAProfileMPEG4Main = 4, + VAProfileH264Baseline va_deprecated_enum = 5, + VAProfileH264Main = 6, + VAProfileH264High = 7, + VAProfileVC1Simple = 8, + VAProfileVC1Main = 9, + VAProfileVC1Advanced = 10, + VAProfileH263Baseline = 11, + VAProfileJPEGBaseline = 12, + VAProfileH264ConstrainedBaseline = 13, + VAProfileVP8Version0_3 = 14, + VAProfileH264MultiviewHigh = 15, + VAProfileH264StereoHigh = 16, + VAProfileHEVCMain = 17, + VAProfileHEVCMain10 = 18, + VAProfileVP9Profile0 = 19, + VAProfileVP9Profile1 = 20, + VAProfileVP9Profile2 = 21, + VAProfileVP9Profile3 = 22, + VAProfileHEVCMain12 = 23, + VAProfileHEVCMain422_10 = 24, + VAProfileHEVCMain422_12 = 25, + VAProfileHEVCMain444 = 26, + VAProfileHEVCMain444_10 = 27, + VAProfileHEVCMain444_12 = 28, + VAProfileHEVCSccMain = 29, + VAProfileHEVCSccMain10 = 30, + VAProfileHEVCSccMain444 = 31, + VAProfileAV1Profile0 = 32, + VAProfileAV1Profile1 = 33, + VAProfileHEVCSccMain444_10 = 34, + /** \brief Profile ID used for protected video playback. */ + VAProfileProtected = 35, + VAProfileH264High10 = 36, + VAProfileVVCMain10 = 37, + VAProfileVVCMultilayerMain10 = 38, + VAProfileAV1Profile2 = 39, + VAProfileH264High422 = 40 +} VAProfile; + +/** + * Currently defined entrypoints + */ +typedef enum { + VAEntrypointVLD = 1, + VAEntrypointIZZ = 2, + VAEntrypointIDCT = 3, + VAEntrypointMoComp = 4, + VAEntrypointDeblocking = 5, + VAEntrypointEncSlice = 6, /* slice level encode */ + VAEntrypointEncPicture = 7, /* pictuer encode, JPEG, etc */ + /* + * For an implementation that supports a low power/high performance variant + * for slice level encode, it can choose to expose the + * VAEntrypointEncSliceLP entrypoint. Certain encoding tools may not be + * available with this entrypoint (e.g. interlace, MBAFF) and the + * application can query the encoding configuration attributes to find + * out more details if this entrypoint is supported. + */ + VAEntrypointEncSliceLP = 8, + VAEntrypointVideoProc = 10, /**< Video pre/post-processing. */ + /** + * \brief VAEntrypointFEI + * + * The purpose of FEI (Flexible Encoding Infrastructure) is to allow applications to + * have more controls and trade off quality for speed with their own IPs. + * The application can optionally provide input to ENC for extra encode control + * and get the output from ENC. Application can chose to modify the ENC + * output/PAK input during encoding, but the performance impact is significant. + * + * On top of the existing buffers for normal encode, there will be + * one extra input buffer (VAEncMiscParameterFEIFrameControl) and + * three extra output buffers (VAEncFEIMVBufferType, VAEncFEIMBModeBufferType + * and VAEncFEIDistortionBufferType) for VAEntrypointFEI entry function. + * If separate PAK is set, two extra input buffers + * (VAEncFEIMVBufferType, VAEncFEIMBModeBufferType) are needed for PAK input. + **/ + VAEntrypointFEI = 11, + /** + * \brief VAEntrypointStats + * + * A pre-processing function for getting some statistics and motion vectors is added, + * and some extra controls for Encode pipeline are provided. The application can + * optionally call the statistics function to get motion vectors and statistics like + * variances, distortions before calling Encode function via this entry point. + * + * Checking whether Statistics is supported can be performed with vaQueryConfigEntrypoints(). + * If Statistics entry point is supported, then the list of returned entry-points will + * include #VAEntrypointStats. Supported pixel format, maximum resolution and statistics + * specific attributes can be obtained via normal attribute query. One input buffer + * (VAStatsStatisticsParameterBufferType) and one or two output buffers + * (VAStatsStatisticsBufferType, VAStatsStatisticsBottomFieldBufferType (for interlace only) + * and VAStatsMVBufferType) are needed for this entry point. + **/ + VAEntrypointStats = 12, + /** + * \brief VAEntrypointProtectedTEEComm + * + * A function for communicating with TEE (Trusted Execution Environment). + **/ + VAEntrypointProtectedTEEComm = 13, + /** + * \brief VAEntrypointProtectedContent + * + * A function for protected content to decrypt encrypted content. + **/ + VAEntrypointProtectedContent = 14, +} VAEntrypoint; + +/** Currently defined configuration attribute types */ +typedef enum { + VAConfigAttribRTFormat = 0, + VAConfigAttribSpatialResidual = 1, + VAConfigAttribSpatialClipping = 2, + VAConfigAttribIntraResidual = 3, + VAConfigAttribEncryption = 4, + VAConfigAttribRateControl = 5, + + /** @name Attributes for decoding */ + /**@{*/ + /** + * \brief Slice Decoding mode. Read/write. + * + * This attribute determines what mode the driver supports for slice + * decoding, through vaGetConfigAttributes(); and what mode the user + * will be providing to the driver, through vaCreateConfig(), if the + * driver supports those. If this attribute is not set by the user then + * it is assumed that VA_DEC_SLICE_MODE_NORMAL mode is used. + * + * See \c VA_DEC_SLICE_MODE_xxx for the list of slice decoding modes. + */ + VAConfigAttribDecSliceMode = 6, + /** + * \brief JPEG decoding attribute. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * JPEG implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValDecJPEG union. + */ + VAConfigAttribDecJPEG = 7, + /** + * \brief Decode processing support. Read/write. + * + * This attribute determines if the driver supports video processing + * with decoding using the decoding context in a single call, through + * vaGetConfigAttributes(); and if the user may use this feature, + * through vaCreateConfig(), if the driver supports the user scenario. + * The user will essentially create a regular decode VAContext. Therefore, + * the parameters of vaCreateContext() such as picture_width, picture_height + * and render_targets are in relation to the decode output parameters + * (not processing output parameters) as normal. + * If this attribute is not set by the user then it is assumed that no + * extra processing is done after decoding for this decode context. + * + * Since essentially the application is creating a decoder config and context, + * all function calls that take in the config (e.g. vaQuerySurfaceAttributes()) + * or context are in relation to the decoder, except those video processing + * function specified in the next paragraph. + * + * Once the decode config and context are created, the user must further + * query the supported processing filters using vaQueryVideoProcFilters(), + * vaQueryVideoProcFilterCaps(), vaQueryVideoProcPipelineCaps() by specifying + * the created decode context. The user must provide processing information + * and extra processing output surfaces as "additional_outputs" to the driver + * through VAProcPipelineParameterBufferType. The render_target specified + * at vaBeginPicture() time refers to the decode output surface. The + * target surface for the output of processing needs to be a different + * surface since the decode process requires the original reconstructed buffer. + * The "surface" member of VAProcPipelineParameterBuffer should be set to the + * same as "render_target" set in vaBeginPicture(), but the driver may choose + * to ignore this parameter. + */ + VAConfigAttribDecProcessing = 8, + /** @name Attributes for encoding */ + /**@{*/ + /** + * \brief Packed headers mode. Read/write. + * + * This attribute determines what packed headers the driver supports, + * through vaGetConfigAttributes(); and what packed headers the user + * will be providing to the driver, through vaCreateConfig(), if the + * driver supports those. + * + * See \c VA_ENC_PACKED_HEADER_xxx for the list of packed headers. + */ + VAConfigAttribEncPackedHeaders = 10, + /** + * \brief Interlaced mode. Read/write. + * + * This attribute determines what kind of interlaced encoding mode + * the driver supports. + * + * See \c VA_ENC_INTERLACED_xxx for the list of interlaced modes. + */ + VAConfigAttribEncInterlaced = 11, + /** + * \brief Maximum number of reference frames. Read-only. + * + * This attribute determines the maximum number of reference + * frames supported for encoding. + * + * Note: for H.264 encoding, the value represents the maximum number + * of reference frames for both the reference picture list 0 (bottom + * 16 bits) and the reference picture list 1 (top 16 bits). + */ + VAConfigAttribEncMaxRefFrames = 13, + /** + * \brief Maximum number of slices per frame. Read-only. + * + * This attribute determines the maximum number of slices the + * driver can support to encode a single frame. + */ + VAConfigAttribEncMaxSlices = 14, + /** + * \brief Slice structure. Read-only. + * + * This attribute determines slice structures supported by the + * driver for encoding. This attribute is a hint to the user so + * that he can choose a suitable surface size and how to arrange + * the encoding process of multiple slices per frame. + * + * More specifically, for H.264 encoding, this attribute + * determines the range of accepted values to + * VAEncSliceParameterBufferH264::macroblock_address and + * VAEncSliceParameterBufferH264::num_macroblocks. + * + * See \c VA_ENC_SLICE_STRUCTURE_xxx for the supported slice + * structure types. + */ + VAConfigAttribEncSliceStructure = 15, + /** + * \brief Macroblock information. Read-only. + * + * This attribute determines whether the driver supports extra + * encoding information per-macroblock. e.g. QP. + * + * More specifically, for H.264 encoding, if the driver returns a non-zero + * value for this attribute, this means the application can create + * additional #VAEncMacroblockParameterBufferH264 buffers referenced + * through VAEncSliceParameterBufferH264::macroblock_info. + */ + VAConfigAttribEncMacroblockInfo = 16, + /** + * \brief Maximum picture width. Read-only. + * + * This attribute determines the maximum picture width the driver supports + * for a given configuration. + */ + VAConfigAttribMaxPictureWidth = 18, + /** + * \brief Maximum picture height. Read-only. + * + * This attribute determines the maximum picture height the driver supports + * for a given configuration. + */ + VAConfigAttribMaxPictureHeight = 19, + /** + * \brief JPEG encoding attribute. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * JPEG implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncJPEG union. + */ + VAConfigAttribEncJPEG = 20, + /** + * \brief Encoding quality range attribute. Read-only. + * + * This attribute conveys whether the driver supports different quality level settings + * for encoding. A value less than or equal to 1 means that the encoder only has a single + * quality setting, and a value greater than 1 represents the number of quality levels + * that can be configured. e.g. a value of 2 means there are two distinct quality levels. + */ + VAConfigAttribEncQualityRange = 21, + /** + * \brief Encoding quantization attribute. Read-only. + * + * This attribute conveys whether the driver supports certain types of quantization methods + * for encoding (e.g. trellis). See \c VA_ENC_QUANTIZATION_xxx for the list of quantization methods + */ + VAConfigAttribEncQuantization = 22, + /** + * \brief Encoding intra refresh attribute. Read-only. + * + * This attribute conveys whether the driver supports certain types of intra refresh methods + * for encoding (e.g. adaptive intra refresh or rolling intra refresh). + * See \c VA_ENC_INTRA_REFRESH_xxx for intra refresh methods + */ + VAConfigAttribEncIntraRefresh = 23, + /** + * \brief Encoding skip frame attribute. Read-only. + * + * This attribute conveys whether the driver supports sending skip frame parameters + * (VAEncMiscParameterTypeSkipFrame) to the encoder's rate control, when the user has + * externally skipped frames. + */ + VAConfigAttribEncSkipFrame = 24, + /** + * \brief Encoding region-of-interest (ROI) attribute. Read-only. + * + * This attribute conveys whether the driver supports region-of-interest (ROI) encoding, + * based on user provided ROI rectangles. The attribute value is partitioned into fields + * as defined in the VAConfigAttribValEncROI union. + * + * If ROI encoding is supported, the ROI information is passed to the driver using + * VAEncMiscParameterTypeROI. + */ + VAConfigAttribEncROI = 25, + /** + * \brief Encoding extended rate control attribute. Read-only. + * + * This attribute conveys whether the driver supports any extended rate control features + * The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncRateControlExt union. + */ + VAConfigAttribEncRateControlExt = 26, + /** + * \brief Processing rate reporting attribute. Read-only. + * + * This attribute conveys whether the driver supports reporting of + * encode/decode processing rate based on certain set of parameters + * (i.e. levels, I frame internvals) for a given configuration. + * If this is supported, vaQueryProcessingRate() can be used to get + * encode or decode processing rate. + * See \c VA_PROCESSING_RATE_xxx for encode/decode processing rate + */ + VAConfigAttribProcessingRate = 27, + /** + * \brief Encoding dirty rectangle. Read-only. + * + * This attribute conveys whether the driver supports dirty rectangle. + * encoding, based on user provided ROI rectangles which indicate the rectangular areas + * where the content has changed as compared to the previous picture. The regions of the + * picture that are not covered by dirty rect rectangles are assumed to have not changed + * compared to the previous picture. The encoder may do some optimizations based on + * this information. The attribute value returned indicates the number of regions that + * are supported. e.g. A value of 0 means dirty rect encoding is not supported. If dirty + * rect encoding is supported, the ROI information is passed to the driver using + * VAEncMiscParameterTypeDirtyRect. + */ + VAConfigAttribEncDirtyRect = 28, + /** + * \brief Parallel Rate Control (hierachical B) attribute. Read-only. + * + * This attribute conveys whether the encoder supports parallel rate control. + * It is a integer value 0 - unsupported, > 0 - maximum layer supported. + * This is the way when hireachical B frames are encoded, multiple independent B frames + * on the same layer may be processed at same time. If supported, app may enable it by + * setting enable_parallel_brc in VAEncMiscParameterRateControl,and the number of B frames + * per layer per GOP will be passed to driver through VAEncMiscParameterParallelRateControl + * structure.Currently three layers are defined. + */ + VAConfigAttribEncParallelRateControl = 29, + /** + * \brief Dynamic Scaling Attribute. Read-only. + * + * This attribute conveys whether encoder is capable to determine dynamic frame + * resolutions adaptive to bandwidth utilization and processing power, etc. + * It is a boolean value 0 - unsupported, 1 - supported. + * If it is supported,for VP9, suggested frame resolution can be retrieved from VACodedBufferVP9Status. + */ + VAConfigAttribEncDynamicScaling = 30, + /** + * \brief frame size tolerance support + * it indicates the tolerance of frame size + */ + VAConfigAttribFrameSizeToleranceSupport = 31, + /** + * \brief Encode function type for FEI. + * + * This attribute conveys whether the driver supports different function types for encode. + * It can be VA_FEI_FUNCTION_ENC, VA_FEI_FUNCTION_PAK, or VA_FEI_FUNCTION_ENC_PAK. Currently + * it is for FEI entry point only. + * Default is VA_FEI_FUNCTION_ENC_PAK. + */ + VAConfigAttribFEIFunctionType = 32, + /** + * \brief Maximum number of FEI MV predictors. Read-only. + * + * This attribute determines the maximum number of MV predictors the driver + * can support to encode a single frame. 0 means no MV predictor is supported. + * Currently it is for FEI entry point only. + */ + VAConfigAttribFEIMVPredictors = 33, + /** + * \brief Statistics attribute. Read-only. + * + * This attribute exposes a number of capabilities of the VAEntrypointStats entry + * point. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValStats union. Currently it is for VAEntrypointStats only. + */ + VAConfigAttribStats = 34, + /** + * \brief Tile Support Attribute. Read-only. + * + * This attribute conveys whether encoder is capable to support tiles. + * If not supported, the tile related parameters sent to encoder, such as + * tiling structure, should be ignored. 0 - unsupported, 1 - supported. + */ + VAConfigAttribEncTileSupport = 35, + /** + * \brief whether accept rouding setting from application. Read-only. + * This attribute is for encode quality, if it is report, + * application can change the rounding setting by VAEncMiscParameterTypeCustomRoundingControl + */ + VAConfigAttribCustomRoundingControl = 36, + /** + * \brief Encoding QP info block size attribute. Read-only. + * This attribute conveys the block sizes that underlying driver + * support for QP info for buffer #VAEncQpBuffer. + */ + VAConfigAttribQPBlockSize = 37, + /** + * \brief encode max frame size attribute. Read-only + * attribute value \c VAConfigAttribValMaxFrameSize represent max frame size support + */ + VAConfigAttribMaxFrameSize = 38, + /** \brief inter frame prediction directrion attribute. Read-only. + * this attribute conveys the prediction direction (backward or forword) for specific config + * the value could be VA_PREDICTION_DIRECTION_XXXX. it can be combined with VAConfigAttribEncMaxRefFrames + * to describe reference list , and the prediction direction. if this attrib is not present,both direction + * should be supported, no restriction. + * for example: normal HEVC encoding , maximum reference frame number in reflist 0 and reflist 1 is deduced + * by VAConfigAttribEncMaxRefFrames. so there are typical P frame, B frame, + * if VAConfigAttribPredictionDirection is also present. it will stipulate prediction direction in both + * reference list. if only one prediction direction present(such as PREVIOUS),all reference frame should be + * previous frame (PoC < current). + */ + VAConfigAttribPredictionDirection = 39, + /** \brief combined submission of multiple frames from different streams, it is optimization for different HW + * implementation, multiple frames encode/decode can improve HW concurrency + */ + VAConfigAttribMultipleFrame = 40, + /** \brief priority setting for the context. Read-Write + * attribute value is \c VAConfigAttribValContextPriority + * this setting also could be update by \c VAContextParameterUpdateBuffer + */ + VAConfigAttribContextPriority = 41, + /** \brief AV1 decoding features. Read-only. + * + * This attribute describes the supported features of an + * AV1 decoder configuration. The value returned uses the + * VAConfigAttribValDecAV1Features type. + */ + VAConfigAttribDecAV1Features = 42, + /** \brief TEE could be any HW secure device. Read-only */ + VAConfigAttribTEEType = 43, + /** \brief TEE type client is a specific module supporting specific functions in TEE. Read-only*/ + VAConfigAttribTEETypeClient = 44, + /** + * \brief Cipher algorithm of the protected content session. + * + * This attribute specifies the cipher algorithm of the protected content session. It + * could be \c VA_PC_CIPHER_AES, etc.... + */ + VAConfigAttribProtectedContentCipherAlgorithm = 45, + /** + * \brief Cipher block size of the protected content session. + * + * This attribute specifies the block size of the protected content session. It could be + * \c VA_PC_BLOCK_SIZE_128, \c VA_PC_BLOCK_SIZE_192, or \c VA_PC_BLOCK_SIZE_256, etc.... + */ + VAConfigAttribProtectedContentCipherBlockSize = 46, + /** + * \brief Cipher mode of the protected content session. + * + * This attribute specifies the cipher mode of the protected content session. It could + * be \c VA_PC_CIPHER_MODE_ECB, \c VA_PC_CIPHER_MODE_CBC, \c VA_PC_CIPHER_MODE_CTR, etc... + */ + VAConfigAttribProtectedContentCipherMode = 47, + /** + * \brief Decryption sample type of the protected content session. + * + * This attribute specifies the decryption sample type of the protected content session. + * It could be \c VA_PC_SAMPLE_TYPE_FULLSAMPLE or \c VA_PC_SAMPLE_TYPE_SUBSAMPLE. + */ + VAConfigAttribProtectedContentCipherSampleType = 48, + /** + * \brief Special usage attribute of the protected session. + * + * The attribute specifies the flow for the protected session could be used. For + * example, it could be \c VA_PC_USAGE_DEFAULT, \c VA_PC_USAGE_WIDEVINE, etc.... + */ + VAConfigAttribProtectedContentUsage = 49, + + /** \brief HEVC/H.265 encoding features. Read-only. + * + * This attribute describes the supported features of an + * HEVC/H.265 encoder configuration. The value returned uses the + * VAConfigAttribValEncHEVCFeatures type. + * + * If this attribute is supported by a driver then it must also + * support the VAConfigAttribEncHEVCBlockSizes attribute. + */ + VAConfigAttribEncHEVCFeatures = 50, + /** \brief HEVC/H.265 encoding block sizes. Read-only. + * + * This attribute describes the supported coding tree and transform + * block sizes of an HEVC/H.265 encoder configuration. The value + * returned uses the VAConfigAttribValEncHEVCBlockSizes type. + * + * If this attribute is supported by a driver then it must also + * support the VAConfigAttribEncHEVCFeatures attribute. + */ + VAConfigAttribEncHEVCBlockSizes = 51, + /** + * \brief AV1 encoding attribute. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * AV1 implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncAV1 union. + */ + VAConfigAttribEncAV1 = 52, + /** + * \brief AV1 encoding attribute extend1. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * AV1 implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncAV1Ext1 union. + */ + VAConfigAttribEncAV1Ext1 = 53, + /** + * \brief AV1 encoding attribute extend2. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * AV1 implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncAV1Ext2 union. + */ + VAConfigAttribEncAV1Ext2 = 54, + /** \brief Settings per block attribute for Encoding. Read-only. + * + * This attribute describes whether to support delta qp per block, + * the supported size of delta qp block and the size of delta QP in bytes. + * The value returned uses the VAConfigAttribValEncPerBlockControl type. + */ + VAConfigAttribEncPerBlockControl = 55, + /** + * \brief Maximum number of tile rows. Read-only. + * + * This attribute determines the maximum number of tile + * rows supported for encoding with tile support. + */ + VAConfigAttribEncMaxTileRows = 56, + /** + * \brief Maximum number of tile cols. Read-only. + * + * This attribute determines the maximum number of tile + * columns supported for encoding with tile support. + */ + VAConfigAttribEncMaxTileCols = 57, + /** + * \brief VP9 encoding attribute. Read-only. + * + * This attribute exposes a number of capabilities of the underlying + * VP9 implementation. The attribute value is partitioned into fields as defined in the + * VAConfigAttribValEncVP9 union. + */ + VAConfigAttribEncVP9 = 58, + /**@}*/ + VAConfigAttribTypeMax +} VAConfigAttribType; + +/** + * Configuration attributes + * If there is more than one value for an attribute, a default + * value will be assigned to the attribute if the client does not + * specify the attribute when creating a configuration + */ +typedef struct _VAConfigAttrib { + VAConfigAttribType type; + uint32_t value; /* OR'd flags (bits) for this attribute */ +} VAConfigAttrib; + +/* Attribute values for VAConfigAttribRTFormat. */ + +#define VA_RT_FORMAT_YUV420 0x00000001 ///< YUV 4:2:0 8-bit. +#define VA_RT_FORMAT_YUV422 0x00000002 ///< YUV 4:2:2 8-bit. +#define VA_RT_FORMAT_YUV444 0x00000004 ///< YUV 4:4:4 8-bit. +#define VA_RT_FORMAT_YUV411 0x00000008 ///< YUV 4:1:1 8-bit. +#define VA_RT_FORMAT_YUV400 0x00000010 ///< Greyscale 8-bit. +#define VA_RT_FORMAT_YUV420_10 0x00000100 ///< YUV 4:2:0 10-bit. +#define VA_RT_FORMAT_YUV422_10 0x00000200 ///< YUV 4:2:2 10-bit. +#define VA_RT_FORMAT_YUV444_10 0x00000400 ///< YUV 4:4:4 10-bit. +#define VA_RT_FORMAT_YUV420_12 0x00001000 ///< YUV 4:2:0 12-bit. +#define VA_RT_FORMAT_YUV422_12 0x00002000 ///< YUV 4:2:2 12-bit. +#define VA_RT_FORMAT_YUV444_12 0x00004000 ///< YUV 4:4:4 12-bit. + +#define VA_RT_FORMAT_RGB16 0x00010000 ///< Packed RGB, 16 bits per pixel. +#define VA_RT_FORMAT_RGB32 0x00020000 ///< Packed RGB, 32 bits per pixel, 8 bits per colour sample. +#define VA_RT_FORMAT_RGBP 0x00100000 ///< Planar RGB, 8 bits per sample. +#define VA_RT_FORMAT_RGB32_10 0x00200000 ///< Packed RGB, 32 bits per pixel, 10 bits per colour sample. + +#define VA_RT_FORMAT_PROTECTED 0x80000000 + +#define VA_RT_FORMAT_RGB32_10BPP VA_RT_FORMAT_RGB32_10 ///< @deprecated use VA_RT_FORMAT_RGB32_10 instead. +#define VA_RT_FORMAT_YUV420_10BPP VA_RT_FORMAT_YUV420_10 ///< @deprecated use VA_RT_FORMAT_YUV420_10 instead. + +/** @name Attribute values for VAConfigAttribRateControl */ +/**@{*/ +/** \brief Driver does not support any form of rate control. */ +#define VA_RC_NONE 0x00000001 +/** \brief Constant bitrate. */ +#define VA_RC_CBR 0x00000002 +/** \brief Variable bitrate. */ +#define VA_RC_VBR 0x00000004 +/** \brief Video conference mode. */ +#define VA_RC_VCM 0x00000008 +/** \brief Constant QP. */ +#define VA_RC_CQP 0x00000010 +/** \brief Variable bitrate with peak rate higher than average bitrate. */ +#define VA_RC_VBR_CONSTRAINED 0x00000020 +/** \brief Intelligent Constant Quality. Provided an initial ICQ_quality_factor, + * adjusts QP at a frame and MB level based on motion to improve subjective quality. */ +#define VA_RC_ICQ 0x00000040 +/** \brief Macroblock based rate control. Per MB control is decided + * internally in the encoder. It may be combined with other RC modes, except CQP. */ +#define VA_RC_MB 0x00000080 +/** \brief Constant Frame Size, it is used for small tolerent */ +#define VA_RC_CFS 0x00000100 +/** \brief Parallel BRC, for hierachical B. + * + * For hierachical B, B frames can be refered by other B frames. + * Currently three layers of hierachy are defined: + * B0 - regular B, no reference to other B frames. + * B1 - reference to only I, P and regular B0 frames. + * B2 - reference to any other frames, including B1. + * In Hierachical B structure, B frames on the same layer can be processed + * simultaneously. And BRC would adjust accordingly. This is so called + * Parallel BRC. */ +#define VA_RC_PARALLEL 0x00000200 +/** \brief Quality defined VBR + * Use Quality factor to determine the good enough QP for each MB such that + * good enough quality can be obtained without waste of bits + * for this BRC mode, you must set all legacy VBR parameters + * and reuse quality_factor in \c VAEncMiscParameterRateControl + * */ +#define VA_RC_QVBR 0x00000400 +/** \brief Average VBR + * Average variable bitrate control algorithm focuses on overall encoding + * quality while meeting the specified target bitrate, within the accuracy + * range, after a convergence period. + * bits_per_second in VAEncMiscParameterRateControl is target bitrate for AVBR. + * Convergence is specified in the unit of frame. + * window_size in VAEncMiscParameterRateControl is equal to convergence for AVBR. + * Accuracy is in the range of [1,100], 1 means one percent, and so on. + * target_percentage in VAEncMiscParameterRateControl is equal to accuracy for AVBR. + * */ +#define VA_RC_AVBR 0x00000800 +/** \brief Transport Controlled BRC + * Specific bitrate control for real time streaming. + * TCBRC can instantly react to channel change to remove or significantly reduce the delay. + * Application (transport) provides channel feedback to driver through TargetFrameSize. + * When channel condition is very good (almost no constraint on instant frame size), + * the app should set target frame size as zero. Otherwise, channel capacity divided by fps + * should be used. + * */ +#define VA_RC_TCBRC 0x00001000 + +/**@}*/ + +/** @name Attribute values for VAConfigAttribDecSliceMode */ +/**@{*/ +/** \brief Driver supports normal mode for slice decoding */ +#define VA_DEC_SLICE_MODE_NORMAL 0x00000001 +/** \brief Driver supports base mode for slice decoding */ +#define VA_DEC_SLICE_MODE_BASE 0x00000002 + +/** @name Attribute values for VAConfigAttribDecJPEG */ +/**@{*/ +typedef union _VAConfigAttribValDecJPEG { + struct { + /** \brief Set to (1 << VA_ROTATION_xxx) for supported rotation angles. */ + uint32_t rotation : 4; + /** \brief set to 1 for crop and partial decode support, 0 if not supported */ + uint32_t crop : 1; + /** \brief Reserved for future use. */ + uint32_t reserved : 27; + } bits; + uint32_t value; +} VAConfigAttribValDecJPEG; +/** @name Attribute values for VAConfigAttribDecProcessing */ +/**@{*/ +/** \brief No decoding + processing in a single decoding call. */ +#define VA_DEC_PROCESSING_NONE 0x00000000 +/** \brief Decode + processing in a single decoding call. */ +#define VA_DEC_PROCESSING 0x00000001 +/**@}*/ + +/** @name Attribute values for VAConfigAttribEncPackedHeaders */ +/**@{*/ +/** \brief Driver does not support any packed headers mode. */ +#define VA_ENC_PACKED_HEADER_NONE 0x00000000 +/** + * \brief Driver supports packed sequence headers. e.g. SPS for H.264. + * + * Application must provide it to driver once this flag is returned through + * vaGetConfigAttributes() + */ +#define VA_ENC_PACKED_HEADER_SEQUENCE 0x00000001 +/** + * \brief Driver supports packed picture headers. e.g. PPS for H.264. + * + * Application must provide it to driver once this falg is returned through + * vaGetConfigAttributes() + */ +#define VA_ENC_PACKED_HEADER_PICTURE 0x00000002 +/** + * \brief Driver supports packed slice headers. e.g. slice_header() for H.264. + * + * Application must provide it to driver once this flag is returned through + * vaGetConfigAttributes() + */ +#define VA_ENC_PACKED_HEADER_SLICE 0x00000004 +/** + * \brief Driver supports misc packed headers. e.g. SEI for H.264. + * + * @deprecated + * This is a deprecated packed header flag, All applications can use + * \c VA_ENC_PACKED_HEADER_RAW_DATA to pass the corresponding packed + * header data buffer to the driver + */ +#define VA_ENC_PACKED_HEADER_MISC 0x00000008 +/** \brief Driver supports raw packed header, see VAEncPackedHeaderRawData */ +#define VA_ENC_PACKED_HEADER_RAW_DATA 0x00000010 +/**@}*/ + +/** @name Attribute values for VAConfigAttribEncInterlaced */ +/**@{*/ +/** \brief Driver does not support interlaced coding. */ +#define VA_ENC_INTERLACED_NONE 0x00000000 +/** \brief Driver supports interlaced frame coding. */ +#define VA_ENC_INTERLACED_FRAME 0x00000001 +/** \brief Driver supports interlaced field coding. */ +#define VA_ENC_INTERLACED_FIELD 0x00000002 +/** \brief Driver supports macroblock adaptive frame field coding. */ +#define VA_ENC_INTERLACED_MBAFF 0x00000004 +/** \brief Driver supports picture adaptive frame field coding. */ +#define VA_ENC_INTERLACED_PAFF 0x00000008 +/**@}*/ + +/** @name Attribute values for VAConfigAttribEncSliceStructure */ +/**@{*/ +/** \brief Driver supports a power-of-two number of rows per slice. */ +#define VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS 0x00000001 +/** \brief Driver supports an arbitrary number of macroblocks per slice. */ +#define VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS 0x00000002 +/** \brief Driver support 1 row per slice */ +#define VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS 0x00000004 +/** \brief Driver support max encoded slice size per slice */ +#define VA_ENC_SLICE_STRUCTURE_MAX_SLICE_SIZE 0x00000008 +/** \brief Driver supports an arbitrary number of rows per slice. */ +#define VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS 0x00000010 +/** \brief Driver supports any number of rows per slice but they must be the same +* for all slices except for the last one, which must be equal or smaller +* to the previous slices. */ +#define VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS 0x00000020 +/**@}*/ + +/** \brief Attribute value for VAConfigAttribMaxFrameSize */ +typedef union _VAConfigAttribValMaxFrameSize { + struct { + /** \brief support max frame size + * if max_frame_size == 1, VAEncMiscParameterTypeMaxFrameSize/VAEncMiscParameterBufferMaxFrameSize + * could be used to set the frame size, if multiple_pass also equal 1, VAEncMiscParameterTypeMultiPassFrameSize + * VAEncMiscParameterBufferMultiPassFrameSize could be used to set frame size and pass information + */ + uint32_t max_frame_size : 1; + /** \brief multiple_pass support */ + uint32_t multiple_pass : 1; + /** \brief reserved bits for future, must be zero*/ + uint32_t reserved : 30; + } bits; + uint32_t value; +} VAConfigAttribValMaxFrameSize; + +/** \brief Attribute value for VAConfigAttribEncJPEG */ +typedef union _VAConfigAttribValEncJPEG { + struct { + /** \brief set to 1 for arithmatic coding. */ + uint32_t arithmatic_coding_mode : 1; + /** \brief set to 1 for progressive dct. */ + uint32_t progressive_dct_mode : 1; + /** \brief set to 1 for non-interleaved. */ + uint32_t non_interleaved_mode : 1; + /** \brief set to 1 for differential. */ + uint32_t differential_mode : 1; + uint32_t max_num_components : 3; + uint32_t max_num_scans : 4; + uint32_t max_num_huffman_tables : 3; + uint32_t max_num_quantization_tables : 3; + } bits; + uint32_t value; +} VAConfigAttribValEncJPEG; + +/** @name Attribute values for VAConfigAttribEncQuantization */ +/**@{*/ +/** \brief Driver does not support special types of quantization */ +#define VA_ENC_QUANTIZATION_NONE 0x00000000 +/** \brief Driver supports trellis quantization */ +#define VA_ENC_QUANTIZATION_TRELLIS_SUPPORTED 0x00000001 +/**@}*/ + +/** @name Attribute values for VAConfigAttribPredictionDirection */ +/**@{*/ +/** \brief Driver support forward reference frame (inter frame for vpx, P frame for H26x MPEG) + * can work with the VAConfigAttribEncMaxRefFrames. for example: low delay B frame of HEVC. + * these value can be OR'd together. typical value should be VA_PREDICTION_DIRECTION_PREVIOUS + * or VA_PREDICTION_DIRECTION_PREVIOUS | VA_PREDICTION_DIRECTION_FUTURE, theoretically, there + * are no stream only include future reference frame. + */ +#define VA_PREDICTION_DIRECTION_PREVIOUS 0x00000001 +/** \brief Driver support backward prediction frame/slice */ +#define VA_PREDICTION_DIRECTION_FUTURE 0x00000002 +/** \brief Dirver require both reference list must be not empty for inter frame */ +#define VA_PREDICTION_DIRECTION_BI_NOT_EMPTY 0x00000004 +/**@}*/ + +/** @name Attribute values for VAConfigAttribEncIntraRefresh */ +/**@{*/ +/** \brief Driver does not support intra refresh */ +#define VA_ENC_INTRA_REFRESH_NONE 0x00000000 +/** \brief Driver supports column based rolling intra refresh */ +#define VA_ENC_INTRA_REFRESH_ROLLING_COLUMN 0x00000001 +/** \brief Driver supports row based rolling intra refresh */ +#define VA_ENC_INTRA_REFRESH_ROLLING_ROW 0x00000002 +/** \brief Driver supports adaptive intra refresh */ +#define VA_ENC_INTRA_REFRESH_ADAPTIVE 0x00000010 +/** \brief Driver supports cyclic intra refresh */ +#define VA_ENC_INTRA_REFRESH_CYCLIC 0x00000020 +/** \brief Driver supports intra refresh of P frame*/ +#define VA_ENC_INTRA_REFRESH_P_FRAME 0x00010000 +/** \brief Driver supports intra refresh of B frame */ +#define VA_ENC_INTRA_REFRESH_B_FRAME 0x00020000 +/** \brief Driver supports intra refresh of multiple reference encoder */ +#define VA_ENC_INTRA_REFRESH_MULTI_REF 0x00040000 + +/**@}*/ + +/** \brief Attribute value for VAConfigAttribEncROI */ +typedef union _VAConfigAttribValEncROI { + struct { + /** \brief The number of ROI regions supported, 0 if ROI is not supported. */ + uint32_t num_roi_regions : 8; + /** + * \brief A flag indicates whether ROI priority is supported + * + * \ref roi_rc_priority_support equal to 1 specifies the underlying driver supports + * ROI priority when VAConfigAttribRateControl != VA_RC_CQP, user can use \c roi_value + * in #VAEncROI to set ROI priority. \ref roi_rc_priority_support equal to 0 specifies + * the underlying driver doesn't support ROI priority. + * + * User should ignore \ref roi_rc_priority_support when VAConfigAttribRateControl == VA_RC_CQP + * because ROI delta QP is always required when VAConfigAttribRateControl == VA_RC_CQP. + */ + uint32_t roi_rc_priority_support : 1; + /** + * \brief A flag indicates whether ROI delta QP is supported + * + * \ref roi_rc_qp_delta_support equal to 1 specifies the underlying driver supports + * ROI delta QP when VAConfigAttribRateControl != VA_RC_CQP, user can use \c roi_value + * in #VAEncROI to set ROI delta QP. \ref roi_rc_qp_delta_support equal to 0 specifies + * the underlying driver doesn't support ROI delta QP. + * + * User should ignore \ref roi_rc_qp_delta_support when VAConfigAttribRateControl == VA_RC_CQP + * because ROI delta QP is always required when VAConfigAttribRateControl == VA_RC_CQP. + */ + uint32_t roi_rc_qp_delta_support : 1; + uint32_t reserved : 22; + } bits; + uint32_t value; +} VAConfigAttribValEncROI; + +/** \brief Attribute value for VAConfigAttribEncRateControlExt */ +typedef union _VAConfigAttribValEncRateControlExt { + struct { + /** + * \brief The maximum number of temporal layers minus 1 + * + * \ref max_num_temporal_layers_minus1 plus 1 specifies the maximum number of temporal + * layers that supported by the underlying driver. \ref max_num_temporal_layers_minus1 + * equal to 0 implies the underlying driver doesn't support encoding with temporal layer. + */ + uint32_t max_num_temporal_layers_minus1 : 8; + + /** + * /brief support temporal layer bit-rate control flag + * + * \ref temporal_layer_bitrate_control_flag equal to 1 specifies the underlying driver + * can support bit-rate control per temporal layer when (#VAConfigAttribRateControl == #VA_RC_CBR || + * #VAConfigAttribRateControl == #VA_RC_VBR). + * + * The underlying driver must set \ref temporal_layer_bitrate_control_flag to 0 when + * \c max_num_temporal_layers_minus1 is equal to 0 + * + * To use bit-rate control per temporal layer, an application must send the right layer + * structure via #VAEncMiscParameterTemporalLayerStructure at the beginning of a coded sequence + * and then followed by #VAEncMiscParameterRateControl and #VAEncMiscParameterFrameRate structures + * for each layer, using the \c temporal_id field as the layer identifier. Otherwise + * the driver doesn't use bitrate control per temporal layer if an application doesn't send the + * layer structure via #VAEncMiscParameterTemporalLayerStructure to the driver. The driver returns + * VA_STATUS_ERROR_INVALID_PARAMETER if an application sends a wrong layer structure or doesn't send + * #VAEncMiscParameterRateControl and #VAEncMiscParameterFrameRate for each layer. + * + * The driver will ignore #VAEncMiscParameterTemporalLayerStructure and the \c temporal_id field + * in #VAEncMiscParameterRateControl and #VAEncMiscParameterFrameRate if + * \ref temporal_layer_bitrate_control_flag is equal to 0 or #VAConfigAttribRateControl == #VA_RC_CQP + */ + uint32_t temporal_layer_bitrate_control_flag : 1; + uint32_t reserved : 23; + } bits; + uint32_t value; +} VAConfigAttribValEncRateControlExt; + +/** \brief Attribute value for VAConfigAttribMultipleFrame*/ +typedef union _VAConfigAttribValMultipleFrame { + struct { + /** \brief max num of concurrent frames from different stream */ + uint32_t max_num_concurrent_frames : 8; + /** \brief indicate whether all stream must support same quality level + * if mixed_quality_level == 0, same quality level setting for multple streams is required + * if mixed_quality_level == 1, different stream can have different quality level*/ + uint32_t mixed_quality_level : 1; + /** \brief reserved bit for future, must be zero */ + uint32_t reserved : 23; + } bits; + uint32_t value; +} VAConfigAttribValMultipleFrame; + +/** brief Attribute value VAConfigAttribValContextPriority */ +typedef union _VAConfigAttribValContextPriority { + struct { + /** \brief the priority , for the Query operation (read) it represents highest priority + * for the set operation (write), value should be [0~highest priority] , 0 is lowest priority*/ + uint32_t priority : 16; + /** \brief reserved bits for future, must be zero*/ + uint32_t reserved : 16; + } bits; + uint32_t value; +} VAConfigAttribValContextPriority; + +/** brief Attribute value VAConfigAttribEncPerBlockControl */ +typedef union _VAConfigAttribValEncPerBlockControl { + struct { + /** \brief whether to support dela qp per block */ + uint32_t delta_qp_support : 1; + /** \brief supported size of delta qp block */ + uint32_t log2_delta_qp_block_size : 4; + /** \brief size of delta qp per block in bytes*/ + uint32_t delta_qp_size_in_bytes : 3; + /** \brief reserved bit for future, must be zero */ + uint32_t reserved : 24; + } bits; + uint32_t value; +} VAConfigAttribValEncPerBlockControl; + +/** @name Attribute values for VAConfigAttribProtectedContentCipherAlgorithm */ +/** \brief AES cipher */ +#define VA_PC_CIPHER_AES 0x00000001 + +/** @name Attribute values for VAConfigAttribProtectedContentCipherBlockSize */ +/** \brief 128 bits block size */ +#define VA_PC_BLOCK_SIZE_128 0x00000001 +/** \brief 192 bits block size */ +#define VA_PC_BLOCK_SIZE_192 0x00000002 +/** \brief 256 bits block size */ +#define VA_PC_BLOCK_SIZE_256 0x00000004 + +/** @name Attribute values for VAConfigAttribProtectedContentCipherMode */ +/** \brief AES ECB */ +#define VA_PC_CIPHER_MODE_ECB 0x00000001 +/** \brief AES CBC */ +#define VA_PC_CIPHER_MODE_CBC 0x00000002 +/** \brief AES CTR */ +#define VA_PC_CIPHER_MODE_CTR 0x00000004 + +/** @name Attribute values for VAConfigAttribProtectedContentCipherSampleType */ +/** \brief Full sample */ +#define VA_PC_SAMPLE_TYPE_FULLSAMPLE 0x00000001 +/** \brief Sub sample */ +#define VA_PC_SAMPLE_TYPE_SUBSAMPLE 0x00000002 + +/** @name Attribute values for VAConfigAttribProtectedContentUsage */ +/** \brief Default usage */ +#define VA_PC_USAGE_DEFAULT 0x00000000 +/** \brief Widevine */ +#define VA_PC_USAGE_WIDEVINE 0x00000001 + +/** @name Attribute values for VAConfigAttribProcessingRate. */ +/**@{*/ +/** \brief Driver does not support processing rate report */ +#define VA_PROCESSING_RATE_NONE 0x00000000 +/** \brief Driver supports encode processing rate report */ +#define VA_PROCESSING_RATE_ENCODE 0x00000001 +/** \brief Driver supports decode processing rate report */ +#define VA_PROCESSING_RATE_DECODE 0x00000002 +/**@}*/ + +/** @name segment ID map block size */ +/**@{*/ +/** \brief each segmentID represent a 16x16 block */ +#define VA_SEGID_BLOCK_16X16 0 +/** \brief each segmentID represent a 32x32 block */ +#define VA_SEGID_BLOCK_32X32 1 +/** \brief each segmentID represent a 64x64 block */ +#define VA_SEGID_BLOCK_64X64 2 +/** \brief each segmentID represent a 8x8 block */ +#define VA_SEGID_BLOCK_8X8 3 +/**@}*/ + +/** + * if an attribute is not applicable for a given + * profile/entrypoint pair, then set the value to the following + */ +#define VA_ATTRIB_NOT_SUPPORTED 0x80000000 + +/** Get maximum number of profiles supported by the implementation */ +int vaMaxNumProfiles( + VADisplay dpy +); + +/** Get maximum number of entrypoints supported by the implementation */ +int vaMaxNumEntrypoints( + VADisplay dpy +); + +/** Get maximum number of attributs supported by the implementation */ +int vaMaxNumConfigAttributes( + VADisplay dpy +); + +/** + * Query supported profiles + * The caller must provide a "profile_list" array that can hold at + * least vaMaxNumProfile() entries. The actual number of profiles + * returned in "profile_list" is returned in "num_profile". + */ +VAStatus vaQueryConfigProfiles( + VADisplay dpy, + VAProfile *profile_list, /* out */ + int *num_profiles /* out */ +); + +/** + * Query supported entrypoints for a given profile + * The caller must provide an "entrypoint_list" array that can hold at + * least vaMaxNumEntrypoints() entries. The actual number of entrypoints + * returned in "entrypoint_list" is returned in "num_entrypoints". + */ +VAStatus vaQueryConfigEntrypoints( + VADisplay dpy, + VAProfile profile, + VAEntrypoint *entrypoint_list, /* out */ + int *num_entrypoints /* out */ +); + +/** + * Get attributes for a given profile/entrypoint pair + * The caller must provide an "attrib_list" with all attributes to be + * retrieved. Upon return, the attributes in "attrib_list" have been + * updated with their value. Unknown attributes or attributes that are + * not supported for the given profile/entrypoint pair will have their + * value set to VA_ATTRIB_NOT_SUPPORTED + */ +VAStatus vaGetConfigAttributes( + VADisplay dpy, + VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, /* in/out */ + int num_attribs +); + +/** Generic ID type, can be re-typed for specific implementation */ +typedef unsigned int VAGenericID; + +typedef VAGenericID VAConfigID; + +/** + * Create a configuration for the video decode/encode/processing pipeline + * it passes in the attribute list that specifies the attributes it cares + * about, with the rest taking default values. + */ +VAStatus vaCreateConfig( + VADisplay dpy, + VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, + int num_attribs, + VAConfigID *config_id /* out */ +); + +/** + * Free resources associdated with a given config + */ +VAStatus vaDestroyConfig( + VADisplay dpy, + VAConfigID config_id +); + +/** + * Query all attributes for a given configuration + * The profile of the configuration is returned in "profile" + * The entrypoint of the configuration is returned in "entrypoint" + * The caller must provide an "attrib_list" array that can hold at least + * vaMaxNumConfigAttributes() entries. The actual number of attributes + * returned in "attrib_list" is returned in "num_attribs" + */ +VAStatus vaQueryConfigAttributes( + VADisplay dpy, + VAConfigID config_id, + VAProfile *profile, /* out */ + VAEntrypoint *entrypoint, /* out */ + VAConfigAttrib *attrib_list,/* out */ + int *num_attribs /* out */ +); + + +/** + * Contexts and Surfaces + * + * Context represents a "virtual" video decode, encode or video processing + * pipeline. Surfaces are render targets for a given context. The data in the + * surfaces are not accessible to the client except if derived image is supported + * and the internal data format of the surface is implementation specific. + * + * Surfaces are provided as a hint of what surfaces will be used when the context + * is created through vaCreateContext(). A surface may be used by different contexts + * at the same time as soon as application can make sure the operations are synchronized + * between different contexts, e.g. a surface is used as the output of a decode context + * and the input of a video process context. Surfaces can only be destroyed after all + * contexts using these surfaces have been destroyed. + * + * Both contexts and surfaces are identified by unique IDs and its + * implementation specific internals are kept opaque to the clients + */ + +typedef VAGenericID VAContextID; + +typedef VAGenericID VASurfaceID; + +#define VA_INVALID_ID 0xffffffff +#define VA_INVALID_SURFACE VA_INVALID_ID + +/** \brief Generic value types. */ +typedef enum { + VAGenericValueTypeInteger = 1, /**< 32-bit signed integer. */ + VAGenericValueTypeFloat, /**< 32-bit floating-point value. */ + VAGenericValueTypePointer, /**< Generic pointer type */ + VAGenericValueTypeFunc /**< Pointer to function */ +} VAGenericValueType; + +/** \brief Generic function type. */ +typedef void (*VAGenericFunc)(void); + +/** \brief Generic value. */ +typedef struct _VAGenericValue { + /** \brief Value type. See #VAGenericValueType. */ + VAGenericValueType type; + /** \brief Value holder. */ + union { + /** \brief 32-bit signed integer. */ + int32_t i; + /** \brief 32-bit float. */ + float f; + /** \brief Generic pointer. */ + void *p; + /** \brief Pointer to function. */ + VAGenericFunc fn; + } value; +} VAGenericValue; + +/** @name Surface attribute flags */ +/**@{*/ +/** \brief Surface attribute is not supported. */ +#define VA_SURFACE_ATTRIB_NOT_SUPPORTED 0x00000000 +/** \brief Surface attribute can be got through vaQuerySurfaceAttributes(). */ +#define VA_SURFACE_ATTRIB_GETTABLE 0x00000001 +/** \brief Surface attribute can be set through vaCreateSurfaces(). */ +#define VA_SURFACE_ATTRIB_SETTABLE 0x00000002 +/**@}*/ + +/** \brief Surface attribute types. */ +typedef enum { + VASurfaceAttribNone = 0, + /** + * \brief Pixel format as a FOURCC (int, read/write). + * + * When vaQuerySurfaceAttributes() is called, the driver will return one + * PixelFormat attribute per supported pixel format. + * + * When provided as an input to vaCreateSurfaces(), the driver will + * allocate a surface with the provided pixel format. + */ + VASurfaceAttribPixelFormat, + /** \brief Minimal width in pixels (int, read-only). */ + VASurfaceAttribMinWidth, + /** \brief Maximal width in pixels (int, read-only). */ + VASurfaceAttribMaxWidth, + /** \brief Minimal height in pixels (int, read-only). */ + VASurfaceAttribMinHeight, + /** \brief Maximal height in pixels (int, read-only). */ + VASurfaceAttribMaxHeight, + /** \brief Surface memory type expressed in bit fields (int, read/write). */ + VASurfaceAttribMemoryType, + /** \brief External buffer descriptor (pointer, write). + * + * Refer to the documentation for the memory type being created to + * determine what descriptor structure to pass here. If not otherwise + * stated, the common VASurfaceAttribExternalBuffers should be used. + */ + VASurfaceAttribExternalBufferDescriptor, + /** \brief Surface usage hint, gives the driver a hint of intended usage + * to optimize allocation (e.g. tiling) (int, read/write). */ + VASurfaceAttribUsageHint, + /** \brief List of possible DRM format modifiers (pointer, write). + * + * The value must be a pointer to a VADRMFormatModifierList. This can only + * be used when allocating a new buffer, it's invalid to use this attribute + * when importing an existing buffer. + */ + VASurfaceAttribDRMFormatModifiers, + /** \brief width and height log2 aligment in pixels (int, read-only) + * + * For special HW requirement used in some codecs, if + * VASurfaceAttribAlignmentSize is not implemented in the driver, then + * the surface_width and surface_height should keep the original logic + * without any modification, this is an add-on requirement to + * surface_width and surface_height. + */ + VASurfaceAttribAlignmentSize, + /** \brief Number of surface attributes. */ + VASurfaceAttribCount +} VASurfaceAttribType; + +/** \brief Surface attribute. */ +typedef struct _VASurfaceAttrib { + /** \brief Type. */ + VASurfaceAttribType type; + /** \brief Flags. See "Surface attribute flags". */ + uint32_t flags; + /** \brief Value. See "Surface attribute types" for the expected types. */ + VAGenericValue value; +} VASurfaceAttrib; + +/** + * @name VASurfaceAttribMemoryType values in bit fields. + * Bits 0:7 are reserved for generic types. Bits 31:28 are reserved for + * Linux DRM. Bits 23:20 are reserved for Android. Bits 19:16 are reserved for Win32. + * DRM, Android and Win32 specific types are defined in respective va_*.h header files. + */ +/**@{*/ +/** \brief VA memory type (default) is supported. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_VA 0x00000001 +/** \brief V4L2 buffer memory type is supported. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_V4L2 0x00000002 +/** \brief User pointer memory type is supported. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_USER_PTR 0x00000004 +/**@}*/ +/** + * \brief VASurfaceAttribAlignmentStruct structure for + * the VASurfaceAttribAlignmentSize attribute. + */ +typedef union _VASurfaceAttribAlignmentStruct { + struct { + /** \brief log2 width aligment */ + uint32_t log2_width_alignment : 4; + /** \brief log2 height aligment */ + uint32_t log2_height_alignment : 4; + uint32_t reserved : 24; + } bits; + uint32_t value; +} VASurfaceAttribAlignmentStruct; + +/** + * \brief VASurfaceAttribExternalBuffers structure for + * the VASurfaceAttribExternalBufferDescriptor attribute. + */ +typedef struct _VASurfaceAttribExternalBuffers { + /** \brief pixel format in fourcc. */ + uint32_t pixel_format; + /** \brief width in pixels. */ + uint32_t width; + /** \brief height in pixels. */ + uint32_t height; + /** \brief total size of the buffer in bytes. */ + uint32_t data_size; + /** \brief number of planes for planar layout */ + uint32_t num_planes; + /** \brief pitch for each plane in bytes */ + uint32_t pitches[4]; + /** \brief offset for each plane in bytes */ + uint32_t offsets[4]; + /** \brief buffer handles or user pointers */ + uintptr_t *buffers; + /** \brief number of elements in the "buffers" array */ + uint32_t num_buffers; + /** \brief flags. See "Surface external buffer descriptor flags". */ + uint32_t flags; + /** \brief reserved for passing private data */ + void *private_data; +} VASurfaceAttribExternalBuffers; + +/** @name VASurfaceAttribExternalBuffers flags */ +/**@{*/ +/** \brief Enable memory tiling */ +#define VA_SURFACE_EXTBUF_DESC_ENABLE_TILING 0x00000001 +/** \brief Memory is cacheable */ +#define VA_SURFACE_EXTBUF_DESC_CACHED 0x00000002 +/** \brief Memory is non-cacheable */ +#define VA_SURFACE_EXTBUF_DESC_UNCACHED 0x00000004 +/** \brief Memory is write-combined */ +#define VA_SURFACE_EXTBUF_DESC_WC 0x00000008 +/** \brief Memory is protected */ +#define VA_SURFACE_EXTBUF_DESC_PROTECTED 0x80000000 + +/** @name VASurfaceAttribUsageHint attribute usage hint flags */ +/**@{*/ +/** \brief Surface usage not indicated. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC 0x00000000 +/** \brief Surface used by video decoder. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_DECODER 0x00000001 +/** \brief Surface used by video encoder. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER 0x00000002 +/** \brief Surface read by video post-processing. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_VPP_READ 0x00000004 +/** \brief Surface written by video post-processing. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_VPP_WRITE 0x00000008 +/** \brief Surface used for display. */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_DISPLAY 0x00000010 +/** \brief Surface used for export to third-party APIs, e.g. via + * vaExportSurfaceHandle(). */ +#define VA_SURFACE_ATTRIB_USAGE_HINT_EXPORT 0x00000020 + +/**@}*/ + +/** + * \brief Queries surface attributes for the supplied config. + * + * This function queries for all supported attributes for the + * supplied VA \c config. 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. + * + * The \c attrib_list array is allocated by the user and \c + * num_attribs shall be initialized to the number of allocated + * elements in that array. Upon successful return, the actual number + * of attributes will be overwritten into \c num_attribs. Otherwise, + * \c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and \c num_attribs + * is adjusted to the number of elements that would be returned if + * enough space was available. + * + * Note: it is perfectly valid to pass NULL to the \c attrib_list + * argument when vaQuerySurfaceAttributes() is used to determine the + * actual number of elements that need to be allocated. + * + * @param[in] dpy the VA display + * @param[in] config the config identifying a codec or a video + * processing pipeline + * @param[out] attrib_list the output array of #VASurfaceAttrib elements + * @param[in,out] num_attribs the number of elements allocated on + * input, the number of elements actually filled in output + */ +VAStatus +vaQuerySurfaceAttributes( + VADisplay dpy, + VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int *num_attribs +); + +/** + * \brief Creates an array of surfaces + * + * Creates an array of surfaces. The optional list of attributes shall + * be constructed based on what the underlying hardware could expose + * through vaQuerySurfaceAttributes(). + * + * @param[in] dpy the VA display + * @param[in] format the desired surface format. See \c VA_RT_FORMAT_* + * @param[in] width the surface width + * @param[in] height the surface height + * @param[out] surfaces the array of newly created surfaces + * @param[in] num_surfaces the number of surfaces to create + * @param[in] attrib_list the list of (optional) attributes, or \c NULL + * @param[in] num_attribs the number of attributes supplied in + * \c attrib_list, or zero + */ +VAStatus +vaCreateSurfaces( + VADisplay dpy, + unsigned int format, + unsigned int width, + unsigned int height, + VASurfaceID *surfaces, + unsigned int num_surfaces, + VASurfaceAttrib *attrib_list, + unsigned int num_attribs +); + +/** + * vaDestroySurfaces - Destroy resources associated with surfaces. + * Surfaces can only be destroyed after all contexts using these surfaces have been + * destroyed. + * dpy: display + * surfaces: array of surfaces to destroy + * num_surfaces: number of surfaces in the array to be destroyed. + */ +VAStatus vaDestroySurfaces( + VADisplay dpy, + VASurfaceID *surfaces, + int num_surfaces +); + +#define VA_PROGRESSIVE 0x1 +/** + * vaCreateContext - Create a context + * dpy: display + * config_id: configuration for the context + * picture_width: coded picture width + * picture_height: coded picture height + * flag: any combination of the following: + * VA_PROGRESSIVE (only progressive frame pictures in the sequence when set) + * render_targets: a hint for render targets (surfaces) tied to the context + * num_render_targets: number of render targets in the above array + * context: created context id upon return + */ +VAStatus vaCreateContext( + VADisplay dpy, + VAConfigID config_id, + int picture_width, + int picture_height, + int flag, + VASurfaceID *render_targets, + int num_render_targets, + VAContextID *context /* out */ +); + +/** + * vaDestroyContext - Destroy a context + * dpy: display + * context: context to be destroyed + */ +VAStatus vaDestroyContext( + VADisplay dpy, + VAContextID context +); + +//Multi-frame context +typedef VAGenericID VAMFContextID; +/** + * vaCreateMFContext - Create a multi-frame context + * interface encapsulating common for all streams memory objects and structures + * required for single GPU task submission from several VAContextID's. + * Allocation: This call only creates an instance, doesn't allocate any additional memory. + * Support identification: Application can identify multi-frame feature support by ability + * to create multi-frame context. If driver supports multi-frame - call successful, + * mf_context != NULL and VAStatus = VA_STATUS_SUCCESS, otherwise if multi-frame processing + * not supported driver returns VA_STATUS_ERROR_UNIMPLEMENTED and mf_context = NULL. + * return values: + * VA_STATUS_SUCCESS - operation successful. + * VA_STATUS_ERROR_UNIMPLEMENTED - no support for multi-frame. + * dpy: display adapter. + * mf_context: Multi-Frame context encapsulating all associated context + * for multi-frame submission. + */ +VAStatus vaCreateMFContext( + VADisplay dpy, + VAMFContextID *mf_context /* out */ +); + +/** + * vaMFAddContext - Provide ability to associate each context used for + * Multi-Frame submission and common Multi-Frame context. + * Try to add context to understand if it is supported. + * Allocation: this call allocates and/or reallocates all memory objects + * common for all contexts associated with particular Multi-Frame context. + * All memory required for each context(pixel buffers, internal driver + * buffers required for processing) allocated during standard vaCreateContext call for each context. + * Runtime dependency - if current implementation doesn't allow to run different entry points/profile, + * first context added will set entry point/profile for whole Multi-Frame context, + * all other entry points and profiles can be rejected to be added. + * Return values: + * VA_STATUS_SUCCESS - operation successful, context was added. + * VA_STATUS_ERROR_OPERATION_FAILED - something unexpected happened - application have to close + * current mf_context and associated contexts and start working with new ones. + * VA_STATUS_ERROR_INVALID_CONTEXT - ContextID is invalid, means: + * 1 - mf_context is not valid context or + * 2 - driver can't suport different VAEntrypoint or VAProfile simultaneosly + * and current context contradicts with previously added, application can continue with current mf_context + * and other contexts passed this call, rejected context can continue work in stand-alone + * mode or other mf_context. + * VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT - particular context being added was created with with + * unsupported VAEntrypoint. Application can continue with current mf_context + * and other contexts passed this call, rejected context can continue work in stand-alone + * mode. + * VA_STATUS_ERROR_UNSUPPORTED_PROFILE - Current context with Particular VAEntrypoint is supported + * but VAProfile is not supported. Application can continue with current mf_context + * and other contexts passed this call, rejected context can continue work in stand-alone + * mode. + * dpy: display adapter. + * context: context being associated with Multi-Frame context. + * mf_context: - multi-frame context used to associate contexts for multi-frame submission. + */ +VAStatus vaMFAddContext( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID context +); + +/** + * vaMFReleaseContext - Removes context from multi-frame and + * association with multi-frame context. + * After association removed vaEndPicture will submit tasks, but not vaMFSubmit. + * Return values: + * VA_STATUS_SUCCESS - operation successful, context was removed. + * VA_STATUS_ERROR_OPERATION_FAILED - something unexpected happened. + * application need to destroy this VAMFContextID and all assotiated VAContextID + * dpy: display + * mf_context: VAMFContextID where context is added + * context: VAContextID to be added + */ +VAStatus vaMFReleaseContext( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID context +); + +/** + * Buffers + * Buffers are used to pass various types of data from the + * client to the server. The server maintains a data store + * for each buffer created, and the client idenfies a buffer + * through a unique buffer id assigned by the server. + */ + +typedef VAGenericID VABufferID; + +typedef enum { + VAPictureParameterBufferType = 0, + VAIQMatrixBufferType = 1, + VABitPlaneBufferType = 2, + VASliceGroupMapBufferType = 3, + VASliceParameterBufferType = 4, + VASliceDataBufferType = 5, + VAMacroblockParameterBufferType = 6, + VAResidualDataBufferType = 7, + VADeblockingParameterBufferType = 8, + VAImageBufferType = 9, + VAProtectedSliceDataBufferType = 10, + VAQMatrixBufferType = 11, + VAHuffmanTableBufferType = 12, + VAProbabilityBufferType = 13, + + /* Following are encode buffer types */ + VAEncCodedBufferType = 21, + VAEncSequenceParameterBufferType = 22, + VAEncPictureParameterBufferType = 23, + VAEncSliceParameterBufferType = 24, + VAEncPackedHeaderParameterBufferType = 25, + VAEncPackedHeaderDataBufferType = 26, + VAEncMiscParameterBufferType = 27, + VAEncMacroblockParameterBufferType = 28, + VAEncMacroblockMapBufferType = 29, + + /** + * \brief Encoding QP buffer + * + * This buffer contains QP per MB for encoding. Currently + * VAEncQPBufferH264 is defined for H.264 encoding, see + * #VAEncQPBufferH264 for details + */ + VAEncQPBufferType = 30, + /* Following are video processing buffer types */ + /** + * \brief Video processing pipeline parameter buffer. + * + * This buffer describes the video processing pipeline. See + * #VAProcPipelineParameterBuffer for details. + */ + VAProcPipelineParameterBufferType = 41, + /** + * \brief Video filter parameter buffer. + * + * This buffer describes the video filter parameters. All buffers + * inherit from #VAProcFilterParameterBufferBase, thus including + * a unique filter buffer type. + * + * The default buffer used by most filters is #VAProcFilterParameterBuffer. + * Filters requiring advanced parameters include, but are not limited to, + * deinterlacing (#VAProcFilterParameterBufferDeinterlacing), + * color balance (#VAProcFilterParameterBufferColorBalance), etc. + */ + VAProcFilterParameterBufferType = 42, + /** + * \brief FEI specific buffer types + */ + VAEncFEIMVBufferType = 43, + VAEncFEIMBCodeBufferType = 44, + VAEncFEIDistortionBufferType = 45, + VAEncFEIMBControlBufferType = 46, + VAEncFEIMVPredictorBufferType = 47, + VAStatsStatisticsParameterBufferType = 48, + /** \brief Statistics output for VAEntrypointStats progressive and top field of interlaced case*/ + VAStatsStatisticsBufferType = 49, + /** \brief Statistics output for VAEntrypointStats bottom field of interlaced case*/ + VAStatsStatisticsBottomFieldBufferType = 50, + VAStatsMVBufferType = 51, + VAStatsMVPredictorBufferType = 52, + /** Force MB's to be non skip for encode.it's per-mb control buffer, The width of the MB map + * Surface is (width of the Picture in MB unit) * 1 byte, multiple of 64 bytes. + * The height is (height of the picture in MB unit). The picture is either + * frame or non-interleaved top or bottom field. If the application provides this + *surface, it will override the "skipCheckDisable" setting in VAEncMiscParameterEncQuality. + */ + VAEncMacroblockDisableSkipMapBufferType = 53, + /** + * \brief HEVC FEI CTB level cmd buffer + * it is CTB level information for future usage. + */ + VAEncFEICTBCmdBufferType = 54, + /** + * \brief HEVC FEI CU level data buffer + * it's CTB level information for future usage + */ + VAEncFEICURecordBufferType = 55, + /** decode stream out buffer, intermedia data of decode, it may include MV, MB mode etc. + * it can be used to detect motion and analyze the frame contain */ + VADecodeStreamoutBufferType = 56, + + /** \brief HEVC Decoding Subset Parameter buffer type + * + * The subsets parameter buffer is concatenation with one or multiple + * subset entry point offsets. All the offset values are layed out one + * by one according to slice order with first slice segment first, second + * slice segment second, etc... The entry number is indicated by parameter + * \ref num_entry_point_offsets. And the first entry position of the entry + * point offsets for any slice segment is indicated by parameter + * entry_offset_to_subset_array in VAPictureParameterBufferHEVC data structure. + */ + VASubsetsParameterBufferType = 57, + /** \brief adjust context parameters dynamically + * + * this parameter is used to update context parameters, detail parameter is in + * \c VAContextParameterUpdateBuffer + */ + VAContextParameterUpdateBufferType = 58, + /** + * \brief Protected session execution buffer type + * + * It's for TEE execution usage (vaProtectedSessionExecute()). The buffer structure is in + * \c VAProtectedSessionExecuteBuffer + */ + VAProtectedSessionExecuteBufferType = 59, + + /** \brief Encryption parameters buffer for protected content session. + * + * Refer to \c VAEncryptionParameters + */ + VAEncryptionParameterBufferType = 60, + + /** + * \brief Encoding delta QP per block buffer + * + * This buffer only could be created and accepted + * when \c VAConfigAttribValEncPerBlockControl delta_qp_support == 1. + * This input buffer contains delta QP per block for encoding. + * The supported size of delta QP block and the size of delta QP + * must be quried from \c VAConfigAttribValEncPerBlockControl. + */ + VAEncDeltaQpPerBlockBufferType = 61, + + /** + * \brief VVC ALF data buffer + * + * Refer to \c VAAlfDataVVC + */ + VAAlfBufferType = 62, + /** + * \brief VVC LMCS data buffer + * + * Refer to \c VALmcsDataVVC + */ + VALmcsBufferType = 63, + /** + * \brief VVC SubPic data buffer + * + * Refer to \c VASubPicVVC + */ + VASubPicBufferType = 64, + /** + * \brief VVC Tile Dimension data buffer + * + * Data buffer of tile widths and heights, with each element formatted as uint16_t + */ + VATileBufferType = 65, + /** + * \brief VVC Slice Structure data buffer + * + * Refer to \c VASliceStructVVC + */ + VASliceStructBufferType = 66, + + VABufferTypeMax +} VABufferType; + +/** \brief update the context parameter + * this structure is used to update context parameters, such as priority of the context + * backend driver should keep the parameter unchanged if there no new + * parameter updated. + */ +typedef struct _VAContextParameterUpdateBuffer { + union { + struct { + /** \brief indicate whether context priority changed */ + uint32_t context_priority_update : 1; + /** \brief Reserved bits for future use, must be zero */ + uint32_t reserved : 31; + } bits; + uint32_t value; + } flags; + /** \brief task/context priority */ + VAConfigAttribValContextPriority context_priority; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved[VA_PADDING_MEDIUM]; +} VAContextParameterUpdateBuffer; + +/** + * These ENCRYPTION_TYPEs are used for the attribute values for + * \c VAConfigAttribEncryption and for encryption_type in + * VAEncryptionParameters. + * + * When used for \c VAConfigAttribEncryption, it be used via + * vaQueryConfigEntrypoints to check which type are supported for specific + * profile or not. + * + * When used for encryption_type in VAEncryptionParameters, it tells driver + * the parameters in VAEncryptionParameters are used for which encryption type. + */ +#define VA_ENCRYPTION_TYPE_FULLSAMPLE_CTR 0x00000001 /* AES CTR fullsample */ +#define VA_ENCRYPTION_TYPE_FULLSAMPLE_CBC 0x00000002 /* AES CBC fullsample */ +#define VA_ENCRYPTION_TYPE_SUBSAMPLE_CTR 0x00000004 /* AES CTR fullsample */ +#define VA_ENCRYPTION_TYPE_SUBSAMPLE_CBC 0x00000008 /* AES CBC fullsample */ + +/** \brief structure for encrypted segment info. */ +typedef struct _VAEncryptionSegmentInfo { + /** \brief The offset relative to the start of the bitstream input in + * bytes of the start of the segment */ + uint32_t segment_start_offset; + /** \brief The length of the segments in bytes */ + uint32_t segment_length; + /** \brief The length in bytes of the remainder of an incomplete block + * from a previous segment*/ + uint32_t partial_aes_block_size; + /** \brief The length in bytes of the initial clear data */ + uint32_t init_byte_length; + /** \brief This will be AES counter for secure decode and secure encode + * when numSegments equals 1, valid size is specified by + * \c key_blob_size */ + uint8_t aes_cbc_iv_or_ctr[64]; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAEncryptionSegmentInfo; + +/** \brief Encryption parameters buffer for VAEncryptionParameterBufferType */ +typedef struct _VAEncryptionParameters { + /** \brief Encryption type, refer to \c VA_ENCRYPTION_TYPE_FULLSAMPLE_CTR, + * \c VA_ENCRYPTION_TYPE_FULLSAMPLE_CBC, \c VA_ENCRYPTION_TYPE_SUBSAMPLE_CTR, + * or \c VA_ENCRYPTION_TYPE_SUBSAMPLE_CBC */ + uint32_t encryption_type; + /** \brief The number of sengments */ + uint32_t num_segments; + /** \brief Pointer of segments */ + VAEncryptionSegmentInfo *segment_info; + /** \brief The status report index reserved for CENC fullsample workload. + * The related structures and definitions are vendor specific. + */ + uint32_t status_report_index; + /** \brief CENC counter length */ + uint32_t size_of_length; + /** \brief Wrapped decrypt blob (Snd)kb, valid size is specified by + * \c key_blob_size */ + uint8_t wrapped_decrypt_blob[64]; + /** \brief Wrapped Key blob info (Sne)kb, valid size is specified by + * \c key_blob_size */ + uint8_t wrapped_encrypt_blob[64]; + /** \brief key blob size + * It could be \c VA_PC_BLOCK_SIZE_128, \c VA_PC_BLOCK_SIZE_192, or + * \c VA_PC_BLOCK_SIZE_256 + */ + uint32_t key_blob_size; + /** \brief Indicates the number of 16-byte BLOCKS that are encrypted in any + * given encrypted region of segments. + * If this value is zero: + * 1. All bytes in encrypted region of segments are encrypted, i.e. the + * CENC or CBC1 scheme is being used + * 2. blocks_stripe_clear must also be zero. + * If this value is non-zero, blocks_stripe_clear must also be non-zero. + */ + uint32_t blocks_stripe_encrypted; + /** \brief Indicates the number of 16-byte BLOCKS that are clear in any given + * encrypted region of segments, as defined by the CENS and CBCS schemes in + * the common encryption spec. + * If this value is zero, all bytes in encrypted region of segments are + * encrypted, i.e. the CENC or CBC1 scheme is being used. + */ + uint32_t blocks_stripe_clear; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAEncryptionParameters; + +/** + * Processing rate parameter for encode. + */ +typedef struct _VAProcessingRateParameterEnc { + /** \brief Profile level */ + uint8_t level_idc; + uint8_t reserved[3]; + /** \brief quality level. When set to 0, default quality + * level is used. + */ + uint32_t quality_level; + /** \brief Period between I frames. */ + uint32_t intra_period; + /** \brief Period between I/P frames. */ + uint32_t ip_period; +} VAProcessingRateParameterEnc; + +/** + * Processing rate parameter for decode. + */ +typedef struct _VAProcessingRateParameterDec { + /** \brief Profile level */ + uint8_t level_idc; + uint8_t reserved0[3]; + uint32_t reserved; +} VAProcessingRateParameterDec; + +typedef struct _VAProcessingRateParameter { + union { + VAProcessingRateParameterEnc proc_buf_enc; + VAProcessingRateParameterDec proc_buf_dec; + }; +} VAProcessingRateParameter; + +/** + * \brief Queries processing rate for the supplied config. + * + * This function queries the processing rate based on parameters in + * \c proc_buf for the given \c config. Upon successful return, the processing + * rate value will be stored in \c processing_rate. Processing rate is + * specified as the number of macroblocks/CTU per second. + * + * If NULL is passed to the \c proc_buf, the default processing rate for the + * given configuration will be returned. + * + * @param[in] dpy the VA display + * @param[in] config the config identifying a codec or a video + * processing pipeline + * @param[in] proc_buf the buffer that contains the parameters for + either the encode or decode processing rate + * @param[out] processing_rate processing rate in number of macroblocks per + second constrained by parameters specified in proc_buf + * + */ +VAStatus +vaQueryProcessingRate( + VADisplay dpy, + VAConfigID config, + VAProcessingRateParameter *proc_buf, + unsigned int *processing_rate +); + +typedef enum { + VAEncMiscParameterTypeFrameRate = 0, + VAEncMiscParameterTypeRateControl = 1, + VAEncMiscParameterTypeMaxSliceSize = 2, + VAEncMiscParameterTypeAIR = 3, + /** \brief Buffer type used to express a maximum frame size (in bits). */ + VAEncMiscParameterTypeMaxFrameSize = 4, + /** \brief Buffer type used for HRD parameters. */ + VAEncMiscParameterTypeHRD = 5, + VAEncMiscParameterTypeQualityLevel = 6, + /** \brief Buffer type used for Rolling intra refresh */ + VAEncMiscParameterTypeRIR = 7, + /** \brief Buffer type used for quantization parameters, it's per-sequence parameter*/ + VAEncMiscParameterTypeQuantization = 8, + /** \brief Buffer type used for sending skip frame parameters to the encoder's + * rate control, when the user has externally skipped frames. */ + VAEncMiscParameterTypeSkipFrame = 9, + /** \brief Buffer type used for region-of-interest (ROI) parameters. */ + VAEncMiscParameterTypeROI = 10, + /** \brief Buffer type used to express a maximum frame size (in bytes) settings for multiple pass. */ + VAEncMiscParameterTypeMultiPassFrameSize = 11, + /** \brief Buffer type used for temporal layer structure */ + VAEncMiscParameterTypeTemporalLayerStructure = 12, + /** \brief Buffer type used for dirty region-of-interest (ROI) parameters. */ + VAEncMiscParameterTypeDirtyRect = 13, + /** \brief Buffer type used for parallel BRC parameters. */ + VAEncMiscParameterTypeParallelBRC = 14, + /** \brief Set MB partion mode mask and Half-pel/Quant-pel motion search */ + VAEncMiscParameterTypeSubMbPartPel = 15, + /** \brief set encode quality tuning */ + VAEncMiscParameterTypeEncQuality = 16, + /** \brief Buffer type used for encoder rounding offset parameters. */ + VAEncMiscParameterTypeCustomRoundingControl = 17, + /** \brief Buffer type used for FEI input frame level parameters */ + VAEncMiscParameterTypeFEIFrameControl = 18, + /** \brief encode extension buffer, ect. MPEG2 Sequence extenstion data */ + VAEncMiscParameterTypeExtensionData = 19 +} VAEncMiscParameterType; + +/** \brief Packed header type. */ +typedef enum { + /** \brief Packed sequence header. */ + VAEncPackedHeaderSequence = 1, + /** \brief Packed picture header. */ + VAEncPackedHeaderPicture = 2, + /** \brief Packed slice header. */ + VAEncPackedHeaderSlice = 3, + /** + * \brief Packed raw header. + * + * Packed raw data header can be used by the client to insert a header + * into the bitstream data buffer at the point it is passed, the driver + * will handle the raw packed header based on "has_emulation_bytes" field + * in the packed header parameter structure. + */ + VAEncPackedHeaderRawData = 4, + /** + * \brief Misc packed header. See codec-specific definitions. + * + * @deprecated + * This is a deprecated packed header type. All applications can use + * \c VAEncPackedHeaderRawData to insert a codec-specific packed header + */ + VAEncPackedHeaderMiscMask va_deprecated_enum = 0x80000000, +} VAEncPackedHeaderType; + +/** \brief Packed header parameter. */ +typedef struct _VAEncPackedHeaderParameterBuffer { + /** Type of the packed header buffer. See #VAEncPackedHeaderType. */ + uint32_t type; + /** \brief Size of the #VAEncPackedHeaderDataBuffer in bits. */ + uint32_t bit_length; + /** \brief Flag: buffer contains start code emulation prevention bytes? */ + uint8_t has_emulation_bytes; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPackedHeaderParameterBuffer; + +/** + * For application, e.g. set a new bitrate + * VABufferID buf_id; + * VAEncMiscParameterBuffer *misc_param; + * VAEncMiscParameterRateControl *misc_rate_ctrl; + * + * vaCreateBuffer(dpy, context, VAEncMiscParameterBufferType, + * sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl), + * 1, NULL, &buf_id); + * + * vaMapBuffer(dpy,buf_id,(void **)&misc_param); + * misc_param->type = VAEncMiscParameterTypeRateControl; + * misc_rate_ctrl= (VAEncMiscParameterRateControl *)misc_param->data; + * misc_rate_ctrl->bits_per_second = 6400000; + * vaUnmapBuffer(dpy, buf_id); + * vaRenderPicture(dpy, context, &buf_id, 1); + */ +typedef struct _VAEncMiscParameterBuffer { + VAEncMiscParameterType type; + uint32_t data[]; +} VAEncMiscParameterBuffer; + +/** \brief Temporal layer Structure*/ +typedef struct _VAEncMiscParameterTemporalLayerStructure { + /** \brief The number of temporal layers */ + uint32_t number_of_layers; + /** \brief The length of the array defining frame layer membership. Should be 1-32 */ + uint32_t periodicity; + /** + * \brief The array indicating the layer id for each frame + * + * The layer id for the first frame in a coded sequence is always 0, so layer_id[] specifies the layer + * ids for frames starting from the 2nd frame. + */ + uint32_t layer_id[32]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterTemporalLayerStructure; + + +/** \brief Rate control parameters */ +typedef struct _VAEncMiscParameterRateControl { + /** The maximum bit-rate which the the rate controller should generate. */ + uint32_t bits_per_second; + /** The target bit-rate which the rate controller should generate, as a percentage of the + * maximum bit-rate. + * + * In CBR mode this value is ignored (treated as 100%). + */ + uint32_t target_percentage; + /** Rate control window size in milliseconds. + * + * The rate controller will attempt to guarantee that the target and maximum bit-rates are + * correct over this window. + */ + uint32_t window_size; + /** Initial quantiser value used at the start of the stream. + * + * Ignored if set to zero. + */ + uint32_t initial_qp; + /** Minimum quantiser value to use. + * + * The quantiser will not go below the value - if this limit is hit, the output bitrate may + * be lower than the target. Ignored if set to zero. + */ + uint32_t min_qp; + /** Basic unit size. + * + * Only used by some drivers - see driver documentation for details. Set to zero if unused. + */ + uint32_t basic_unit_size; + union { + struct { + /** Force rate controller reset. + * + * The next frame will be treated as the start of a new stream, with all rate + * controller state reset to its initial values. + */ + uint32_t reset : 1; + /** Disable frame skip in rate control mode. */ + uint32_t disable_frame_skip : 1; + /** Disable bit stuffing in rate control mode. */ + uint32_t disable_bit_stuffing : 1; + /** Macroblock-level rate control. + * + * 0: use default, 1: always enable, 2: always disable, other: reserved. + * + * This feature is only available if VAConfigAttribRateControl has the + * \ref VA_RC_MB bit set. + */ + uint32_t mb_rate_control : 4; + /** The temporal layer that these rate control parameters apply to. */ + uint32_t temporal_id : 8; + /** Ensure that intra frames also conform to the constant frame size. */ + uint32_t cfs_I_frames : 1; + /** Enable parallel rate control for hierarchical B frames. + * + * See \ref VA_RC_PARALLEL. + */ + uint32_t enable_parallel_brc : 1; + uint32_t enable_dynamic_scaling : 1; + /** Frame tolerance mode. + * + * Indicates the tolerance the application has to variations in the frame size. + * For example, wireless display scenarios may require very steady bit rate to + * reduce buffering time. It affects the rate control algorithm used, + * but may or may not have an effect based on the combination of other BRC + * parameters. Only valid when the driver reports support for + * #VAConfigAttribFrameSizeToleranceSupport. + * + * equals 0 -- normal mode; + * equals 1 -- maps to sliding window; + * equals 2 -- maps to low delay mode; + * other -- invalid. + */ + uint32_t frame_tolerance_mode : 2; + /** Reserved for future use, must be zero. */ + uint32_t reserved : 12; + } bits; + uint32_t value; + } rc_flags; + /** Initial quality factor used in ICQ mode. + * + * This value must be between 1 and 51. + * this value will be deprecated in future, to use quality_factor instead of it. + */ + uint32_t ICQ_quality_factor; + /** Maximum quantiser value to use. + * + * The quantiser will not go above this value - if this limit is hit, the output bitrate + * may exceed the target. Ignored if set to zero. + */ + uint32_t max_qp; + /** Quality factor + * + * the range will be different for different codec + */ + uint32_t quality_factor; + /** Target frame size + * + * Desired frame size in bytes. + * This parameter can be used in some RC modes (like Transport Controlled BRC) + * where feedback from the app is required. + * Zero value means no limits. + * + */ + uint32_t target_frame_size; + /** Reserved bytes for future use, must be zero. */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterRateControl; + +/** Encode framerate parameters. + * + * Sets the encode framerate used by the rate controller. This should be + * provided in all modes using a bitrate target (variable framerate is not + * supported). + */ +typedef struct _VAEncMiscParameterFrameRate { + /** Encode framerate. + * + * The framerate is specified as a number of frames per second, as a + * fraction. The denominator of the fraction is given in the top half + * (the high two bytes) of the framerate field, and the numerator is + * given in the bottom half (the low two bytes). + * + * That is: + * denominator = framerate >> 16 & 0xffff; + * numerator = framerate & 0xffff; + * fps = numerator / denominator; + * + * For example, if framerate is set to (100 << 16 | 750), this is + * 750 / 100, hence 7.5fps. + * + * If the denominator is zero (the high two bytes are both zero) then + * it takes the value one instead, so the framerate is just the integer + * in the low 2 bytes. + */ + uint32_t framerate; + union { + struct { + /** The temporal layer that these framerate parameters apply to. */ + uint32_t temporal_id : 8; + /** Reserved for future use, must be zero. */ + uint32_t reserved : 24; + } bits; + uint32_t value; + } framerate_flags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterFrameRate; + +/** + * Allow a maximum slice size to be specified (in bits). + * The encoder will attempt to make sure that individual slices do not exceed this size + * Or to signal applicate if the slice size exceed this size, see "status" of VACodedBufferSegment + */ +typedef struct _VAEncMiscParameterMaxSliceSize { + uint32_t max_slice_size; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterMaxSliceSize; + +typedef struct _VAEncMiscParameterAIR { + uint32_t air_num_mbs; + uint32_t air_threshold; + uint32_t air_auto; /* if set to 1 then hardware auto-tune the AIR threshold */ + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterAIR; + +/* + * \brief Rolling intra refresh data structure for encoding. + */ +typedef struct _VAEncMiscParameterRIR { + union { + struct + /** + * \brief Indicate if intra refresh is enabled in column/row. + * + * App should query VAConfigAttribEncIntraRefresh to confirm RIR support + * by the driver before sending this structure. + */ + { + /* \brief enable RIR in column */ + uint32_t enable_rir_column : 1; + /* \brief enable RIR in row */ + uint32_t enable_rir_row : 1; + uint32_t reserved : 30; + } bits; + uint32_t value; + } rir_flags; + /** + * \brief Indicates the column or row location in MB. It is ignored if + * rir_flags is 0. + */ + uint16_t intra_insertion_location; + /** + * \brief Indicates the number of columns or rows in MB. It is ignored if + * rir_flags is 0. + */ + uint16_t intra_insert_size; + /** + * \brief indicates the Qp difference for inserted intra columns or rows. + * App can use this to adjust intra Qp based on bitrate & max frame size. + */ + uint8_t qp_delta_for_inserted_intra; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterRIR; + +/** HRD / VBV buffering parameters for encoding. + * + * This sets the HRD / VBV parameters which will be used by the rate + * controller for encoding. It should be specified in modes using a bitrate + * target when the buffering of the output stream needs to be constrained. + * + * If not provided, the encoder may use arbitrary amounts of buffering. + */ +typedef struct _VAEncMiscParameterHRD { + /** The initial fullness of the HRD coded picture buffer, in bits. + * + * This sets how full the CPB is when encoding begins - that is, how much + * buffering will happen on the decoder side before the first frame. + * The CPB fullness will be reset to this value after any rate control + * reset (a change in parameters or an explicit reset). + * + * For H.264, it should match the value of initial_cpb_removal_delay in + * buffering_period SEI messages. + */ + uint32_t initial_buffer_fullness; + /** The HRD coded picture buffer size, in bits. + * + * For H.264, it should match the value of cpb_size_value_minus1 in the VUI + * parameters. + */ + uint32_t buffer_size; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterHRD; + +/** + * \brief Defines a maximum frame size (in bits). + * + * This misc parameter buffer defines the maximum size of a frame (in + * bits). The encoder will try to make sure that each frame does not + * exceed this size. Otherwise, if the frame size exceeds this size, + * the \c status flag of #VACodedBufferSegment will contain + * #VA_CODED_BUF_STATUS_FRAME_SIZE_OVERFLOW. + */ +typedef struct _VAEncMiscParameterBufferMaxFrameSize { + /** \brief Type. Shall be set to #VAEncMiscParameterTypeMaxFrameSize. */ + /** duplicated with VAEncMiscParameterBuffer, should be deprecated*/ + va_deprecated VAEncMiscParameterType type; + /** \brief Maximum size of a frame (in bits). */ + uint32_t max_frame_size; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterBufferMaxFrameSize; + +/** + * \brief Maximum frame size (in bytes) settings for multiple pass. + * + * This misc parameter buffer defines the maximum size of a frame (in + * bytes) settings for multiple pass. currently only AVC encoder can + * support this settings in multiple pass case. If the frame size exceeds + * this size, the encoder will do more pak passes to adjust the QP value + * to control the frame size. + */ +typedef struct _VAEncMiscParameterBufferMultiPassFrameSize { + /** \brief Type. Shall be set to #VAEncMiscParameterTypeMultiPassMaxFrameSize. */ + /** duplicated with VAEncMiscParameterBuffer, should be deprecated*/ + va_deprecated VAEncMiscParameterType type; + /** \brief Maximum size of a frame (in byte) */ + uint32_t max_frame_size; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved; + /** \brief number of passes, every pass has different QP, currently AVC encoder can support up to 4 passes */ + uint8_t num_passes; + /** \brief delta QP list for every pass */ + uint8_t *delta_qp; + + /** \brief Reserved bytes for future use, must be zero */ + unsigned long va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterBufferMultiPassFrameSize; + +/** + * \brief Encoding quality level. + * + * The encoding quality could be set through this structure, if the implementation + * supports multiple quality levels. The quality level set through this structure is + * persistent over the entire coded sequence, or until a new structure is being sent. + * The quality level range can be queried through the VAConfigAttribEncQualityRange + * attribute. A lower value means higher quality, and a value of 1 represents the highest + * quality. The quality level setting is used as a trade-off between quality and speed/power + * consumption, with higher quality corresponds to lower speed and higher power consumption. + */ +typedef struct _VAEncMiscParameterBufferQualityLevel { + /** \brief Encoding quality level setting. When set to 0, default quality + * level is used. + */ + uint32_t quality_level; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterBufferQualityLevel; + +/** + * \brief Quantization settings for encoding. + * + * Some encoders support special types of quantization such as trellis, and this structure + * can be used by the app to control these special types of quantization by the encoder. + */ +typedef struct _VAEncMiscParameterQuantization { + union { + /* if no flags is set then quantization is determined by the driver */ + struct { + /* \brief disable trellis for all frames/fields */ + uint32_t disable_trellis : 1; + /* \brief enable trellis for I frames/fields */ + uint32_t enable_trellis_I : 1; + /* \brief enable trellis for P frames/fields */ + uint32_t enable_trellis_P : 1; + /* \brief enable trellis for B frames/fields */ + uint32_t enable_trellis_B : 1; + uint32_t reserved : 28; + } bits; + uint32_t value; + } quantization_flags; + uint32_t va_reserved; +} VAEncMiscParameterQuantization; + +/** + * \brief Encoding skip frame. + * + * The application may choose to skip frames externally to the encoder (e.g. drop completely or + * code as all skip's). For rate control purposes the encoder will need to know the size and number + * of skipped frames. Skip frame(s) indicated through this structure is applicable only to the + * current frame. It is allowed for the application to still send in packed headers for the driver to + * pack, although no frame will be encoded (e.g. for HW to encrypt the frame). + */ +typedef struct _VAEncMiscParameterSkipFrame { + /** \brief Indicates skip frames as below. + * 0: Encode as normal, no skip. + * 1: One or more frames were skipped prior to the current frame, encode the current frame as normal. + * 2: The current frame is to be skipped, do not encode it but pack/encrypt the packed header contents + * (all except VAEncPackedHeaderSlice) which could contain actual frame contents (e.g. pack the frame + * in VAEncPackedHeaderPicture). */ + uint8_t skip_frame_flag; + /** \brief The number of frames skipped prior to the current frame. Valid when skip_frame_flag = 1. */ + uint8_t num_skip_frames; + /** \brief When skip_frame_flag = 1, the size of the skipped frames in bits. When skip_frame_flag = 2, + * the size of the current skipped frame that is to be packed/encrypted in bits. */ + uint32_t size_skip_frames; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterSkipFrame; + +/** + * \brief Encoding region-of-interest (ROI). + * + * The encoding ROI can be set through VAEncMiscParameterBufferROI, if the implementation + * supports ROI input. The ROI set through this structure is applicable only to the + * current frame or field, so must be sent every frame or field to be applied. The number of + * supported ROIs can be queried through the VAConfigAttribEncROI. The encoder will use the + * ROI information to adjust the QP values of the MB's that fall within the ROIs. + */ +typedef struct _VAEncROI { + /** \brief Defines the ROI boundary in pixels, the driver will map it to appropriate + * codec coding units. It is relative to frame coordinates for the frame case and + * to field coordinates for the field case. */ + VARectangle roi_rectangle; + /** + * \brief ROI value + * + * \ref roi_value specifies ROI delta QP or ROI priority. + * -- ROI delta QP is the value that will be added on top of the frame level QP. + * -- ROI priority specifies the priority of a region, it can be positive (more important) + * or negative (less important) values and is compared with non-ROI region (taken as value 0), + * E.g. ROI region with \ref roi_value -3 is less important than the non-ROI region (\ref roi_value + * implied to be 0) which is less important than ROI region with roi_value +2. For overlapping + * regions, the roi_value that is first in the ROI array will have priority. + * + * \ref roi_value always specifes ROI delta QP when VAConfigAttribRateControl == VA_RC_CQP, no matter + * the value of \c roi_value_is_qp_delta in #VAEncMiscParameterBufferROI. + * + * \ref roi_value depends on \c roi_value_is_qp_delta in #VAEncMiscParameterBufferROI when + * VAConfigAttribRateControl != VA_RC_CQP. \ref roi_value specifies ROI_delta QP if \c roi_value_is_qp_delta + * in VAEncMiscParameterBufferROI is 1, otherwise \ref roi_value specifies ROI priority. + */ + int8_t roi_value; +} VAEncROI; + +typedef struct _VAEncMiscParameterBufferROI { + /** \brief Number of ROIs being sent.*/ + uint32_t num_roi; + + /** \brief Valid when VAConfigAttribRateControl != VA_RC_CQP, then the encoder's + * rate control will determine actual delta QPs. Specifies the max/min allowed delta + * QPs. */ + int8_t max_delta_qp; + int8_t min_delta_qp; + + /** \brief Pointer to a VAEncROI array with num_roi elements. It is relative to frame + * coordinates for the frame case and to field coordinates for the field case.*/ + VAEncROI *roi; + union { + struct { + /** + * \brief An indication for roi value. + * + * \ref roi_value_is_qp_delta equal to 1 indicates \c roi_value in #VAEncROI should + * be used as ROI delta QP. \ref roi_value_is_qp_delta equal to 0 indicates \c roi_value + * in #VAEncROI should be used as ROI priority. + * + * \ref roi_value_is_qp_delta is only available when VAConfigAttribRateControl != VA_RC_CQP, + * the setting must comply with \c roi_rc_priority_support and \c roi_rc_qp_delta_support in + * #VAConfigAttribValEncROI. The underlying driver should ignore this field + * when VAConfigAttribRateControl == VA_RC_CQP. + */ + uint32_t roi_value_is_qp_delta : 1; + uint32_t reserved : 31; + } bits; + uint32_t value; + } roi_flags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterBufferROI; +/* + * \brief Dirty rectangle data structure for encoding. + * + * The encoding dirty rect can be set through VAEncMiscParameterBufferDirtyRect, if the + * implementation supports dirty rect input. The rect set through this structure is applicable + * only to the current frame or field, so must be sent every frame or field to be applied. + * The number of supported rects can be queried through the VAConfigAttribEncDirtyRect. The + * encoder will use the rect information to know those rectangle areas have changed while the + * areas not covered by dirty rect rectangles are assumed to have not changed compared to the + * previous picture. The encoder may do some internal optimizations. + */ +typedef struct _VAEncMiscParameterBufferDirtyRect { + /** \brief Number of Rectangle being sent.*/ + uint32_t num_roi_rectangle; + + /** \brief Pointer to a VARectangle array with num_roi_rectangle elements.*/ + VARectangle *roi_rectangle; +} VAEncMiscParameterBufferDirtyRect; + +/** \brief Attribute value for VAConfigAttribEncParallelRateControl */ +typedef struct _VAEncMiscParameterParallelRateControl { + /** brief Number of layers*/ + uint32_t num_layers; + /** brief Number of B frames per layer per GOP. + * + * it should be allocated by application, and the is num_layers. + * num_b_in_gop[0] is the number of regular B which refers to only I or P frames. */ + uint32_t *num_b_in_gop; +} VAEncMiscParameterParallelRateControl; + +/** per frame encoder quality controls, once set they will persist for all future frames + *till it is updated again. */ +typedef struct _VAEncMiscParameterEncQuality { + union { + struct { + /** Use raw frames for reference instead of reconstructed frames. + * it only impact motion estimation (ME) stage, and will not impact MC stage + * so the reconstruct picture will can match with decode side */ + uint32_t useRawPicForRef : 1; + /** Disables skip check for ME stage, it will increase the bistream size + * but will improve the qulity */ + uint32_t skipCheckDisable : 1; + /** Indicates app will override default driver FTQ settings using FTQEnable. + * FTQ is forward transform quantization */ + uint32_t FTQOverride : 1; + /** Enables/disables FTQ. */ + uint32_t FTQEnable : 1; + /** Indicates the app will provide the Skip Threshold LUT to use when FTQ is + * enabled (FTQSkipThresholdLUT), else default driver thresholds will be used. */ + uint32_t FTQSkipThresholdLUTInput : 1; + /** Indicates the app will provide the Skip Threshold LUT to use when FTQ is + * disabled (NonFTQSkipThresholdLUT), else default driver thresholds will be used. */ + uint32_t NonFTQSkipThresholdLUTInput : 1; + uint32_t ReservedBit : 1; + /** Control to enable the ME mode decision algorithm to bias to fewer B Direct/Skip types. + * Applies only to B frames, all other frames will ignore this setting. */ + uint32_t directBiasAdjustmentEnable : 1; + /** Enables global motion bias. global motion also is called HME (Heirarchical Motion Estimation ) + * HME is used to handle large motions and avoiding local minima in the video encoding process + * down scaled the input and reference picture, then do ME. the result will be a predictor to next level HME or ME + * current interface divide the HME to 3 level. UltraHME , SuperHME, and HME, result of UltraHME will be input of SurperHME, + * result of superHME will be a input for HME. HME result will be input of ME. it is a switch for HMEMVCostScalingFactor + * can change the HME bias inside RDO stage*/ + uint32_t globalMotionBiasAdjustmentEnable : 1; + /** MV cost scaling ratio for HME ( predictors. It is used when + * globalMotionBiasAdjustmentEnable == 1, else it is ignored. Values are: + * 0: set MV cost to be 0 for HME predictor. + * 1: scale MV cost to be 1/2 of the default value for HME predictor. + * 2: scale MV cost to be 1/4 of the default value for HME predictor. + * 3: scale MV cost to be 1/8 of the default value for HME predictor. */ + uint32_t HMEMVCostScalingFactor : 2; + /**disable HME, if it is disabled. Super*ultraHME should also be disabled */ + uint32_t HMEDisable : 1; + /**disable Super HME, if it is disabled, ultraHME should be disabled */ + uint32_t SuperHMEDisable : 1; + /** disable Ultra HME */ + uint32_t UltraHMEDisable : 1; + /** disable panic mode. Panic mode happened when there are extreme BRC (bit rate control) requirement + * frame size cant achieve the target of BRC. when Panic mode is triggered, Coefficients will + * be set to zero. disable panic mode will improve quality but will impact BRC */ + uint32_t PanicModeDisable : 1; + /** Force RepartitionCheck + * 0: DEFAULT - follow driver default settings. + * 1: FORCE_ENABLE - enable this feature totally for all cases. + * 2: FORCE_DISABLE - disable this feature totally for all cases. */ + uint32_t ForceRepartitionCheck : 2; + + }; + uint32_t encControls; + }; + + /** Maps QP to skip thresholds when FTQ is enabled. Valid range is 0-255. */ + uint8_t FTQSkipThresholdLUT[52]; + /** Maps QP to skip thresholds when FTQ is disabled. Valid range is 0-65535. */ + uint16_t NonFTQSkipThresholdLUT[52]; + + uint32_t reserved[VA_PADDING_HIGH]; // Reserved for future use. + +} VAEncMiscParameterEncQuality; + +/** + * \brief Custom Encoder Rounding Offset Control. + * Application may use this structure to set customized rounding + * offset parameters for quantization. + * Valid when \c VAConfigAttribCustomRoundingControl equals 1. + */ +typedef struct _VAEncMiscParameterCustomRoundingControl { + union { + struct { + /** \brief Enable customized rounding offset for intra blocks. + * If 0, default value would be taken by driver for intra + * rounding offset. + */ + uint32_t enable_custom_rouding_intra : 1 ; + + /** \brief Intra rounding offset + * Ignored if \c enable_custom_rouding_intra equals 0. + */ + uint32_t rounding_offset_intra : 7; + + /** \brief Enable customized rounding offset for inter blocks. + * If 0, default value would be taken by driver for inter + * rounding offset. + */ + uint32_t enable_custom_rounding_inter : 1 ; + + /** \brief Inter rounding offset + * Ignored if \c enable_custom_rouding_inter equals 0. + */ + uint32_t rounding_offset_inter : 7; + + /* Reserved */ + uint32_t reserved : 16; + } bits; + uint32_t value; + } rounding_offset_setting; +} VAEncMiscParameterCustomRoundingControl; + +/** + * There will be cases where the bitstream buffer will not have enough room to hold + * the data for the entire slice, and the following flags will be used in the slice + * parameter to signal to the server for the possible cases. + * If a slice parameter buffer and slice data buffer pair is sent to the server with + * the slice data partially in the slice data buffer (BEGIN and MIDDLE cases below), + * then a slice parameter and data buffer needs to be sent again to complete this slice. + */ +#define VA_SLICE_DATA_FLAG_ALL 0x00 /* whole slice is in the buffer */ +#define VA_SLICE_DATA_FLAG_BEGIN 0x01 /* The beginning of the slice is in the buffer but the end if not */ +#define VA_SLICE_DATA_FLAG_MIDDLE 0x02 /* Neither beginning nor end of the slice is in the buffer */ +#define VA_SLICE_DATA_FLAG_END 0x04 /* end of the slice is in the buffer */ + +/* Codec-independent Slice Parameter Buffer base */ +typedef struct _VASliceParameterBufferBase { + uint32_t slice_data_size; /* number of bytes in the slice data buffer for this slice */ + uint32_t slice_data_offset; /* the offset to the first byte of slice data */ + uint32_t slice_data_flag; /* see VA_SLICE_DATA_FLAG_XXX definitions */ +} VASliceParameterBufferBase; + +/********************************** + * JPEG common data structures + **********************************/ +/** + * \brief Huffman table for JPEG decoding. + * + * This structure holds the complete Huffman tables. This is an + * aggregation of all Huffman table (DHT) segments maintained by the + * application. i.e. up to 2 Huffman tables are stored in there for + * baseline profile. + * + * The #load_huffman_table array can be used as a hint to notify the + * VA driver implementation about which table(s) actually changed + * since the last submission of this buffer. + */ +typedef struct _VAHuffmanTableBufferJPEGBaseline { + /** \brief Specifies which #huffman_table is valid. */ + uint8_t load_huffman_table[2]; + /** \brief Huffman tables indexed by table identifier (Th). */ + struct { + /** @name DC table (up to 12 categories) */ + /**@{*/ + /** \brief Number of Huffman codes of length i + 1 (Li). */ + uint8_t num_dc_codes[16]; + /** \brief Value associated with each Huffman code (Vij). */ + uint8_t dc_values[12]; + /**@}*/ + /** @name AC table (2 special codes + up to 16 * 10 codes) */ + /**@{*/ + /** \brief Number of Huffman codes of length i + 1 (Li). */ + uint8_t num_ac_codes[16]; + /** \brief Value associated with each Huffman code (Vij). */ + uint8_t ac_values[162]; + /** \brief Padding to 4-byte boundaries. Must be set to zero. */ + uint8_t pad[2]; + /**@}*/ + } huffman_table[2]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAHuffmanTableBufferJPEGBaseline; + +/**************************** + * MPEG-2 data structures + ****************************/ + +/* MPEG-2 Picture Parameter Buffer */ +/* + * For each frame or field, and before any slice data, a single + * picture parameter buffer must be send. + */ +typedef struct _VAPictureParameterBufferMPEG2 { + uint16_t horizontal_size; + uint16_t vertical_size; + VASurfaceID forward_reference_picture; + VASurfaceID backward_reference_picture; + /* meanings of the following fields are the same as in the standard */ + int32_t picture_coding_type; + int32_t f_code; /* pack all four fcode into this */ + union { + struct { + uint32_t intra_dc_precision : 2; + uint32_t picture_structure : 2; + uint32_t top_field_first : 1; + uint32_t frame_pred_frame_dct : 1; + uint32_t concealment_motion_vectors : 1; + uint32_t q_scale_type : 1; + uint32_t intra_vlc_format : 1; + uint32_t alternate_scan : 1; + uint32_t repeat_first_field : 1; + uint32_t progressive_frame : 1; + uint32_t is_first_field : 1; /* indicate whether the current field + * is the first field for field picture + */ + } bits; + uint32_t value; + } picture_coding_extension; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAPictureParameterBufferMPEG2; + +/** MPEG-2 Inverse Quantization Matrix Buffer */ +typedef struct _VAIQMatrixBufferMPEG2 { + /** \brief Same as the MPEG-2 bitstream syntax element. */ + int32_t load_intra_quantiser_matrix; + /** \brief Same as the MPEG-2 bitstream syntax element. */ + int32_t load_non_intra_quantiser_matrix; + /** \brief Same as the MPEG-2 bitstream syntax element. */ + int32_t load_chroma_intra_quantiser_matrix; + /** \brief Same as the MPEG-2 bitstream syntax element. */ + int32_t load_chroma_non_intra_quantiser_matrix; + /** \brief Luminance intra matrix, in zig-zag scan order. */ + uint8_t intra_quantiser_matrix[64]; + /** \brief Luminance non-intra matrix, in zig-zag scan order. */ + uint8_t non_intra_quantiser_matrix[64]; + /** \brief Chroma intra matrix, in zig-zag scan order. */ + uint8_t chroma_intra_quantiser_matrix[64]; + /** \brief Chroma non-intra matrix, in zig-zag scan order. */ + uint8_t chroma_non_intra_quantiser_matrix[64]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAIQMatrixBufferMPEG2; + +/** MPEG-2 Slice Parameter Buffer */ +typedef struct _VASliceParameterBufferMPEG2 { + uint32_t slice_data_size;/* number of bytes in the slice data buffer for this slice */ + uint32_t slice_data_offset;/* the offset to the first byte of slice data */ + uint32_t slice_data_flag; /* see VA_SLICE_DATA_FLAG_XXX defintions */ + uint32_t macroblock_offset;/* the offset to the first bit of MB from the first byte of slice data */ + uint32_t slice_horizontal_position; + uint32_t slice_vertical_position; + int32_t quantiser_scale_code; + int32_t intra_slice_flag; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferMPEG2; + +/** MPEG-2 Macroblock Parameter Buffer */ +typedef struct _VAMacroblockParameterBufferMPEG2 { + uint16_t macroblock_address; + /* + * macroblock_address (in raster scan order) + * top-left: 0 + * bottom-right: picture-height-in-mb*picture-width-in-mb - 1 + */ + uint8_t macroblock_type; /* see definition below */ + union { + struct { + uint32_t frame_motion_type : 2; + uint32_t field_motion_type : 2; + uint32_t dct_type : 1; + } bits; + uint32_t value; + } macroblock_modes; + uint8_t motion_vertical_field_select; + /* + * motion_vertical_field_select: + * see section 6.3.17.2 in the spec + * only the lower 4 bits are used + * bit 0: first vector forward + * bit 1: first vector backward + * bit 2: second vector forward + * bit 3: second vector backward + */ + int16_t PMV[2][2][2]; /* see Table 7-7 in the spec */ + uint16_t coded_block_pattern; + /* + * The bitplanes for coded_block_pattern are described + * in Figure 6.10-12 in the spec + */ + + /* Number of skipped macroblocks after this macroblock */ + uint16_t num_skipped_macroblocks; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAMacroblockParameterBufferMPEG2; + +/* + * OR'd flags for macroblock_type (section 6.3.17.1 in the spec) + */ +#define VA_MB_TYPE_MOTION_FORWARD 0x02 +#define VA_MB_TYPE_MOTION_BACKWARD 0x04 +#define VA_MB_TYPE_MOTION_PATTERN 0x08 +#define VA_MB_TYPE_MOTION_INTRA 0x10 + +/** + * MPEG-2 Residual Data Buffer + * For each macroblock, there wil be 64 shorts (16-bit) in the + * residual data buffer + */ + +/**************************** + * MPEG-4 Part 2 data structures + ****************************/ + +/* MPEG-4 Picture Parameter Buffer */ +/* + * For each frame or field, and before any slice data, a single + * picture parameter buffer must be send. + */ +typedef struct _VAPictureParameterBufferMPEG4 { + uint16_t vop_width; + uint16_t vop_height; + VASurfaceID forward_reference_picture; + VASurfaceID backward_reference_picture; + union { + struct { + uint32_t short_video_header : 1; + uint32_t chroma_format : 2; + uint32_t interlaced : 1; + uint32_t obmc_disable : 1; + uint32_t sprite_enable : 2; + uint32_t sprite_warping_accuracy : 2; + uint32_t quant_type : 1; + uint32_t quarter_sample : 1; + uint32_t data_partitioned : 1; + uint32_t reversible_vlc : 1; + uint32_t resync_marker_disable : 1; + } bits; + uint32_t value; + } vol_fields; + uint8_t no_of_sprite_warping_points; + int16_t sprite_trajectory_du[3]; + int16_t sprite_trajectory_dv[3]; + uint8_t quant_precision; + union { + struct { + uint32_t vop_coding_type : 2; + uint32_t backward_reference_vop_coding_type : 2; + uint32_t vop_rounding_type : 1; + uint32_t intra_dc_vlc_thr : 3; + uint32_t top_field_first : 1; + uint32_t alternate_vertical_scan_flag : 1; + } bits; + uint32_t value; + } vop_fields; + uint8_t vop_fcode_forward; + uint8_t vop_fcode_backward; + uint16_t vop_time_increment_resolution; + /* short header related */ + uint8_t num_gobs_in_vop; + uint8_t num_macroblocks_in_gob; + /* for direct mode prediction */ + int16_t TRB; + int16_t TRD; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAPictureParameterBufferMPEG4; + +/** MPEG-4 Inverse Quantization Matrix Buffer */ +typedef struct _VAIQMatrixBufferMPEG4 { + /** Same as the MPEG-4:2 bitstream syntax element. */ + int32_t load_intra_quant_mat; + /** Same as the MPEG-4:2 bitstream syntax element. */ + int32_t load_non_intra_quant_mat; + /** The matrix for intra blocks, in zig-zag scan order. */ + uint8_t intra_quant_mat[64]; + /** The matrix for non-intra blocks, in zig-zag scan order. */ + uint8_t non_intra_quant_mat[64]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAIQMatrixBufferMPEG4; + +/** MPEG-4 Slice Parameter Buffer */ +typedef struct _VASliceParameterBufferMPEG4 { + uint32_t slice_data_size;/* number of bytes in the slice data buffer for this slice */ + uint32_t slice_data_offset;/* the offset to the first byte of slice data */ + uint32_t slice_data_flag; /* see VA_SLICE_DATA_FLAG_XXX defintions */ + uint32_t macroblock_offset;/* the offset to the first bit of MB from the first byte of slice data */ + uint32_t macroblock_number; + int32_t quant_scale; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferMPEG4; + +/** + VC-1 data structures +*/ + +typedef enum /* see 7.1.1.32 */ +{ + VAMvMode1Mv = 0, + VAMvMode1MvHalfPel = 1, + VAMvMode1MvHalfPelBilinear = 2, + VAMvModeMixedMv = 3, + VAMvModeIntensityCompensation = 4 +} VAMvModeVC1; + +/** VC-1 Picture Parameter Buffer */ +/* + * For each picture, and before any slice data, a picture parameter + * buffer must be send. Multiple picture parameter buffers may be + * sent for a single picture. In that case picture parameters will + * apply to all slice data that follow it until a new picture + * parameter buffer is sent. + * + * Notes: + * pic_quantizer_type should be set to the applicable quantizer + * type as defined by QUANTIZER (J.1.19) and either + * PQUANTIZER (7.1.1.8) or PQINDEX (7.1.1.6) + */ +typedef struct _VAPictureParameterBufferVC1 { + VASurfaceID forward_reference_picture; + VASurfaceID backward_reference_picture; + /* if out-of-loop post-processing is done on the render + target, then we need to keep the in-loop decoded + picture as a reference picture */ + VASurfaceID inloop_decoded_picture; + + /* sequence layer for AP or meta data for SP and MP */ + union { + struct { + uint32_t pulldown : 1; /* SEQUENCE_LAYER::PULLDOWN */ + uint32_t interlace : 1; /* SEQUENCE_LAYER::INTERLACE */ + uint32_t tfcntrflag : 1; /* SEQUENCE_LAYER::TFCNTRFLAG */ + uint32_t finterpflag : 1; /* SEQUENCE_LAYER::FINTERPFLAG */ + uint32_t psf : 1; /* SEQUENCE_LAYER::PSF */ + uint32_t multires : 1; /* METADATA::MULTIRES */ + uint32_t overlap : 1; /* METADATA::OVERLAP */ + uint32_t syncmarker : 1; /* METADATA::SYNCMARKER */ + uint32_t rangered : 1; /* METADATA::RANGERED */ + uint32_t max_b_frames : 3; /* METADATA::MAXBFRAMES */ + uint32_t profile : 2; /* SEQUENCE_LAYER::PROFILE or The MSB of METADATA::PROFILE */ + } bits; + uint32_t value; + } sequence_fields; + + uint16_t coded_width; /* ENTRY_POINT_LAYER::CODED_WIDTH */ + uint16_t coded_height; /* ENTRY_POINT_LAYER::CODED_HEIGHT */ + union { + struct { + uint32_t broken_link : 1; /* ENTRY_POINT_LAYER::BROKEN_LINK */ + uint32_t closed_entry : 1; /* ENTRY_POINT_LAYER::CLOSED_ENTRY */ + uint32_t panscan_flag : 1; /* ENTRY_POINT_LAYER::PANSCAN_FLAG */ + uint32_t loopfilter : 1; /* ENTRY_POINT_LAYER::LOOPFILTER */ + } bits; + uint32_t value; + } entrypoint_fields; + uint8_t conditional_overlap_flag; /* ENTRY_POINT_LAYER::CONDOVER */ + uint8_t fast_uvmc_flag; /* ENTRY_POINT_LAYER::FASTUVMC */ + union { + struct { + uint32_t luma_flag : 1; /* ENTRY_POINT_LAYER::RANGE_MAPY_FLAG */ + uint32_t luma : 3; /* ENTRY_POINT_LAYER::RANGE_MAPY */ + uint32_t chroma_flag : 1; /* ENTRY_POINT_LAYER::RANGE_MAPUV_FLAG */ + uint32_t chroma : 3; /* ENTRY_POINT_LAYER::RANGE_MAPUV */ + } bits; + uint32_t value; + } range_mapping_fields; + + uint8_t b_picture_fraction; /* Index for PICTURE_LAYER::BFRACTION value in Table 40 (7.1.1.14) */ + uint8_t cbp_table; /* PICTURE_LAYER::CBPTAB/ICBPTAB */ + uint8_t mb_mode_table; /* PICTURE_LAYER::MBMODETAB */ + uint8_t range_reduction_frame;/* PICTURE_LAYER::RANGEREDFRM */ + uint8_t rounding_control; /* PICTURE_LAYER::RNDCTRL */ + uint8_t post_processing; /* PICTURE_LAYER::POSTPROC */ + uint8_t picture_resolution_index; /* PICTURE_LAYER::RESPIC */ + uint8_t luma_scale; /* PICTURE_LAYER::LUMSCALE */ + uint8_t luma_shift; /* PICTURE_LAYER::LUMSHIFT */ + + union { + struct { + uint32_t picture_type : 3; /* PICTURE_LAYER::PTYPE */ + uint32_t frame_coding_mode : 3; /* PICTURE_LAYER::FCM */ + uint32_t top_field_first : 1; /* PICTURE_LAYER::TFF */ + uint32_t is_first_field : 1; /* set to 1 if it is the first field */ + uint32_t intensity_compensation : 1; /* PICTURE_LAYER::INTCOMP */ + } bits; + uint32_t value; + } picture_fields; + union { + struct { + uint32_t mv_type_mb : 1; /* PICTURE::MVTYPEMB */ + uint32_t direct_mb : 1; /* PICTURE::DIRECTMB */ + uint32_t skip_mb : 1; /* PICTURE::SKIPMB */ + uint32_t field_tx : 1; /* PICTURE::FIELDTX */ + uint32_t forward_mb : 1; /* PICTURE::FORWARDMB */ + uint32_t ac_pred : 1; /* PICTURE::ACPRED */ + uint32_t overflags : 1; /* PICTURE::OVERFLAGS */ + } flags; + uint32_t value; + } raw_coding; + union { + struct { + uint32_t bp_mv_type_mb : 1; /* PICTURE::MVTYPEMB */ + uint32_t bp_direct_mb : 1; /* PICTURE::DIRECTMB */ + uint32_t bp_skip_mb : 1; /* PICTURE::SKIPMB */ + uint32_t bp_field_tx : 1; /* PICTURE::FIELDTX */ + uint32_t bp_forward_mb : 1; /* PICTURE::FORWARDMB */ + uint32_t bp_ac_pred : 1; /* PICTURE::ACPRED */ + uint32_t bp_overflags : 1; /* PICTURE::OVERFLAGS */ + } flags; + uint32_t value; + } bitplane_present; /* signal what bitplane is being passed via the bitplane buffer */ + union { + struct { + uint32_t reference_distance_flag : 1;/* PICTURE_LAYER::REFDIST_FLAG */ + uint32_t reference_distance : 5;/* PICTURE_LAYER::REFDIST */ + uint32_t num_reference_pictures: 1;/* PICTURE_LAYER::NUMREF */ + uint32_t reference_field_pic_indicator : 1;/* PICTURE_LAYER::REFFIELD */ + } bits; + uint32_t value; + } reference_fields; + union { + struct { + uint32_t mv_mode : 3; /* PICTURE_LAYER::MVMODE */ + uint32_t mv_mode2 : 3; /* PICTURE_LAYER::MVMODE2 */ + uint32_t mv_table : 3; /* PICTURE_LAYER::MVTAB/IMVTAB */ + uint32_t two_mv_block_pattern_table: 2; /* PICTURE_LAYER::2MVBPTAB */ + uint32_t four_mv_switch : 1; /* PICTURE_LAYER::4MVSWITCH */ + uint32_t four_mv_block_pattern_table : 2; /* PICTURE_LAYER::4MVBPTAB */ + uint32_t extended_mv_flag : 1; /* ENTRY_POINT_LAYER::EXTENDED_MV */ + uint32_t extended_mv_range : 2; /* PICTURE_LAYER::MVRANGE */ + uint32_t extended_dmv_flag : 1; /* ENTRY_POINT_LAYER::EXTENDED_DMV */ + uint32_t extended_dmv_range : 2; /* PICTURE_LAYER::DMVRANGE */ + } bits; + uint32_t value; + } mv_fields; + union { + struct { + uint32_t dquant : 2; /* ENTRY_POINT_LAYER::DQUANT */ + uint32_t quantizer : 2; /* ENTRY_POINT_LAYER::QUANTIZER */ + uint32_t half_qp : 1; /* PICTURE_LAYER::HALFQP */ + uint32_t pic_quantizer_scale : 5;/* PICTURE_LAYER::PQUANT */ + uint32_t pic_quantizer_type : 1;/* PICTURE_LAYER::PQUANTIZER */ + uint32_t dq_frame : 1; /* VOPDQUANT::DQUANTFRM */ + uint32_t dq_profile : 2; /* VOPDQUANT::DQPROFILE */ + uint32_t dq_sb_edge : 2; /* VOPDQUANT::DQSBEDGE */ + uint32_t dq_db_edge : 2; /* VOPDQUANT::DQDBEDGE */ + uint32_t dq_binary_level : 1; /* VOPDQUANT::DQBILEVEL */ + uint32_t alt_pic_quantizer : 5;/* VOPDQUANT::ALTPQUANT */ + } bits; + uint32_t value; + } pic_quantizer_fields; + union { + struct { + uint32_t variable_sized_transform_flag : 1;/* ENTRY_POINT_LAYER::VSTRANSFORM */ + uint32_t mb_level_transform_type_flag : 1;/* PICTURE_LAYER::TTMBF */ + uint32_t frame_level_transform_type : 2;/* PICTURE_LAYER::TTFRM */ + uint32_t transform_ac_codingset_idx1 : 2;/* PICTURE_LAYER::TRANSACFRM */ + uint32_t transform_ac_codingset_idx2 : 2;/* PICTURE_LAYER::TRANSACFRM2 */ + uint32_t intra_transform_dc_table : 1;/* PICTURE_LAYER::TRANSDCTAB */ + } bits; + uint32_t value; + } transform_fields; + + uint8_t luma_scale2; /* PICTURE_LAYER::LUMSCALE2 */ + uint8_t luma_shift2; /* PICTURE_LAYER::LUMSHIFT2 */ + uint8_t intensity_compensation_field; /* Index for PICTURE_LAYER::INTCOMPFIELD value in Table 109 (9.1.1.48) */ + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM - 1]; +} VAPictureParameterBufferVC1; + +/** VC-1 Bitplane Buffer +There will be at most three bitplanes coded in any picture header. To send +the bitplane data more efficiently, each byte is divided in two nibbles, with +each nibble carrying three bitplanes for one macroblock. The following table +shows the bitplane data arrangement within each nibble based on the picture +type. + +Picture Type Bit3 Bit2 Bit1 Bit0 +I or BI OVERFLAGS ACPRED FIELDTX +P MYTYPEMB SKIPMB DIRECTMB +B FORWARDMB SKIPMB DIRECTMB + +Within each byte, the lower nibble is for the first MB and the upper nibble is +for the second MB. E.g. the lower nibble of the first byte in the bitplane +buffer is for Macroblock #1 and the upper nibble of the first byte is for +Macroblock #2 in the first row. +*/ + +/* VC-1 Slice Parameter Buffer */ +typedef struct _VASliceParameterBufferVC1 { + uint32_t slice_data_size;/* number of bytes in the slice data buffer for this slice */ + uint32_t slice_data_offset;/* the offset to the first byte of slice data */ + uint32_t slice_data_flag; /* see VA_SLICE_DATA_FLAG_XXX defintions */ + uint32_t macroblock_offset;/* the offset to the first bit of MB from the first byte of slice data */ + uint32_t slice_vertical_position; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferVC1; + +/* VC-1 Slice Data Buffer */ +/* +This is simplely a buffer containing raw bit-stream bytes +*/ + +/**************************** + * H.264/AVC data structures + ****************************/ + +typedef struct _VAPictureH264 { + VASurfaceID picture_id; + uint32_t frame_idx; + uint32_t flags; + int32_t TopFieldOrderCnt; + int32_t BottomFieldOrderCnt; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAPictureH264; +/* flags in VAPictureH264 could be OR of the following */ +#define VA_PICTURE_H264_INVALID 0x00000001 +#define VA_PICTURE_H264_TOP_FIELD 0x00000002 +#define VA_PICTURE_H264_BOTTOM_FIELD 0x00000004 +#define VA_PICTURE_H264_SHORT_TERM_REFERENCE 0x00000008 +#define VA_PICTURE_H264_LONG_TERM_REFERENCE 0x00000010 + +/** H.264 Picture Parameter Buffer */ +/* + * For each picture, and before any slice data, a single + * picture parameter buffer must be send. + */ +typedef struct _VAPictureParameterBufferH264 { + VAPictureH264 CurrPic; + VAPictureH264 ReferenceFrames[16]; /* in DPB */ + uint16_t picture_width_in_mbs_minus1; + uint16_t picture_height_in_mbs_minus1; + uint8_t bit_depth_luma_minus8; + uint8_t bit_depth_chroma_minus8; + uint8_t num_ref_frames; + union { + struct { + uint32_t chroma_format_idc : 2; + uint32_t residual_colour_transform_flag : 1; /* Renamed to separate_colour_plane_flag in newer standard versions. */ + uint32_t gaps_in_frame_num_value_allowed_flag : 1; + uint32_t frame_mbs_only_flag : 1; + uint32_t mb_adaptive_frame_field_flag : 1; + uint32_t direct_8x8_inference_flag : 1; + uint32_t MinLumaBiPredSize8x8 : 1; /* see A.3.3.2 */ + uint32_t log2_max_frame_num_minus4 : 4; + uint32_t pic_order_cnt_type : 2; + uint32_t log2_max_pic_order_cnt_lsb_minus4 : 4; + uint32_t delta_pic_order_always_zero_flag : 1; + } bits; + uint32_t value; + } seq_fields; + // FMO is not supported. + va_deprecated uint8_t num_slice_groups_minus1; + va_deprecated uint8_t slice_group_map_type; + va_deprecated uint16_t slice_group_change_rate_minus1; + int8_t pic_init_qp_minus26; + int8_t pic_init_qs_minus26; + int8_t chroma_qp_index_offset; + int8_t second_chroma_qp_index_offset; + union { + struct { + uint32_t entropy_coding_mode_flag : 1; + uint32_t weighted_pred_flag : 1; + uint32_t weighted_bipred_idc : 2; + uint32_t transform_8x8_mode_flag : 1; + uint32_t field_pic_flag : 1; + uint32_t constrained_intra_pred_flag : 1; + uint32_t pic_order_present_flag : 1; /* Renamed to bottom_field_pic_order_in_frame_present_flag in newer standard versions. */ + uint32_t deblocking_filter_control_present_flag : 1; + uint32_t redundant_pic_cnt_present_flag : 1; + uint32_t reference_pic_flag : 1; /* nal_ref_idc != 0 */ + } bits; + uint32_t value; + } pic_fields; + uint16_t frame_num; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAPictureParameterBufferH264; + +/** H.264 Inverse Quantization Matrix Buffer */ +typedef struct _VAIQMatrixBufferH264 { + /** \brief 4x4 scaling list, in raster scan order. */ + uint8_t ScalingList4x4[6][16]; + /** \brief 8x8 scaling list, in raster scan order. */ + uint8_t ScalingList8x8[2][64]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAIQMatrixBufferH264; + +/** H.264 Slice Parameter Buffer */ +typedef struct _VASliceParameterBufferH264 { + uint32_t slice_data_size;/* number of bytes in the slice data buffer for this slice */ + /** \brief Byte offset to the NAL Header Unit for this slice. */ + uint32_t slice_data_offset; + uint32_t slice_data_flag; /* see VA_SLICE_DATA_FLAG_XXX defintions */ + /** + * \brief Bit offset from NAL Header Unit to the begining of slice_data(). + * + * This bit offset is relative to and includes the NAL unit byte + * and represents the number of bits parsed in the slice_header() + * after the removal of any emulation prevention bytes in + * there. However, the slice data buffer passed to the hardware is + * the original bitstream, thus including any emulation prevention + * bytes. + */ + uint16_t slice_data_bit_offset; + uint16_t first_mb_in_slice; + uint8_t slice_type; + uint8_t direct_spatial_mv_pred_flag; + /** + * H264/AVC syntax element + * + * if num_ref_idx_active_override_flag equals 0, host decoder should + * set its value to num_ref_idx_l0_default_active_minus1. + */ + uint8_t num_ref_idx_l0_active_minus1; + /** + * H264/AVC syntax element + * + * if num_ref_idx_active_override_flag equals 0, host decoder should + * set its value to num_ref_idx_l1_default_active_minus1. + */ + uint8_t num_ref_idx_l1_active_minus1; + uint8_t cabac_init_idc; + int8_t slice_qp_delta; + uint8_t disable_deblocking_filter_idc; + int8_t slice_alpha_c0_offset_div2; + int8_t slice_beta_offset_div2; + VAPictureH264 RefPicList0[32]; /* See 8.2.4.2 */ + VAPictureH264 RefPicList1[32]; /* See 8.2.4.2 */ + uint8_t luma_log2_weight_denom; + uint8_t chroma_log2_weight_denom; + uint8_t luma_weight_l0_flag; + int16_t luma_weight_l0[32]; + int16_t luma_offset_l0[32]; + uint8_t chroma_weight_l0_flag; + int16_t chroma_weight_l0[32][2]; + int16_t chroma_offset_l0[32][2]; + uint8_t luma_weight_l1_flag; + int16_t luma_weight_l1[32]; + int16_t luma_offset_l1[32]; + uint8_t chroma_weight_l1_flag; + int16_t chroma_weight_l1[32][2]; + int16_t chroma_offset_l1[32][2]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferH264; + +/**************************** + * Common encode data structures + ****************************/ +typedef enum { + VAEncPictureTypeIntra = 0, + VAEncPictureTypePredictive = 1, + VAEncPictureTypeBidirectional = 2, +} VAEncPictureType; + +/** + * \brief Encode Slice Parameter Buffer. + * + * @deprecated + * This is a deprecated encode slice parameter buffer, All applications + * \c can use VAEncSliceParameterBufferXXX (XXX = MPEG2, HEVC, H264, JPEG) + */ +typedef struct _VAEncSliceParameterBuffer { + uint32_t start_row_number; /* starting MB row number for this slice */ + uint32_t slice_height; /* slice height measured in MB */ + union { + struct { + uint32_t is_intra : 1; + uint32_t disable_deblocking_filter_idc : 2; + uint32_t uses_long_term_ref : 1; + uint32_t is_long_term_ref : 1; + } bits; + uint32_t value; + } slice_flags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSliceParameterBuffer; + + +/**************************** + * H.263 specific encode data structures + ****************************/ + +typedef struct _VAEncSequenceParameterBufferH263 { + uint32_t intra_period; + uint32_t bits_per_second; + uint32_t frame_rate; + uint32_t initial_qp; + uint32_t min_qp; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSequenceParameterBufferH263; + +typedef struct _VAEncPictureParameterBufferH263 { + VASurfaceID reference_picture; + VASurfaceID reconstructed_picture; + VABufferID coded_buf; + uint16_t picture_width; + uint16_t picture_height; + VAEncPictureType picture_type; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferH263; + +/**************************** + * MPEG-4 specific encode data structures + ****************************/ + +typedef struct _VAEncSequenceParameterBufferMPEG4 { + uint8_t profile_and_level_indication; + uint32_t intra_period; + uint32_t video_object_layer_width; + uint32_t video_object_layer_height; + uint32_t vop_time_increment_resolution; + uint32_t fixed_vop_rate; + uint32_t fixed_vop_time_increment; + uint32_t bits_per_second; + uint32_t frame_rate; + uint32_t initial_qp; + uint32_t min_qp; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSequenceParameterBufferMPEG4; + +typedef struct _VAEncPictureParameterBufferMPEG4 { + VASurfaceID reference_picture; + VASurfaceID reconstructed_picture; + VABufferID coded_buf; + uint16_t picture_width; + uint16_t picture_height; + uint32_t modulo_time_base; /* number of 1s */ + uint32_t vop_time_increment; + VAEncPictureType picture_type; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferMPEG4; + + + +/** Buffer functions */ + +/** + * Creates a buffer for "num_elements" elements of "size" bytes and + * initalize with "data". + * if "data" is null, then the contents of the buffer data store + * are undefined. + * Basically there are two ways to get buffer data to the server side. One is + * to call vaCreateBuffer() with a non-null "data", which results the data being + * copied to the data store on the server side. A different method that + * eliminates this copy is to pass null as "data" when calling vaCreateBuffer(), + * and then use vaMapBuffer() to map the data store from the server side to the + * client address space for access. + * The user must call vaDestroyBuffer() to destroy a buffer. + * Note: image buffers are created by the library, not the client. Please see + * vaCreateImage on how image buffers are managed. + */ +VAStatus vaCreateBuffer( + VADisplay dpy, + VAContextID context, + VABufferType type, /* in */ + unsigned int size, /* in */ + unsigned int num_elements, /* in */ + void *data, /* in */ + VABufferID *buf_id /* out */ +); + +/** + * Create a buffer for given width & height get unit_size, pitch, buf_id for 2D buffer + * for permb qp buffer, it will return unit_size for one MB or LCU and the pitch for alignments + * can call vaMapBuffer with this Buffer ID to get virtual address. + * e.g. AVC 1080P encode, 1920x1088, the size in MB is 120x68,but inside driver, + * maybe it should align with 256, and one byte present one Qp.so, call the function. + * then get unit_size = 1, pitch = 256. call vaMapBuffer to get the virtual address (pBuf). + * then read write the memory like 2D. the size is 256x68, application can only use 120x68 + * pBuf + 256 is the start of next line. + * different driver implementation maybe return different unit_size and pitch + */ +VAStatus vaCreateBuffer2( + VADisplay dpy, + VAContextID context, + VABufferType type, + unsigned int width, + unsigned int height, + unsigned int *unit_size, + unsigned int *pitch, + VABufferID *buf_id +); + +/** + * Convey to the server how many valid elements are in the buffer. + * e.g. if multiple slice parameters are being held in a single buffer, + * this will communicate to the server the number of slice parameters + * that are valid in the buffer. + */ +VAStatus vaBufferSetNumElements( + VADisplay dpy, + VABufferID buf_id, /* in */ + unsigned int num_elements /* in */ +); + + +/** + * device independent data structure for codedbuffer + */ + +/* + * FICTURE_AVE_QP(bit7-0): The average Qp value used during this frame + * LARGE_SLICE(bit8):At least one slice in the current frame was large + * enough for the encoder to attempt to limit its size. + * SLICE_OVERFLOW(bit9): At least one slice in the current frame has + * exceeded the maximum slice size specified. + * BITRATE_OVERFLOW(bit10): The peak bitrate was exceeded for this frame. + * BITRATE_HIGH(bit11): The frame size got within the safety margin of the maximum size (VCM only) + * AIR_MB_OVER_THRESHOLD: the number of MBs adapted to Intra MB + */ +#define VA_CODED_BUF_STATUS_PICTURE_AVE_QP_MASK 0xff +#define VA_CODED_BUF_STATUS_LARGE_SLICE_MASK 0x100 +#define VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK 0x200 +#define VA_CODED_BUF_STATUS_BITRATE_OVERFLOW 0x400 +#define VA_CODED_BUF_STATUS_BITRATE_HIGH 0x800 +/** + * \brief The frame has exceeded the maximum requested size. + * + * This flag indicates that the encoded frame size exceeds the value + * specified through a misc parameter buffer of type + * #VAEncMiscParameterTypeMaxFrameSize. + */ +#define VA_CODED_BUF_STATUS_FRAME_SIZE_OVERFLOW 0x1000 +/** + * \brief the bitstream is bad or corrupt. + */ +#define VA_CODED_BUF_STATUS_BAD_BITSTREAM 0x8000 +#define VA_CODED_BUF_STATUS_AIR_MB_OVER_THRESHOLD 0xff0000 + +/** + * \brief The coded buffer segment status contains frame encoding passes number + * + * This is the mask to get the number of encoding passes from the coded + * buffer segment status. + * NUMBER_PASS(bit24~bit27): the number for encoding passes executed for the coded frame. + * + */ +#define VA_CODED_BUF_STATUS_NUMBER_PASSES_MASK 0xf000000 + +/** + * \brief The coded buffer segment contains a single NAL unit. + * + * This flag indicates that the coded buffer segment contains a + * single NAL unit. This flag might be useful to the user for + * processing the coded buffer. + */ +#define VA_CODED_BUF_STATUS_SINGLE_NALU 0x10000000 + +/** + * \brief Coded buffer segment. + * + * #VACodedBufferSegment is an element of a linked list describing + * some information on the coded buffer. The coded buffer segment + * could contain either a single NAL unit, or more than one NAL unit. + * It is recommended (but not required) to return a single NAL unit + * in a coded buffer segment, and the implementation should set the + * VA_CODED_BUF_STATUS_SINGLE_NALU status flag if that is the case. + */ +typedef struct _VACodedBufferSegment { + /** + * \brief Size of the data buffer in this segment (in bytes). + */ + uint32_t size; + /** \brief Bit offset into the data buffer where the video data starts. */ + uint32_t bit_offset; + /** \brief Status set by the driver. See \c VA_CODED_BUF_STATUS_*. */ + uint32_t status; + /** \brief Reserved for future use. */ + uint32_t reserved; + /** \brief Pointer to the start of the data buffer. */ + void *buf; + /** + * \brief Pointer to the next #VACodedBufferSegment element, + * or \c NULL if there is none. + */ + void *next; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VACodedBufferSegment; + +/** + * Map data store of the buffer into the client's address space + * vaCreateBuffer() needs to be called with "data" set to NULL before + * calling vaMapBuffer() + * + * if buffer type is VAEncCodedBufferType, pbuf points to link-list of + * VACodedBufferSegment, and the list is terminated if "next" is NULL + */ +VAStatus vaMapBuffer( + VADisplay dpy, + VABufferID buf_id, /* in */ + void **pbuf /* out */ +); + +/** + * Map data store of the buffer into the client's address space + * this interface could be used to convey the operation hint + * backend driver could use these hint to optimize the implementations + */ + +/** \brief VA_MAPBUFFER_FLAG_DEFAULT is used when there are no flag specified + * same as VA_MAPBUFFER_FLAG_READ | VA_MAPBUFFER_FLAG_WRITE. + */ +#define VA_MAPBUFFER_FLAG_DEFAULT 0 +/** \brief application will read the surface after map */ +#define VA_MAPBUFFER_FLAG_READ 1 +/** \brief application will write the surface after map */ +#define VA_MAPBUFFER_FLAG_WRITE 2 + +VAStatus vaMapBuffer2( + VADisplay dpy, + VABufferID buf_id, /* in */ + void **pbuf, /* out */ + uint32_t flags /* in */ +); + +/** + * After client making changes to a mapped data store, it needs to + * "Unmap" it to let the server know that the data is ready to be + * consumed by the server + */ +VAStatus vaUnmapBuffer( + VADisplay dpy, + VABufferID buf_id /* in */ +); + +/** + * After this call, the buffer is deleted and this buffer_id is no longer valid + * + * A buffer can be re-used and sent to the server by another Begin/Render/End + * sequence if vaDestroyBuffer() is not called with this buffer. + * + * Note re-using a shared buffer (e.g. a slice data buffer) between the host and the + * hardware accelerator can result in performance dropping. + */ +VAStatus vaDestroyBuffer( + VADisplay dpy, + VABufferID buffer_id +); + +/** \brief VA buffer information */ +typedef struct { + /** \brief Buffer handle */ + uintptr_t handle; + /** \brief Buffer type (See \ref VABufferType). */ + uint32_t type; + /** + * \brief Buffer memory type (See \ref VASurfaceAttribMemoryType). + * + * On input to vaAcquireBufferHandle(), this field can serve as a hint + * to specify the set of memory types the caller is interested in. + * On successful return from vaAcquireBufferHandle(), the field is + * updated with the best matching memory type. + */ + uint32_t mem_type; + /** \brief Size of the underlying buffer. */ + size_t mem_size; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VABufferInfo; + +/** + * \brief Acquires buffer handle for external API usage + * + * Locks the VA buffer object \ref buf_id for external API usage like + * EGL or OpenCL (OCL). This function is a synchronization point. This + * means that any pending operation is guaranteed to be completed + * prior to returning from the function. + * + * If the referenced VA buffer object is the backing store of a VA + * surface, then this function acts as if vaSyncSurface() on the + * parent surface was called first. + * + * The \ref VABufferInfo argument shall be zero'ed on input. On + * successful output, the data structure is filled in with all the + * necessary buffer level implementation details like handle, type, + * memory type and memory size. + * + * Note: the external API implementation, or the application, can + * express the memory types it is interested in by filling in the \ref + * mem_type field accordingly. On successful output, the memory type + * that fits best the request and that was used is updated in the \ref + * VABufferInfo data structure. If none of the supplied memory types + * is supported, then a \ref VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE + * error is returned. + * + * The \ref VABufferInfo data is valid until vaReleaseBufferHandle() + * is called. Besides, no additional operation is allowed on any of + * the buffer parent object until vaReleaseBufferHandle() is called. + * e.g. decoding into a VA surface backed with the supplied VA buffer + * object \ref buf_id would fail with a \ref VA_STATUS_ERROR_SURFACE_BUSY + * error. + * + * Possible errors: + * - \ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation + * does not support this interface + * - \ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied + * - \ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied + * - \ref VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE: the implementation + * does not support exporting buffers of the specified type + * - \ref VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE: none of the requested + * memory types in \ref VABufferInfo.mem_type was supported + * + * @param[in] dpy the VA display + * @param[in] buf_id the VA buffer + * @param[in,out] buf_info the associated VA buffer information + * @return VA_STATUS_SUCCESS if successful + */ +VAStatus +vaAcquireBufferHandle(VADisplay dpy, VABufferID buf_id, VABufferInfo *buf_info); + +/** + * \brief Releases buffer after usage from external API + * + * Unlocks the VA buffer object \ref buf_id from external API usage like + * EGL or OpenCL (OCL). This function is a synchronization point. This + * means that any pending operation is guaranteed to be completed + * prior to returning from the function. + * + * The \ref VABufferInfo argument shall point to the original data + * structure that was obtained from vaAcquireBufferHandle(), unaltered. + * This is necessary so that the VA driver implementation could + * deallocate any resources that were needed. + * + * In any case, returning from this function invalidates any contents + * in \ref VABufferInfo. i.e. the underlyng buffer handle is no longer + * valid. Therefore, VA driver implementations are free to reset this + * data structure to safe defaults. + * + * Possible errors: + * - \ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation + * does not support this interface + * - \ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied + * - \ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied + * - \ref VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE: the implementation + * does not support exporting buffers of the specified type + * + * @param[in] dpy the VA display + * @param[in] buf_id the VA buffer + * @return VA_STATUS_SUCCESS if successful + */ +VAStatus +vaReleaseBufferHandle(VADisplay dpy, VABufferID buf_id); + +/** @name vaExportSurfaceHandle() flags + * + * @{ + */ +/** Export surface to be read by external API. */ +#define VA_EXPORT_SURFACE_READ_ONLY 0x0001 +/** Export surface to be written by external API. */ +#define VA_EXPORT_SURFACE_WRITE_ONLY 0x0002 +/** Export surface to be both read and written by external API. */ +#define VA_EXPORT_SURFACE_READ_WRITE 0x0003 +/** Export surface with separate layers. + * + * For example, NV12 surfaces should be exported as two separate + * planes for luma and chroma. + */ +#define VA_EXPORT_SURFACE_SEPARATE_LAYERS 0x0004 +/** Export surface with composed layers. + * + * For example, NV12 surfaces should be exported as a single NV12 + * composed object. + */ +#define VA_EXPORT_SURFACE_COMPOSED_LAYERS 0x0008 + +/** @} */ + +/** + * \brief Export a handle to a surface for use with an external API + * + * The exported handles are owned by the caller, and the caller is + * responsible for freeing them when no longer needed (e.g. by closing + * DRM PRIME file descriptors). + * + * This does not perform any synchronisation. If the contents of the + * surface will be read, vaSyncSurface() must be called before doing so. + * If the contents of the surface are written, then all operations must + * be completed externally before using the surface again by via VA-API + * functions. + * + * @param[in] dpy VA display. + * @param[in] surface_id Surface to export. + * @param[in] mem_type Memory type to export to. + * @param[in] flags Combination of flags to apply + * (VA_EXPORT_SURFACE_*). + * @param[out] descriptor Pointer to the descriptor structure to fill + * with the handle details. The type of this structure depends on + * the value of mem_type. + * + * @return Status code: + * - VA_STATUS_SUCCESS: Success. + * - VA_STATUS_ERROR_INVALID_DISPLAY: The display is not valid. + * - VA_STATUS_ERROR_UNIMPLEMENTED: The driver does not implement + * this interface. + * - VA_STATUS_ERROR_INVALID_SURFACE: The surface is not valid, or + * the surface is not exportable in the specified way. + * - VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE: The driver does not + * support exporting surfaces to the specified memory type. + */ +VAStatus vaExportSurfaceHandle(VADisplay dpy, + VASurfaceID surface_id, + uint32_t mem_type, uint32_t flags, + void *descriptor); + +/** + * Render (Video Decode/Encode/Processing) Pictures + * + * A picture represents either a frame or a field. + * + * The Begin/Render/End sequence sends the video decode/encode/processing buffers + * to the server + */ + +/** + * Get ready for a video pipeline + * - decode a picture to a target surface + * - encode a picture from a target surface + * - process a picture to a target surface + */ +VAStatus vaBeginPicture( + VADisplay dpy, + VAContextID context, + VASurfaceID render_target +); + +/** + * Send video decode, encode or processing buffers to the server. + */ +VAStatus vaRenderPicture( + VADisplay dpy, + VAContextID context, + VABufferID *buffers, + int num_buffers +); + +/** + * Make the end of rendering for a picture. + * The server should start processing all pending operations for this + * surface. This call is non-blocking. The client can start another + * Begin/Render/End sequence on a different render target. + * if VAContextID used in this function previously successfully passed + * vaMFAddContext call, real processing will be started during vaMFSubmit + */ +VAStatus vaEndPicture( + VADisplay dpy, + VAContextID context +); + +/** + * Make the end of rendering for a pictures in contexts passed with submission. + * The server should start processing all pending operations for contexts. + * All contexts passed should be associated through vaMFAddContext + * and call sequence Begin/Render/End performed. + * This call is non-blocking. The client can start another + * Begin/Render/End/vaMFSubmit sequence on a different render targets. + * Return values: + * VA_STATUS_SUCCESS - operation successful, context was removed. + * VA_STATUS_ERROR_INVALID_CONTEXT - mf_context or one of contexts are invalid + * due to mf_context not created or one of contexts not assotiated with mf_context + * through vaAddContext. + * VA_STATUS_ERROR_INVALID_PARAMETER - one of context has not submitted it's frame + * through vaBeginPicture vaRenderPicture vaEndPicture call sequence. + * dpy: display + * mf_context: Multi-Frame context + * contexts: list of contexts submitting their tasks for multi-frame operation. + * num_contexts: number of passed contexts. + */ +VAStatus vaMFSubmit( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID * contexts, + int num_contexts +); + +/* + +Synchronization + +*/ + +/** + * This function 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. + */ +VAStatus vaSyncSurface( + VADisplay dpy, + VASurfaceID render_target +); + +/** \brief Indicates an infinite timeout. */ +#define VA_TIMEOUT_INFINITE 0xFFFFFFFFFFFFFFFF + +/** + * \brief Synchronizes pending operations associated with the supplied surface. + * + * This function blocks during specified timeout (in nanoseconds) until + * all pending operations on the render target have been completed. + * If timeout is zero, the function returns immediately. + * + * Possible errors: + * - \ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation + * does not support this interface + * - \ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied + * - \ref VA_STATUS_ERROR_INVALID_SURFACE: an invalid surface was supplied + * - \ref VA_STATUS_ERROR_TIMEDOUT: synchronization is still in progress, + * client should call the function again to complete synchronization + * + * @param[in] dpy the VA display + * @param[in] surface the surface for which synchronization is performed + * @param[in] timeout_ns the timeout in nanoseconds + * + */ +VAStatus vaSyncSurface2( + VADisplay dpy, + VASurfaceID surface, + uint64_t timeout_ns +); + +typedef enum { + VASurfaceRendering = 1, /* Rendering in progress */ + VASurfaceDisplaying = 2, /* Displaying in progress (not safe to render into it) */ + /* this status is useful if surface is used as the source */ + /* of an overlay */ + VASurfaceReady = 4, /* not being rendered or displayed */ + VASurfaceSkipped = 8 /* Indicate a skipped frame during encode */ +} VASurfaceStatus; + +/** + * Find out any pending ops on the render target + */ +VAStatus vaQuerySurfaceStatus( + VADisplay dpy, + VASurfaceID render_target, + VASurfaceStatus *status /* out */ +); + +typedef enum { + VADecodeSliceMissing = 0, + VADecodeMBError = 1, + VADecodeReset = 2, +} VADecodeErrorType; + +/** + * Client calls vaQuerySurfaceError with VA_STATUS_ERROR_DECODING_ERROR, server side returns + * an array of structure VASurfaceDecodeMBErrors, and the array is terminated by setting status=-1 +*/ +typedef struct _VASurfaceDecodeMBErrors { + int32_t status; /* 1 if hardware has returned detailed info below, -1 means this record is invalid */ + uint32_t start_mb; /* start mb address with errors */ + uint32_t end_mb; /* end mb address with errors */ + VADecodeErrorType decode_error_type; + uint32_t num_mb; /* number of mbs with errors */ + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW - 1]; +} VASurfaceDecodeMBErrors; + +/** + * After the application gets VA_STATUS_ERROR_DECODING_ERROR after calling vaSyncSurface(), + * it can call vaQuerySurfaceError to find out further details on the particular error. + * VA_STATUS_ERROR_DECODING_ERROR should be passed in as "error_status". + * + * After the applications get VA_STATUS_HW_BUSY or VA_STATUS_SUCCESSFULL from vaSyncSurface(), + * it still can call vaQuerySurfaceError to find out further details to know if has real hw reset + * happened on this surface since umd and kmd could recover the context from reset with success in sometimes. + * VA_STATUS_HW_BUSY or VA_STATUS_SUCCESSFULL also could be passed in as "error_status". + * + * Upon the return, error_info will point to an array of _VASurfaceDecodeMBErrors structure, + * which is allocated and filled by libVA with detailed information on the VADecodeErrorType. + * The array is terminated if "status==-1" is detected. + */ +VAStatus vaQuerySurfaceError( + VADisplay dpy, + VASurfaceID surface, + VAStatus error_status, + void **error_info +); + +/** + * \brief Synchronizes pending operations associated with the supplied buffer. + * + * This function blocks during specified timeout (in nanoseconds) until + * all pending operations on the supplied buffer have been completed. + * If timeout is zero, the function returns immediately. + * + * Possible errors: + * - \ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation + * does not support this interface + * - \ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied + * - \ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied + * - \ref VA_STATUS_ERROR_TIMEDOUT: synchronization is still in progress, + * client should call the function again to complete synchronization + * + * @param[in] dpy the VA display + * @param[in] buf_id the buffer for which synchronization is performed + * @param[in] timeout_ns the timeout in nanoseconds + * + */ +VAStatus vaSyncBuffer( + VADisplay dpy, + VABufferID buf_id, + uint64_t timeout_ns +); + +/** + * Notes about synchronization interfaces: + * vaSyncSurface: + * 1. Allows to synchronize output surface (i.e. from decoding or VP) + * 2. Allows to synchronize all bitstreams being encoded from the given input surface (1->N pipelines). + * + * vaSyncSurface2: + * 1. The same as vaSyncSurface but allows to specify a timeout + * + * vaSyncBuffer: + * 1. Allows to synchronize output buffer (e.g. bitstream from encoding). + * Comparing to vaSyncSurface this function synchronizes given bitstream only. + */ + +/** + * Images and Subpictures + * VAImage is used to either get the surface data to client memory, or + * to copy image data in client memory to a surface. + * Both images, subpictures and surfaces follow the same 2D coordinate system where origin + * is at the upper left corner with positive X to the right and positive Y down + */ +#define VA_FOURCC(ch0, ch1, ch2, ch3) \ + ((unsigned long)(unsigned char) (ch0) | ((unsigned long)(unsigned char) (ch1) << 8) | \ + ((unsigned long)(unsigned char) (ch2) << 16) | ((unsigned long)(unsigned char) (ch3) << 24 )) + +/* Pre-defined fourcc codes. */ + +/** NV12: two-plane 8-bit YUV 4:2:0. + * The first plane contains Y, the second plane contains U and V in pairs of bytes. + */ +#define VA_FOURCC_NV12 0x3231564E +/** NV21: two-plane 8-bit YUV 4:2:0. + * Same as NV12, but with U and V swapped. + */ +#define VA_FOURCC_NV21 0x3132564E + +/** AI44: packed 4-bit YA. + * + * The bottom half of each byte contains luma, the top half contains alpha. + */ +#define VA_FOURCC_AI44 0x34344149 + +/** RGBA: packed 8-bit RGBA. + * + * Four bytes per pixel: red, green, blue, alpha. + */ +#define VA_FOURCC_RGBA 0x41424752 +/** RGBX: packed 8-bit RGB. + * + * Four bytes per pixel: red, green, blue, unspecified. + */ +#define VA_FOURCC_RGBX 0x58424752 +/** BGRA: packed 8-bit RGBA. + * + * Four bytes per pixel: blue, green, red, alpha. + */ +#define VA_FOURCC_BGRA 0x41524742 +/** BGRX: packed 8-bit RGB. + * + * Four bytes per pixel: blue, green, red, unspecified. + */ +#define VA_FOURCC_BGRX 0x58524742 +/** ARGB: packed 8-bit RGBA. + * + * Four bytes per pixel: alpha, red, green, blue. + */ +#define VA_FOURCC_ARGB 0x42475241 +/** XRGB: packed 8-bit RGB. + * + * Four bytes per pixel: unspecified, red, green, blue. + */ +#define VA_FOURCC_XRGB 0x42475258 +/** ABGR: packed 8-bit RGBA. + * + * Four bytes per pixel: alpha, blue, green, red. + */ +#define VA_FOURCC_ABGR 0x52474241 +/** XBGR: packed 8-bit RGB. + * + * Four bytes per pixel: unspecified, blue, green, red. + */ +#define VA_FOURCC_XBGR 0x52474258 + +/** UYUV: packed 8-bit YUV 4:2:2. + * + * Four bytes per pair of pixels: U, Y, U, V. + */ +#define VA_FOURCC_UYVY 0x59565955 +/** YUY2: packed 8-bit YUV 4:2:2. + * + * Four bytes per pair of pixels: Y, U, Y, V. + */ +#define VA_FOURCC_YUY2 0x32595559 +/** AYUV: packed 8-bit YUVA 4:4:4. + * + * Four bytes per pixel: A, Y, U, V. + */ +#define VA_FOURCC_AYUV 0x56555941 +/** NV11: two-plane 8-bit YUV 4:1:1. + * + * The first plane contains Y, the second plane contains U and V in pairs of bytes. + */ +#define VA_FOURCC_NV11 0x3131564e +/** YV12: three-plane 8-bit YUV 4:2:0. + * + * The three planes contain Y, V and U respectively. + */ +#define VA_FOURCC_YV12 0x32315659 +/** P208: two-plane 8-bit YUV 4:2:2. + * + * The first plane contains Y, the second plane contains U and V in pairs of bytes. + */ +#define VA_FOURCC_P208 0x38303250 +/** I420: three-plane 8-bit YUV 4:2:0. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_I420 0x30323449 +/** YV24: three-plane 8-bit YUV 4:4:4. + * + * The three planes contain Y, V and U respectively. + */ +#define VA_FOURCC_YV24 0x34325659 +/** YV32: four-plane 8-bit YUVA 4:4:4 + * + * The four planes contain Y, V, U and A respectively. + */ +#define VA_FOURCC_YV32 0x32335659 +/** Y800: 8-bit greyscale. + */ +#define VA_FOURCC_Y800 0x30303859 +/** IMC3: three-plane 8-bit YUV 4:2:0. + * + * Equivalent to YV12, but with the additional constraint that the pitch of all three planes + * must be the same. + */ +#define VA_FOURCC_IMC3 0x33434D49 +/** 411P: three-plane 8-bit YUV 4:1:1. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_411P 0x50313134 +/** 411R: three-plane 8-bit YUV. + * + * The subsampling is the transpose of 4:1:1 - full chroma appears on every fourth line. + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_411R 0x52313134 +/** 422H: three-plane 8-bit YUV 4:2:2. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_422H 0x48323234 +/** 422V: three-plane 8-bit YUV 4:4:0. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_422V 0x56323234 +/** 444P: three-plane 8-bit YUV 4:4:4. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_444P 0x50343434 + +/** RGBP: three-plane 8-bit RGB. + * + * The three planes contain red, green and blue respectively. + */ +#define VA_FOURCC_RGBP 0x50424752 +/** BGRP: three-plane 8-bit RGB. + * + * The three planes contain blue, green and red respectively. + */ +#define VA_FOURCC_BGRP 0x50524742 +/** RG16: packed 5/6-bit RGB. + * + * Each pixel is a two-byte little-endian value. + * Red, green and blue are found in bits 15:11, 10:5, 4:0 respectively. + */ +#define VA_FOURCC_RGB565 0x36314752 +/** BG16: packed 5/6-bit RGB. + * + * Each pixel is a two-byte little-endian value. + * Blue, green and red are found in bits 15:11, 10:5, 4:0 respectively. + */ +#define VA_FOURCC_BGR565 0x36314742 + +/** Y210: packed 10-bit YUV 4:2:2. + * + * Eight bytes represent a pair of pixels. Each sample is a two-byte little-endian value, + * with the bottom six bits ignored. The samples are in the order Y, U, Y, V. + */ +#define VA_FOURCC_Y210 0x30313259 +/** Y212: packed 12-bit YUV 4:2:2. + * + * Eight bytes represent a pair of pixels. Each sample is a two-byte little-endian value. + * The samples are in the order Y, U, Y, V. + */ +#define VA_FOURCC_Y212 0x32313259 +/** Y216: packed 16-bit YUV 4:2:2. + * + * Eight bytes represent a pair of pixels. Each sample is a two-byte little-endian value. + * The samples are in the order Y, U, Y, V. + */ +#define VA_FOURCC_Y216 0x36313259 +/** Y410: packed 10-bit YUVA 4:4:4. + * + * Each pixel is a four-byte little-endian value. + * A, V, Y, U are found in bits 31:30, 29:20, 19:10, 9:0 respectively. + */ +#define VA_FOURCC_Y410 0x30313459 +/** Y412 packed 12-bit YUVA 4:4:4. + * + * Each pixel is a set of four samples, each of which is a two-byte little-endian value. + * The samples are in the order A, V, Y, U. + */ +#define VA_FOURCC_Y412 0x32313459 +/** Y416: packed 16-bit YUVA 4:4:4. + * + * Each pixel is a set of four samples, each of which is a two-byte little-endian value. + * The samples are in the order A, V, Y, U. + */ +#define VA_FOURCC_Y416 0x36313459 + +/** YV16: three-plane 8-bit YUV 4:2:2. + * + * The three planes contain Y, V and U respectively. + */ +#define VA_FOURCC_YV16 0x36315659 +/** P010: two-plane 10-bit YUV 4:2:0. + * + * Each sample is a two-byte little-endian value with the bottom six bits ignored. + * The first plane contains Y, the second plane contains U and V in pairs of samples. + */ +#define VA_FOURCC_P010 0x30313050 +/** P012: two-plane 12-bit YUV 4:2:0. + * + * Each sample is a two-byte little-endian value with the bottom four bits ignored. + * The first plane contains Y, the second plane contains U and V in pairs of samples. + */ +#define VA_FOURCC_P012 0x32313050 +/** P016: two-plane 16-bit YUV 4:2:0. + * + * Each sample is a two-byte little-endian value. The first plane contains Y, the second + * plane contains U and V in pairs of samples. + */ +#define VA_FOURCC_P016 0x36313050 + +/** I010: three-plane 10-bit YUV 4:2:0. + * + * Each sample is a two-byte little-endian value with the top six bits ignored. + * The three planes contain Y, V and U respectively. + */ +#define VA_FOURCC_I010 0x30313049 + +/** IYUV: three-plane 8-bit YUV 4:2:0. + * + * @deprecated Use I420 instead. + */ +#define VA_FOURCC_IYUV 0x56555949 +/** + * 10-bit Pixel RGB formats. + */ +#define VA_FOURCC_A2R10G10B10 0x30335241 /* VA_FOURCC('A','R','3','0') */ +/** + * 10-bit Pixel BGR formats. + */ +#define VA_FOURCC_A2B10G10R10 0x30334241 /* VA_FOURCC('A','B','3','0') */ +/** + * 10-bit Pixel RGB formats without alpha. + */ +#define VA_FOURCC_X2R10G10B10 0x30335258 /* VA_FOURCC('X','R','3','0') */ +/** + * 10-bit Pixel BGR formats without alpha. + */ +#define VA_FOURCC_X2B10G10R10 0x30334258 /* VA_FOURCC('X','B','3','0') */ + +/** Y8: 8-bit greyscale. + * + * Only a single sample, 8 bit Y plane for monochrome images + */ +#define VA_FOURCC_Y8 0x20203859 +/** Y16: 16-bit greyscale. + * + * Only a single sample, 16 bit Y plane for monochrome images + */ +#define VA_FOURCC_Y16 0x20363159 +/** VYUV: packed 8-bit YUV 4:2:2. + * + * Four bytes per pair of pixels: V, Y, U, V. + */ +#define VA_FOURCC_VYUY 0x59555956 +/** YVYU: packed 8-bit YUV 4:2:2. + * + * Four bytes per pair of pixels: Y, V, Y, U. + */ +#define VA_FOURCC_YVYU 0x55595659 +/** AGRB64: three-plane 16-bit ARGB 16:16:16:16 + * + * The four planes contain: alpha, red, green, blue respectively. + */ +#define VA_FOURCC_ARGB64 0x34475241 +/** ABGR64: three-plane 16-bit ABGR 16:16:16:16 + * + * The four planes contain: alpha, blue, green, red respectively. + */ +#define VA_FOURCC_ABGR64 0x34474241 +/** XYUV: packed 8-bit YUVX 4:4:4. + * + * Four bytes per pixel: X, Y, U, V. + */ +#define VA_FOURCC_XYUV 0x56555958 +/** Q416: three-plane 16-bit YUV 4:4:4. + * + * The three planes contain Y, U and V respectively. + */ +#define VA_FOURCC_Q416 0x36313451 + +/* byte order */ +#define VA_LSB_FIRST 1 +#define VA_MSB_FIRST 2 + +typedef struct _VAImageFormat { + uint32_t fourcc; + uint32_t byte_order; /* VA_LSB_FIRST, VA_MSB_FIRST */ + uint32_t bits_per_pixel; + /* for RGB formats */ + uint32_t depth; /* significant bits per pixel */ + uint32_t red_mask; + uint32_t green_mask; + uint32_t blue_mask; + uint32_t alpha_mask; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAImageFormat; + +typedef VAGenericID VAImageID; + +typedef struct _VAImage { + VAImageID image_id; /* uniquely identify this image */ + VAImageFormat format; + VABufferID buf; /* image data buffer */ + /* + * Image data will be stored in a buffer of type VAImageBufferType to facilitate + * data store on the server side for optimal performance. The buffer will be + * created by the CreateImage function, and proper storage allocated based on the image + * size and format. This buffer is managed by the library implementation, and + * accessed by the client through the buffer Map/Unmap functions. + */ + uint16_t width; + uint16_t height; + uint32_t data_size; + uint32_t num_planes; /* can not be greater than 3 */ + /* + * An array indicating the scanline pitch in bytes for each plane. + * Each plane may have a different pitch. Maximum 3 planes for planar formats + */ + uint32_t pitches[3]; + /* + * An array indicating the byte offset from the beginning of the image data + * to the start of each plane. + */ + uint32_t offsets[3]; + + /* The following fields are only needed for paletted formats */ + int32_t num_palette_entries; /* set to zero for non-palette images */ + /* + * Each component is one byte and entry_bytes indicates the number of components in + * each entry (eg. 3 for YUV palette entries). set to zero for non-palette images + */ + int32_t entry_bytes; + /* + * An array of ascii characters describing the order of the components within the bytes. + * Only entry_bytes characters of the string are used. + */ + int8_t component_order[4]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAImage; + +/** Get maximum number of image formats supported by the implementation */ +int vaMaxNumImageFormats( + VADisplay dpy +); + +/** + * Query supported image formats + * The caller must provide a "format_list" array that can hold at + * least vaMaxNumImageFormats() entries. The actual number of formats + * returned in "format_list" is returned in "num_formats". + */ +VAStatus vaQueryImageFormats( + VADisplay dpy, + VAImageFormat *format_list, /* out */ + int *num_formats /* out */ +); + +/** + * Create a VAImage structure + * The width and height fields returned in the VAImage structure may get + * enlarged for some YUV formats. Upon return from this function, + * image->buf has been created and proper storage allocated by the library. + * The client can access the image through the Map/Unmap calls. + */ +VAStatus vaCreateImage( + VADisplay dpy, + VAImageFormat *format, + int width, + int height, + VAImage *image /* out */ +); + +/** + * Should call DestroyImage before destroying the surface it is bound to + */ +VAStatus vaDestroyImage( + VADisplay dpy, + VAImageID image +); + +VAStatus vaSetImagePalette( + VADisplay dpy, + VAImageID image, + /* + * pointer to an array holding the palette data. The size of the array is + * num_palette_entries * entry_bytes in size. The order of the components + * in the palette is described by the component_order in VAImage struct + */ + unsigned char *palette +); + +/** + * Retrive surface data into a VAImage + * Image must be in a format supported by the implementation + */ +VAStatus vaGetImage( + VADisplay dpy, + VASurfaceID surface, + int x, /* coordinates of the upper left source pixel */ + int y, + unsigned int width, /* width and height of the region */ + unsigned int height, + VAImageID image +); + +/** + * Copy data from a VAImage to a surface + * Image must be in a format supported by the implementation + * Returns a VA_STATUS_ERROR_SURFACE_BUSY if the surface + * shouldn't be rendered into when this is called + */ +VAStatus vaPutImage( + VADisplay dpy, + VASurfaceID surface, + VAImageID image, + int src_x, + int src_y, + unsigned int src_width, + unsigned int src_height, + int dest_x, + int dest_y, + unsigned int dest_width, + unsigned int dest_height +); + +/** + * Derive an VAImage from an existing surface. + * This interface will derive a VAImage and corresponding image buffer from + * an existing VA Surface. The image buffer can then be mapped/unmapped for + * direct CPU access. This operation is only possible on implementations with + * direct rendering capabilities and internal surface formats that can be + * represented with a VAImage. When the operation is not possible this interface + * will return VA_STATUS_ERROR_OPERATION_FAILED. Clients should then fall back + * to using vaCreateImage + vaPutImage to accomplish the same task in an + * indirect manner. + * + * Implementations should only return success when the resulting image buffer + * would be useable with vaMap/Unmap. + * + * When directly accessing a surface special care must be taken to insure + * proper synchronization with the graphics hardware. Clients should call + * vaQuerySurfaceStatus to insure that a surface is not the target of concurrent + * rendering or currently being displayed by an overlay. + * + * Additionally nothing about the contents of a surface should be assumed + * following a vaPutSurface. Implementations are free to modify the surface for + * scaling or subpicture blending within a call to vaPutImage. + * + * Calls to vaPutImage or vaGetImage using the same surface from which the image + * has been derived will return VA_STATUS_ERROR_SURFACE_BUSY. vaPutImage or + * vaGetImage with other surfaces is supported. + * + * An image created with vaDeriveImage should be freed with vaDestroyImage. The + * image and image buffer structures will be destroyed; however, the underlying + * surface will remain unchanged until freed with vaDestroySurfaces. + */ +VAStatus vaDeriveImage( + VADisplay dpy, + VASurfaceID surface, + VAImage *image /* out */ +); + +/** + * Subpictures + * Subpicture is a special type of image that can be blended + * with a surface during vaPutSurface(). Subpicture can be used to render + * DVD sub-titles or closed captioning text etc. + */ + +typedef VAGenericID VASubpictureID; + +/** Get maximum number of subpicture formats supported by the implementation */ +int vaMaxNumSubpictureFormats( + VADisplay dpy +); + +/** flags for subpictures */ +#define VA_SUBPICTURE_CHROMA_KEYING 0x0001 +#define VA_SUBPICTURE_GLOBAL_ALPHA 0x0002 +#define VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD 0x0004 +/** + * Query supported subpicture formats + * The caller must provide a "format_list" array that can hold at + * least vaMaxNumSubpictureFormats() entries. The flags arrary holds the flag + * for each format to indicate additional capabilities for that format. The actual + * number of formats returned in "format_list" is returned in "num_formats". + * flags: returned value to indicate addtional capabilities + * VA_SUBPICTURE_CHROMA_KEYING - supports chroma-keying + * VA_SUBPICTURE_GLOBAL_ALPHA - supports global alpha + * VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD - supports unscaled screen relative subpictures for On Screen Display + */ + +VAStatus vaQuerySubpictureFormats( + VADisplay dpy, + VAImageFormat *format_list, /* out */ + unsigned int *flags, /* out */ + unsigned int *num_formats /* out */ +); + +/** + * Subpictures are created with an image associated. + */ +VAStatus vaCreateSubpicture( + VADisplay dpy, + VAImageID image, + VASubpictureID *subpicture /* out */ +); + +/** + * Destroy the subpicture before destroying the image it is assocated to + */ +VAStatus vaDestroySubpicture( + VADisplay dpy, + VASubpictureID subpicture +); + +/** + * Bind an image to the subpicture. This image will now be associated with + * the subpicture instead of the one at creation. + */ +VAStatus vaSetSubpictureImage( + VADisplay dpy, + VASubpictureID subpicture, + VAImageID image +); + +/** + * If chromakey is enabled, then the area where the source value falls within + * the chromakey [min, max] range is transparent + * The chromakey component format is the following: + * For RGB: [0:7] Red [8:15] Blue [16:23] Green + * For YUV: [0:7] V [8:15] U [16:23] Y + * The chromakey mask can be used to mask out certain components for chromakey + * comparision + */ +VAStatus vaSetSubpictureChromakey( + VADisplay dpy, + VASubpictureID subpicture, + unsigned int chromakey_min, + unsigned int chromakey_max, + unsigned int chromakey_mask +); + +/** + * Global alpha value is between 0 and 1. A value of 1 means fully opaque and + * a value of 0 means fully transparent. If per-pixel alpha is also specified then + * the overall alpha is per-pixel alpha multiplied by the global alpha + */ +VAStatus vaSetSubpictureGlobalAlpha( + VADisplay dpy, + VASubpictureID subpicture, + float global_alpha +); + +/** + * vaAssociateSubpicture associates the subpicture with target_surfaces. + * It defines the region mapping between the subpicture and the target + * surfaces through source and destination rectangles (with the same width and height). + * Both will be displayed at the next call to vaPutSurface. Additional + * associations before the call to vaPutSurface simply overrides the association. + */ +VAStatus vaAssociateSubpicture( + VADisplay dpy, + VASubpictureID subpicture, + VASurfaceID *target_surfaces, + int num_surfaces, + int16_t src_x, /* upper left offset in subpicture */ + int16_t src_y, + uint16_t src_width, + uint16_t src_height, + int16_t dest_x, /* upper left offset in surface */ + int16_t dest_y, + uint16_t dest_width, + uint16_t dest_height, + /* + * whether to enable chroma-keying, global-alpha, or screen relative mode + * see VA_SUBPICTURE_XXX values + */ + uint32_t flags +); + +/** + * vaDeassociateSubpicture removes the association of the subpicture with target_surfaces. + */ +VAStatus vaDeassociateSubpicture( + VADisplay dpy, + VASubpictureID subpicture, + VASurfaceID *target_surfaces, + int num_surfaces +); + +/** + * Display attributes + * Display attributes are used to control things such as contrast, hue, saturation, + * brightness etc. in the rendering process. The application can query what + * attributes are supported by the driver, and then set the appropriate attributes + * before calling vaPutSurface() + * + * Display attributes can also be used to query/set platform or display adaptor (vaDisplay) + * related information. These attributes do not depend on vaConfig, and could not be used + * for vaPutSurface. Application can use vaQueryDisplayAttributes/vaGetDisplayAttributes + * at anytime after vaInitialize, but (for settable attributes) vaSetDisplayAttributes should be + * called after vaInitialize and before any other function call. + * + * To distinguish these two types of display attributes, display adaptor related attributes + * should be marked as "HW attribute" in the description. + */ + +/* PowerVR IEP Lite attributes */ +typedef enum { + VADISPLAYATTRIB_BLE_OFF = 0x00, + VADISPLAYATTRIB_BLE_LOW, + VADISPLAYATTRIB_BLE_MEDIUM, + VADISPLAYATTRIB_BLE_HIGH, + VADISPLAYATTRIB_BLE_NONE, +} VADisplayAttribBLEMode; + +/** attribute value for VADisplayAttribRotation */ +#define VA_ROTATION_NONE 0x00000000 +#define VA_ROTATION_90 0x00000001 +#define VA_ROTATION_180 0x00000002 +#define VA_ROTATION_270 0x00000003 +/**@}*/ + +/** + * @name Mirroring directions + * + * Those values could be used for VADisplayAttribMirror attribute or + * VAProcPipelineParameterBuffer::mirror_state. + + */ +/**@{*/ +/** \brief No Mirroring. */ +#define VA_MIRROR_NONE 0x00000000 +/** \brief Horizontal Mirroring. */ +#define VA_MIRROR_HORIZONTAL 0x00000001 +/** \brief Vertical Mirroring. */ +#define VA_MIRROR_VERTICAL 0x00000002 +/**@}*/ + +/** attribute value for VADisplayAttribOutOfLoopDeblock */ +#define VA_OOL_DEBLOCKING_FALSE 0x00000000 +#define VA_OOL_DEBLOCKING_TRUE 0x00000001 + +/** Render mode */ +#define VA_RENDER_MODE_UNDEFINED 0 +#define VA_RENDER_MODE_LOCAL_OVERLAY 1 +#define VA_RENDER_MODE_LOCAL_GPU 2 +#define VA_RENDER_MODE_EXTERNAL_OVERLAY 4 +#define VA_RENDER_MODE_EXTERNAL_GPU 8 + +/** Render device */ +#define VA_RENDER_DEVICE_UNDEFINED 0 +#define VA_RENDER_DEVICE_LOCAL 1 +#define VA_RENDER_DEVICE_EXTERNAL 2 + +/**\brief sub device info + * Sub-device is the concept basing on the "device" behind "vaDisplay". + * If a device could be divided to several sub devices, the task of + * decode/encode/vpp could be assigned on one sub-device. So, application + * could choose the sub device before any other operations. After that, + * all of the task execution/resource allocation will be dispatched to + * the sub device. If application does not choose the sub device, driver + * will assign one as default. + * + * If the value == VA_ATTRIB_NOT_SUPPORTED, it mean that the attribute + * is unsupport or UNKNOWN. + */ + +typedef union _VADisplayAttribValSubDevice { + struct { + /** \brief current sub device index, read - write */ + uint32_t current_sub_device : 4; + /** \brief sub devices count, read - only */ + uint32_t sub_device_count : 4; + /** \brief reserved bits for future, must be zero*/ + uint32_t reserved : 8; + /** \brief bit mask to indicate which sub_device is available, read only + * \code + * VADisplayAttribValSubDevice reg; + * VADisplayAttribute reg_attr; + * reg_attr.type = VADisplayAttribSubDevice; + * vaGetDisplayAttributes(dpy, ®_attr, 1); + * reg.value = reg_attr.value; + * + * for(int i = 0; i < reg.bits.sub_device_count; i ++ ){ + * if((1< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* _VA_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_android.h b/rs/moq-vaapi/libva/va/va_android.h new file mode 100644 index 00000000000..5df76aa9778 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_android.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef _VA_ANDROID_H_ +#define _VA_ANDROID_H_ + +#include + +/** \brief Android Gralloc buffer memory type. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_ANDROID_GRALLOC 0x00100000 +/** \brief Android ION buffer memory type. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_ANDROID_ION 0x00200000 + +#endif /* _VA_ANDROID_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_backend.h b/rs/moq-vaapi/libva/va/va_backend.h new file mode 100644 index 00000000000..3bbf08b4b99 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_backend.h @@ -0,0 +1,733 @@ +/* + * Copyright (c) 2007 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * Video Decode Acceleration -Backend API + */ + +#ifndef _VA_BACKEND_H_ +#define _VA_BACKEND_H_ + +#include + +typedef struct VADriverContext *VADriverContextP; +typedef struct VADisplayContext *VADisplayContextP; + +/** \brief VA display types. */ +enum { + /** \brief Mask to major identifier for VA display type. */ + VA_DISPLAY_MAJOR_MASK = 0xf0, + + /** \brief VA/X11 API is used, through vaGetDisplay() entry-point. */ + VA_DISPLAY_X11 = 0x10, + /** \brief VA/GLX API is used, through vaGetDisplayGLX() entry-point. */ + VA_DISPLAY_GLX = (VA_DISPLAY_X11 | (1 << 0)), + /** \brief VA/Android API is used, through vaGetDisplay() entry-point. */ + VA_DISPLAY_ANDROID va_deprecated_enum = 0x20, + /** \brief VA/DRM API is used, through vaGetDisplayDRM() entry-point. */ + VA_DISPLAY_DRM = 0x30, + /** \brief VA/DRM API is used, with a render-node device path */ + VA_DISPLAY_DRM_RENDERNODES = (VA_DISPLAY_DRM | (1 << 0)), + /** \brief VA/Wayland API is used, through vaGetDisplayWl() entry-point. */ + VA_DISPLAY_WAYLAND = 0x40, + /** \brief VA/Win32 API is used, through vaGetDisplayWin32() entry-point. */ + VA_DISPLAY_WIN32 = 0x80, +}; + +struct VADriverVTable { + VAStatus(*vaTerminate)(VADriverContextP ctx); + + VAStatus(*vaQueryConfigProfiles)( + VADriverContextP ctx, + VAProfile *profile_list, /* out */ + int *num_profiles /* out */ + ); + + VAStatus(*vaQueryConfigEntrypoints)( + VADriverContextP ctx, + VAProfile profile, + VAEntrypoint *entrypoint_list, /* out */ + int *num_entrypoints /* out */ + ); + + VAStatus(*vaGetConfigAttributes)( + VADriverContextP ctx, + VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, /* in/out */ + int num_attribs + ); + + VAStatus(*vaCreateConfig)( + VADriverContextP ctx, + VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, + int num_attribs, + VAConfigID *config_id /* out */ + ); + + VAStatus(*vaDestroyConfig)( + VADriverContextP ctx, + VAConfigID config_id + ); + + VAStatus(*vaQueryConfigAttributes)( + VADriverContextP ctx, + VAConfigID config_id, + VAProfile *profile, /* out */ + VAEntrypoint *entrypoint, /* out */ + VAConfigAttrib *attrib_list, /* out */ + int *num_attribs /* out */ + ); + + VAStatus(*vaCreateSurfaces)( + VADriverContextP ctx, + int width, + int height, + int format, + int num_surfaces, + VASurfaceID *surfaces /* out */ + ); + + VAStatus(*vaDestroySurfaces)( + VADriverContextP ctx, + VASurfaceID *surface_list, + int num_surfaces + ); + + VAStatus(*vaCreateContext)( + VADriverContextP ctx, + VAConfigID config_id, + int picture_width, + int picture_height, + int flag, + VASurfaceID *render_targets, + int num_render_targets, + VAContextID *context /* out */ + ); + + VAStatus(*vaDestroyContext)( + VADriverContextP ctx, + VAContextID context + ); + + VAStatus(*vaCreateBuffer)( + VADriverContextP ctx, + VAContextID context, /* in */ + VABufferType type, /* in */ + unsigned int size, /* in */ + unsigned int num_elements, /* in */ + void *data, /* in */ + VABufferID *buf_id + ); + + VAStatus(*vaBufferSetNumElements)( + VADriverContextP ctx, + VABufferID buf_id, /* in */ + unsigned int num_elements /* in */ + ); + + VAStatus(*vaMapBuffer)( + VADriverContextP ctx, + VABufferID buf_id, /* in */ + void **pbuf /* out */ + ); + + VAStatus(*vaUnmapBuffer)( + VADriverContextP ctx, + VABufferID buf_id /* in */ + ); + + VAStatus(*vaDestroyBuffer)( + VADriverContextP ctx, + VABufferID buffer_id + ); + + VAStatus(*vaBeginPicture)( + VADriverContextP ctx, + VAContextID context, + VASurfaceID render_target + ); + + VAStatus(*vaRenderPicture)( + VADriverContextP ctx, + VAContextID context, + VABufferID *buffers, + int num_buffers + ); + + VAStatus(*vaEndPicture)( + VADriverContextP ctx, + VAContextID context + ); + + VAStatus(*vaSyncSurface)( + VADriverContextP ctx, + VASurfaceID render_target + ); + + VAStatus(*vaQuerySurfaceStatus)( + VADriverContextP ctx, + VASurfaceID render_target, + VASurfaceStatus *status /* out */ + ); + + VAStatus(*vaQuerySurfaceError)( + VADriverContextP ctx, + VASurfaceID render_target, + VAStatus error_status, + void **error_info /*out*/ + ); + + VAStatus(*vaPutSurface)( + VADriverContextP ctx, + VASurfaceID surface, + void* draw, /* Drawable of window system */ + short srcx, + short srcy, + unsigned short srcw, + unsigned short srch, + short destx, + short desty, + unsigned short destw, + unsigned short desth, + VARectangle *cliprects, /* client supplied clip list */ + unsigned int number_cliprects, /* number of clip rects in the clip list */ + unsigned int flags /* de-interlacing flags */ + ); + + VAStatus(*vaQueryImageFormats)( + VADriverContextP ctx, + VAImageFormat *format_list, /* out */ + int *num_formats /* out */ + ); + + VAStatus(*vaCreateImage)( + VADriverContextP ctx, + VAImageFormat *format, + int width, + int height, + VAImage *image /* out */ + ); + + VAStatus(*vaDeriveImage)( + VADriverContextP ctx, + VASurfaceID surface, + VAImage *image /* out */ + ); + + VAStatus(*vaDestroyImage)( + VADriverContextP ctx, + VAImageID image + ); + + VAStatus(*vaSetImagePalette)( + VADriverContextP ctx, + VAImageID image, + /* + * pointer to an array holding the palette data. The size of the array is + * num_palette_entries * entry_bytes in size. The order of the components + * in the palette is described by the component_order in VAImage struct + */ + unsigned char *palette + ); + + VAStatus(*vaGetImage)( + VADriverContextP ctx, + VASurfaceID surface, + int x, /* coordinates of the upper left source pixel */ + int y, + unsigned int width, /* width and height of the region */ + unsigned int height, + VAImageID image + ); + + VAStatus(*vaPutImage)( + VADriverContextP ctx, + VASurfaceID surface, + VAImageID image, + int src_x, + int src_y, + unsigned int src_width, + unsigned int src_height, + int dest_x, + int dest_y, + unsigned int dest_width, + unsigned int dest_height + ); + + VAStatus(*vaQuerySubpictureFormats)( + VADriverContextP ctx, + VAImageFormat *format_list, /* out */ + unsigned int *flags, /* out */ + unsigned int *num_formats /* out */ + ); + + VAStatus(*vaCreateSubpicture)( + VADriverContextP ctx, + VAImageID image, + VASubpictureID *subpicture /* out */ + ); + + VAStatus(*vaDestroySubpicture)( + VADriverContextP ctx, + VASubpictureID subpicture + ); + + VAStatus(*vaSetSubpictureImage)( + VADriverContextP ctx, + VASubpictureID subpicture, + VAImageID image + ); + + VAStatus(*vaSetSubpictureChromakey)( + VADriverContextP ctx, + VASubpictureID subpicture, + unsigned int chromakey_min, + unsigned int chromakey_max, + unsigned int chromakey_mask + ); + + VAStatus(*vaSetSubpictureGlobalAlpha)( + VADriverContextP ctx, + VASubpictureID subpicture, + float global_alpha + ); + + VAStatus(*vaAssociateSubpicture)( + VADriverContextP ctx, + VASubpictureID subpicture, + VASurfaceID *target_surfaces, + int num_surfaces, + short src_x, /* upper left offset in subpicture */ + short src_y, + unsigned short src_width, + unsigned short src_height, + short dest_x, /* upper left offset in surface */ + short dest_y, + unsigned short dest_width, + unsigned short dest_height, + /* + * whether to enable chroma-keying or global-alpha + * see VA_SUBPICTURE_XXX values + */ + unsigned int flags + ); + + VAStatus(*vaDeassociateSubpicture)( + VADriverContextP ctx, + VASubpictureID subpicture, + VASurfaceID *target_surfaces, + int num_surfaces + ); + + VAStatus(*vaQueryDisplayAttributes)( + VADriverContextP ctx, + VADisplayAttribute *attr_list, /* out */ + int *num_attributes /* out */ + ); + + VAStatus(*vaGetDisplayAttributes)( + VADriverContextP ctx, + VADisplayAttribute *attr_list, /* in/out */ + int num_attributes + ); + + VAStatus(*vaSetDisplayAttributes)( + VADriverContextP ctx, + VADisplayAttribute *attr_list, + int num_attributes + ); + + /* used by va trace */ + VAStatus(*vaBufferInfo)( + VADriverContextP ctx, /* in */ + VABufferID buf_id, /* in */ + VABufferType *type, /* out */ + unsigned int *size, /* out */ + unsigned int *num_elements /* out */ + ); + + /* lock/unlock surface for external access */ + VAStatus(*vaLockSurface)( + VADriverContextP ctx, + VASurfaceID surface, + unsigned int *fourcc, /* out for follow argument */ + unsigned int *luma_stride, + unsigned int *chroma_u_stride, + unsigned int *chroma_v_stride, + unsigned int *luma_offset, + unsigned int *chroma_u_offset, + unsigned int *chroma_v_offset, + unsigned int *buffer_name, /* if it is not NULL, assign the low lever + * surface buffer name + */ + void **buffer /* if it is not NULL, map the surface buffer for + * CPU access + */ + ); + + VAStatus(*vaUnlockSurface)( + VADriverContextP ctx, + VASurfaceID surface + ); + + /* DEPRECATED */ + VAStatus + (*vaGetSurfaceAttributes)( + VADriverContextP dpy, + VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int num_attribs + ); + + VAStatus + (*vaCreateSurfaces2)( + VADriverContextP ctx, + unsigned int format, + unsigned int width, + unsigned int height, + VASurfaceID *surfaces, + unsigned int num_surfaces, + VASurfaceAttrib *attrib_list, + unsigned int num_attribs + ); + + VAStatus + (*vaQuerySurfaceAttributes)( + VADriverContextP dpy, + VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int *num_attribs + ); + + VAStatus + (*vaAcquireBufferHandle)( + VADriverContextP ctx, + VABufferID buf_id, /* in */ + VABufferInfo * buf_info /* in/out */ + ); + + VAStatus + (*vaReleaseBufferHandle)( + VADriverContextP ctx, + VABufferID buf_id /* in */ + ); + + VAStatus(*vaCreateMFContext)( + VADriverContextP ctx, + VAMFContextID *mfe_context /* out */ + ); + + VAStatus(*vaMFAddContext)( + VADriverContextP ctx, + VAMFContextID mf_context, + VAContextID context + ); + + VAStatus(*vaMFReleaseContext)( + VADriverContextP ctx, + VAMFContextID mf_context, + VAContextID context + ); + + VAStatus(*vaMFSubmit)( + VADriverContextP ctx, + VAMFContextID mf_context, + VAContextID *contexts, + int num_contexts + ); + VAStatus(*vaCreateBuffer2)( + VADriverContextP ctx, + VAContextID context, /* in */ + VABufferType type, /* in */ + unsigned int width, /* in */ + unsigned int height, /* in */ + unsigned int *unit_size, /* out */ + unsigned int *pitch, /* out */ + VABufferID *buf_id /* out */ + ); + + VAStatus(*vaQueryProcessingRate)( + VADriverContextP ctx, /* in */ + VAConfigID config_id, /* in */ + VAProcessingRateParameter *proc_buf,/* in */ + unsigned int *processing_rate /* out */ + ); + + VAStatus + (*vaExportSurfaceHandle)( + VADriverContextP ctx, + VASurfaceID surface_id, /* in */ + uint32_t mem_type, /* in */ + uint32_t flags, /* in */ + void *descriptor /* out */ + ); + VAStatus(*vaSyncSurface2)( + VADriverContextP ctx, + VASurfaceID surface, + uint64_t timeout_ns + ); + + VAStatus(*vaSyncBuffer)( + VADriverContextP ctx, + VABufferID buf_id, + uint64_t timeout_ns + ); + + VAStatus + (*vaCopy)( + VADriverContextP ctx, /* in */ + VACopyObject *dst, /* in */ + VACopyObject *src, /* in */ + VACopyOption option /* in */ + ); + + VAStatus(*vaMapBuffer2)( + VADriverContextP ctx, + VABufferID buf_id, /* in */ + void **pbuf, /* out */ + uint32_t flags /* in */ + ); + /** \brief Reserved bytes for future use, must be zero */ + unsigned long reserved[53]; + +}; + +struct VADriverContext { + void *pDriverData; + + /** + * The core VA implementation hooks. + * + * This structure is allocated from libva with calloc(). + */ + struct VADriverVTable *vtable; + + /** + * The VA/GLX implementation hooks. + * + * This structure is intended for drivers that implement the + * VA/GLX API. The driver implementation is responsible for the + * allocation and deallocation of this structure. + */ + struct VADriverVTableGLX *vtable_glx; + + /** + * The VA/EGL implementation hooks. + * + * This structure is intended for drivers that implement the + * VA/EGL API. The driver implementation is responsible for the + * allocation and deallocation of this structure. + */ + struct VADriverVTableEGL *vtable_egl; + + /** + * The third-party/private implementation hooks. + * + * This structure is intended for drivers that implement the + * private API. The driver implementation is responsible for the + * allocation and deallocation of this structure. + */ + void *vtable_tpi; + + void *native_dpy; + int x11_screen; + int version_major; + int version_minor; + int max_profiles; + int max_entrypoints; + int max_attributes; + int max_image_formats; + int max_subpic_formats; + int max_display_attributes; + const char *str_vendor; + + void *handle; /* dlopen handle */ + + /** + * \brief DRM state. + * + * This field holds driver specific data for DRM-based + * drivers. This structure is allocated from libva with + * calloc(). Do not deallocate from within VA driver + * implementations. + * + * All structures shall be derived from struct drm_state. So, for + * instance, this field holds a dri_state structure for VA/X11 + * drivers that use the DRM protocol. + */ + void *drm_state; + + void *glx; /* opaque for GLX code */ + + /** \brief VA display type. */ + unsigned long display_type; + + /** + * The VA/Wayland implementation hooks. + * + * This structure is intended for drivers that implement the + * VA/Wayland API. libVA allocates this structure with calloc() + * and owns the resulting memory. + */ + struct VADriverVTableWayland *vtable_wayland; + + /** + * \brief The VA/VPP implementation hooks. + * + * This structure is allocated from libva with calloc(). + */ + struct VADriverVTableVPP *vtable_vpp; + + char *override_driver_name; + + void *pDisplayContext; + + /** + * Error callback. + * + * This is set by libva when the driver is opened, and will not be + * changed thereafter. The driver can call it with an error message, + * which will be propagated to the API user through their error + * callbacks, or sent to a default output if no callback is available. + * + * It is expected that end users will always be able to see these + * messages, so it should be called only for serious errors. For + * example, hardware problems or fatal configuration errors. + * + * @param pDriverContext Pointer to the driver context structure + * being used by the current driver. + * @param message Message to send to the API user. This must be a + * null-terminated string. + */ + void (*error_callback)(VADriverContextP pDriverContext, + const char *message); + /** + * Info callback. + * + * This has the same behaviour as the error callback, but has its + * own set of callbacks to the API user. + * + * It should be used for informational messages which may be useful + * for an application programmer or for debugging. For example, minor + * configuration errors, or information about the reason when another + * API call generates an error return. It is not expected that end + * users will see these messages. + * + * @param pDriverContext Pointer to the driver context structure + * being used by the current driver. + * @param message Message to send to the API user. This must be a + * null-terminated string. + */ + void (*info_callback)(VADriverContextP pDriverContext, + const char *message); + + /** + * \brief The VA/Protected implementation hooks. + * + * This structure is allocated from libva with calloc(). + */ + struct VADriverVTableProt *vtable_prot; + + unsigned long reserved[37]; /* reserve for future add-ins, decrease the subscript accordingly */ +}; + +#define VA_DISPLAY_MAGIC 0x56414430 /* VAD0 */ +struct VADisplayContext { + int vadpy_magic; + + VADisplayContextP pNext; + VADriverContextP pDriverContext; + + /* Deprecated */ + int (*vaIsValid)( + VADisplayContextP ctx + ); + + void (*vaDestroy)( + VADisplayContextP ctx + ); + + /* Deprecated */ + VAStatus(*vaGetDriverName)( + VADisplayContextP ctx, + char **driver_name + ); + + void *opaque; /* opaque for display extensions (e.g. GLX) */ + void *vatrace; /* opaque for VA trace context */ + /* Deprecated */ + void *vafool; /* opaque for VA fool context */ + + VAMessageCallback error_callback; + void *error_callback_user_context; + VAMessageCallback info_callback; + void *info_callback_user_context; + + /* Deprecated */ + VAStatus(*vaGetNumCandidates)( + VADisplayContextP ctx, + int * num_candidates + ); + + /* Deprecated */ + VAStatus(*vaGetDriverNameByIndex)( + VADisplayContextP ctx, + char **driver_name, + int candidate_index + ); + + /** + * \brief Callback to get an array of driver names. + * + * + * The caller must provide a num_drivers + * This structure is allocated from libva with calloc(). + * + * @param drivers An num_drivers sized array of null terminated strings. + * The array is managed my the caller. The callee will + * populate the individual driver name strings and the + * caller must free them. + * @param num_driver The number of driver strings contained within drivers. + * The caller must set that to the size of the drivers + * array, where the callee will update the value to + * min(caller num_driver, num_drivers_support). + */ + VAStatus(*vaGetDriverNames)( + VADisplayContextP ctx, + char **drivers, + unsigned *num_drivers + ); + + /** \brief Reserved bytes for future use, must be zero */ + unsigned long reserved[29]; +}; + +typedef VAStatus(*VADriverInit)( + VADriverContextP driver_context +); + +#endif /* _VA_BACKEND_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_backend_prot.h b/rs/moq-vaapi/libva/va/va_backend_prot.h new file mode 100644 index 00000000000..93447e11ffc --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_backend_prot.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2020 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_BACKEND_PROT_H +#define VA_BACKEND_PROT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \brief VTable version for VA/PROTECTION hooks. */ +#define VA_DRIVER_VTABLE_PROT_VERSION 1 + +struct VADriverVTableProt { + unsigned int version; + + VAStatus + (*vaCreateProtectedSession)( + VADriverContextP ctx, + VAConfigID config_id, + VAProtectedSessionID *protected_session + ); + + VAStatus + (*vaDestroyProtectedSession)( + VADriverContextP ctx, + VAProtectedSessionID protected_session + ); + + VAStatus + (*vaAttachProtectedSession)( + VADriverContextP ctx, + VAContextID context, + VAProtectedSessionID protected_session + ); + + VAStatus + (*vaDetachProtectedSession)( + VADriverContextP ctx, + VAContextID context + ); + + VAStatus + (*vaProtectedSessionExecute)( + VADriverContextP ctx, + VAProtectedSessionID protected_session, + VABufferID buf_id + ); + + /** \brief Reserved bytes for future use, must be zero */ + unsigned long reserved[VA_PADDING_MEDIUM]; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* VA_BACKEND_PROT_H */ diff --git a/rs/moq-vaapi/libva/va/va_backend_vpp.h b/rs/moq-vaapi/libva/va/va_backend_vpp.h new file mode 100644 index 00000000000..8ed10d5fa57 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_backend_vpp.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2007-2011 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_BACKEND_VPP_H +#define VA_BACKEND_VPP_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \brief VTable version for VA/VPP hooks. */ +#define VA_DRIVER_VTABLE_VPP_VERSION 1 + +struct VADriverVTableVPP { + unsigned int version; + + VAStatus + (*vaQueryVideoProcFilters)( + VADriverContextP ctx, + VAContextID context, + VAProcFilterType *filters, + unsigned int *num_filters + ); + + VAStatus + (*vaQueryVideoProcFilterCaps)( + VADriverContextP ctx, + VAContextID context, + VAProcFilterType type, + void *filter_caps, + unsigned int *num_filter_caps + ); + + VAStatus + (*vaQueryVideoProcPipelineCaps)( + VADriverContextP ctx, + VAContextID context, + VABufferID *filters, + unsigned int num_filters, + VAProcPipelineCaps *pipeline_caps + ); + + /** \brief Reserved bytes for future use, must be zero */ + unsigned long reserved[16]; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* VA_BACKEND_VPP_H */ diff --git a/rs/moq-vaapi/libva/va/va_compat.h b/rs/moq-vaapi/libva/va/va_compat.h new file mode 100644 index 00000000000..41a3f73e7e0 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_compat.h @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2007-2011 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_compat.h + * \brief The Compatibility API + * + * This file contains the \ref api_compat "Compatibility API". + */ + +#ifndef VA_COMPAT_H +#define VA_COMPAT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_compat Compatibility API + * + * The Compatibility API allows older programs that are not ported to + * the current API to still build and run correctly. In particular, + * this exposes older API to allow for backwards source compatibility. + * + * @{ + */ + +/** + * Makes a string literal out of the macro argument + */ +#define VA_CPP_HELPER_STRINGIFY(x) \ + VA_CPP_HELPER_STRINGIFY_(x) +#define VA_CPP_HELPER_STRINGIFY_(x) \ + #x + +/** + * Concatenates two macro arguments at preprocessing time. + */ +#define VA_CPP_HELPER_CONCAT(a, b) \ + VA_CPP_HELPER_CONCAT_(a, b) +#define VA_CPP_HELPER_CONCAT_(a, b) \ + a ## b + +/** + * Generates the number of macro arguments at preprocessing time. + * + * + * Note: this doesn't work for macros with no arguments + */ +#define VA_CPP_HELPER_N_ARGS(...) \ + VA_CPP_HELPER_N_ARGS_(__VA_ARGS__, VA_CPP_HELPER_N_ARGS_LIST_REV()) +#define VA_CPP_HELPER_N_ARGS_(...) \ + VA_CPP_HELPER_N_ARGS_LIST(__VA_ARGS__) +#define VA_CPP_HELPER_N_ARGS_LIST(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a12, a13, a14, a15, a16, N, ...) N +#define VA_CPP_HELPER_N_ARGS_LIST_REV() \ + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +/** + * Generates a versioned function alias. + * + * VA_CPP_HELPER_ALIAS(vaSomeFunction, 0,32,0) will generate + * .symber vaSomeFunction_0_32_0, vaSomeFunction@VA_API_0.32.0 + */ +#define VA_CPP_HELPER_ALIAS(func, major, minor, micro) \ + VA_CPP_HELPER_ALIAS_(func, major, minor, micro, "@") +#define VA_CPP_HELPER_ALIAS_DEFAULT(func, major, minor, micro) \ + VA_CPP_HELPER_ALIAS_(func, major, minor, micro, "@@") +#define VA_CPP_HELPER_ALIAS_(func, major, minor, micro, binding) \ + asm(".symver " #func "_" #major "_" #minor "_" #micro ", " \ + #func binding "VA_API_" #major "." #minor "." #micro) + +/* vaCreateSurfaces() */ + +#ifndef VA_COMPAT_DISABLED +#define vaCreateSurfaces(dpy, ...) \ + VA_CPP_HELPER_CONCAT(vaCreateSurfaces, \ + VA_CPP_HELPER_N_ARGS(dpy, __VA_ARGS__)) \ + (dpy, __VA_ARGS__) +#endif + +#define vaCreateSurfaces6(dpy, width, height, format, num_surfaces, surfaces) \ + (vaCreateSurfaces)(dpy, format, width, height, surfaces, num_surfaces, \ + NULL, 0) + +#define vaCreateSurfaces8(dpy, format, width, height, surfaces, num_surfaces, attribs, num_attribs) \ + (vaCreateSurfaces)(dpy, format, width, height, surfaces, num_surfaces, \ + attribs, num_attribs) + +/*@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_COMPAT_H */ diff --git a/rs/moq-vaapi/libva/va/va_dec_av1.h b/rs/moq-vaapi/libva/va/va_dec_av1.h new file mode 100644 index 00000000000..c19553857ca --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_dec_av1.h @@ -0,0 +1,695 @@ +/* + * Copyright (c) 2019 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_dec_av1.h + * \brief The AV1 decoding API + * + * This file contains the \ref api_dec_av1 "AV1 decoding API". + */ + +#ifndef VA_DEC_AV1_H +#define VA_DEC_AV1_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_dec_av1 AV1 decoding API + * + * This AV1 decoding API supports 8-bit/10bit 420 format only. + * + * @{ + */ + +/** Attribute value for VAConfigAttribDecAV1Features. + * + * This attribute decribes the supported features of a AV1 + * decoder configuration. + * + */ +typedef union VAConfigAttribValDecAV1Features { + struct { + /** large scale tile + * + * This conveys whether AV1 large scale tile is supported by HW. + * 0 - unsupported, 1 - supported. + */ + uint32_t lst_support : 2; + /* Reserved for future use. */ + uint32_t reserved : 30; + } bits; + uint32_t value; +} VAConfigAttribValDecAV1Features; + +/** + * \brief AV1 Decoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters. + * App should send a surface with this data structure down to VAAPI once + * per frame. + * + */ + +/** \brief Segmentation Information + */ +typedef struct _VASegmentationStructAV1 { + union { + struct { + /** Indicates whether segmentation map related syntax elements + * are present or not for current frame. If equal to 0, + * the segmentation map related syntax elements are + * not present for the current frame and the control flags of + * segmentation map related tables feature_data[][], and + * feature_mask[] are not valid and shall be ignored by accelerator. + */ + uint32_t enabled : 1; + /** Value 1 indicates that the segmentation map are updated + * during the decoding of this frame. + * Value 0 means that the segmentation map from the previous + * frame is used. + */ + uint32_t update_map : 1; + /** Value 1 indicates that the updates to the segmentation map + * are coded relative to the existing segmentation map. + * Value 0 indicates that the new segmentation map is coded + * without reference to the existing segmentation map. + */ + uint32_t temporal_update : 1; + /** Value 1 indicates that new parameters are about to be + * specified for each segment. + * Value 0 indicates that the segmentation parameters + * should keep their existing values. + */ + uint32_t update_data : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 28; + } bits; + uint32_t value; + } segment_info_fields; + + /** \brief Segmentation parameters for current frame. + * feature_data[segment_id][feature_id] + * where segment_id has value range [0..7] indicating the segment id. + * and feature_id is defined as + typedef enum { + SEG_LVL_ALT_Q, // Use alternate Quantizer .... + SEG_LVL_ALT_LF_Y_V, // Use alternate loop filter value on y plane vertical + SEG_LVL_ALT_LF_Y_H, // Use alternate loop filter value on y plane horizontal + SEG_LVL_ALT_LF_U, // Use alternate loop filter value on u plane + SEG_LVL_ALT_LF_V, // Use alternate loop filter value on v plane + SEG_LVL_REF_FRAME, // Optional Segment reference frame + SEG_LVL_SKIP, // Optional Segment (0,0) + skip mode + SEG_LVL_GLOBALMV, + SEG_LVL_MAX + } SEG_LVL_FEATURES; + * feature_data[][] is equivalent to variable FeatureData[][] in spec, + * which is after clip3() operation. + * Clip3(x, y, z) = (z < x)? x : ((z > y)? y : z); + * The limit is defined in Segmentation_Feature_Max[ SEG_LVL_MAX ] = { + * 255, MAX_LOOP_FILTER, MAX_LOOP_FILTER, MAX_LOOP_FILTER, MAX_LOOP_FILTER, 7, 0, 0 } + */ + int16_t feature_data[8][8]; + + /** \brief indicates if a feature is enabled or not. + * Each bit field itself is the feature_id. Index is segment_id. + * feature_mask[segment_id] & (1 << feature_id) equal to 1 specify that the feature of + * feature_id for segment of segment_id is enabled, otherwise disabled. + */ + uint8_t feature_mask[8]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VASegmentationStructAV1; + +/** \brief Film Grain Information + */ +typedef struct _VAFilmGrainStructAV1 { + union { + struct { + /** \brief Specify whether or not film grain is applied on current frame. + * If set to 0, all the rest parameters should be set to zero + * and ignored. + */ + uint32_t apply_grain : 1; + uint32_t chroma_scaling_from_luma : 1; + uint32_t grain_scaling_minus_8 : 2; + uint32_t ar_coeff_lag : 2; + uint32_t ar_coeff_shift_minus_6 : 2; + uint32_t grain_scale_shift : 2; + uint32_t overlap_flag : 1; + uint32_t clip_to_restricted_range : 1; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 20; + } bits; + uint32_t value; + } film_grain_info_fields; + + uint16_t grain_seed; + /* value range [0..14] */ + uint8_t num_y_points; + uint8_t point_y_value[14]; + uint8_t point_y_scaling[14]; + /* value range [0..10] */ + uint8_t num_cb_points; + uint8_t point_cb_value[10]; + uint8_t point_cb_scaling[10]; + /* value range [0..10] */ + uint8_t num_cr_points; + uint8_t point_cr_value[10]; + uint8_t point_cr_scaling[10]; + /* value range [-128..127] */ + int8_t ar_coeffs_y[24]; + int8_t ar_coeffs_cb[25]; + int8_t ar_coeffs_cr[25]; + uint8_t cb_mult; + uint8_t cb_luma_mult; + uint16_t cb_offset; + uint8_t cr_mult; + uint8_t cr_luma_mult; + uint16_t cr_offset; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VAFilmGrainStructAV1; + +typedef enum { + /** identity transformation, 0-parameter */ + VAAV1TransformationIdentity = 0, + /** translational motion, 2-parameter */ + VAAV1TransformationTranslation = 1, + /** simplified affine with rotation + zoom only, 4-parameter */ + VAAV1TransformationRotzoom = 2, + /** affine, 6-parameter */ + VAAV1TransformationAffine = 3, + /** transformation count */ + VAAV1TransformationCount +} VAAV1TransformationType; + +typedef struct _VAWarpedMotionParamsAV1 { + + /** \brief Specify the type of warped motion */ + VAAV1TransformationType wmtype; + + /** \brief Specify warp motion parameters + * wm.wmmat[] corresponds to gm_params[][] in spec. + * Details in AV1 spec section 5.9.24 or refer to libaom code + * https://aomedia.googlesource.com/aom/+/refs/heads/master/av1/decoder/decodeframe.c + */ + int32_t wmmat[8]; + + /* valid or invalid on affine set */ + uint8_t invalid; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VAWarpedMotionParamsAV1; + +/** + * \brief AV1 Decoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters and should be sent once + * per frame. + * + */ +typedef struct _VADecPictureParameterBufferAV1 { + /**@{*/ + + /** \brief sequence level information + */ + + /** \brief AV1 bit stream profile + */ + uint8_t profile; + + uint8_t order_hint_bits_minus_1; + + /** \brief bit depth index + * value range [0..2] + * 0 - bit depth 8; + * 1 - bit depth 10; + * 2 - bit depth 12; + */ + uint8_t bit_depth_idx; + + /** \brief corresponds to AV1 spec variable of the same name. */ + uint8_t matrix_coefficients; + + union { + struct { + uint32_t still_picture : 1; + uint32_t use_128x128_superblock : 1; + uint32_t enable_filter_intra : 1; + uint32_t enable_intra_edge_filter : 1; + + /** read_compound_tools */ + uint32_t enable_interintra_compound : 1; + uint32_t enable_masked_compound : 1; + + uint32_t enable_dual_filter : 1; + uint32_t enable_order_hint : 1; + uint32_t enable_jnt_comp : 1; + uint32_t enable_cdef : 1; + uint32_t mono_chrome : 1; + uint32_t color_range : 1; + uint32_t subsampling_x : 1; + uint32_t subsampling_y : 1; + va_deprecated uint32_t chroma_sample_position : 1; + uint32_t film_grain_params_present : 1; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 16; + } fields; + uint32_t value; + } seq_info_fields; + + /** \brief Picture level information + */ + + /** \brief buffer description of decoded current picture + */ + VASurfaceID current_frame; + + /** \brief display buffer of current picture + * Used for film grain applied decoded picture. + * Valid only when apply_grain equals 1. + */ + VASurfaceID current_display_picture; + + /** \brief number of anchor frames for large scale tile + * This parameter gives the number of entries of anchor_frames_list[]. + * Value range [0..128]. + */ + uint8_t anchor_frames_num; + + /** \brief anchor frame list for large scale tile + * For large scale tile applications, the anchor frames could come from + * previously decoded frames in current sequence (aka. internal), or + * from external sources. + * For external anchor frames, application should call API + * vaCreateBuffer() to generate frame buffers and populate them with + * pixel frames. And this process may happen multiple times. + * The array anchor_frames_list[] is used to register all the available + * anchor frames from both external and internal, up to the current + * frame instance. If a previously registerred anchor frame is no longer + * needed, it should be removed from the list. But it does not prevent + * applications from relacing the frame buffer with new anchor frames. + * Please note that the internal anchor frames may not still be present + * in the current DPB buffer. But if it is in the anchor_frames_list[], + * it should not be replaced with other frames or removed from memory + * until it is not shown in the list. + * This number of entries of the list is given by parameter anchor_frames_num. + */ + VASurfaceID *anchor_frames_list; + + /** \brief Picture resolution minus 1 + * Picture original resolution. If SuperRes is enabled, + * this is the upscaled resolution. + * value range [0..65535] + */ + uint16_t frame_width_minus1; + uint16_t frame_height_minus1; + + /** \brief Output frame buffer size in unit of tiles + * Valid only when large_scale_tile equals 1. + * value range [0..65535] + */ + uint16_t output_frame_width_in_tiles_minus_1; + uint16_t output_frame_height_in_tiles_minus_1; + + /** \brief Surface indices of reference frames in DPB. + * + * Contains a list of uncompressed frame buffer surface indices as references. + * Application needs to make sure all the entries point to valid frames + * except for intra frames by checking ref_frame_id[]. If missing frame + * is identified, application may choose to perform error recovery by + * pointing problematic index to an alternative frame buffer. + * Driver is not responsible to validate reference frames' id. + */ + VASurfaceID ref_frame_map[8]; + + /** \brief Reference frame indices. + * + * Contains a list of indices into ref_frame_map[8]. + * It specifies the reference frame correspondence. + * The indices of the array are defined as [LAST_FRAME – LAST_FRAME, + * LAST2_FRAME – LAST_FRAME, …, ALTREF_FRAME – LAST_FRAME], where each + * symbol is defined as: + * enum{INTRA_FRAME = 0, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, + * BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME}; + */ + uint8_t ref_frame_idx[7]; + + /** \brief primary reference frame index + * Index into ref_frame_idx[], specifying which reference frame contains + * propagated info that should be loaded at the start of the frame. + * When value equals PRIMARY_REF_NONE (7), it indicates there is + * no primary reference frame. + * value range [0..7] + */ + uint8_t primary_ref_frame; + + uint8_t order_hint; + + VASegmentationStructAV1 seg_info; + VAFilmGrainStructAV1 film_grain_info; + + /** \brief tile structure + * When uniform_tile_spacing_flag == 1, width_in_sbs_minus_1[] and + * height_in_sbs_minus_1[] should be ignored, which will be generated + * by driver based on tile_cols and tile_rows. + */ + uint8_t tile_cols; + uint8_t tile_rows; + + /* The width/height of a tile minus 1 in units of superblocks. Though the + * maximum number of tiles is 64, since ones of the last tile are computed + * from ones of the other tiles and frame_width/height, they are not + * necessarily specified. + */ + uint16_t width_in_sbs_minus_1[63]; + uint16_t height_in_sbs_minus_1[63]; + + /** \brief number of tiles minus 1 in large scale tile list + * Same as AV1 semantic element. + * Valid only when large_scale_tiles == 1. + */ + uint16_t tile_count_minus_1; + + /* specify the tile index for context updating */ + uint16_t context_update_tile_id; + + union { + struct { + /** \brief flags for current picture + * same syntax and semantic as those in AV1 code + */ + + /** \brief Frame Type + * 0: KEY_FRAME; + * 1: INTER_FRAME; + * 2: INTRA_ONLY_FRAME; + * 3: SWITCH_FRAME + * For SWITCH_FRAME, application shall set error_resilient_mode = 1, + * refresh_frame_flags, etc. appropriately. And driver will convert it + * to INTER_FRAME. + */ + uint32_t frame_type : 2; + uint32_t show_frame : 1; + uint32_t showable_frame : 1; + uint32_t error_resilient_mode : 1; + uint32_t disable_cdf_update : 1; + uint32_t allow_screen_content_tools : 1; + uint32_t force_integer_mv : 1; + uint32_t allow_intrabc : 1; + uint32_t use_superres : 1; + uint32_t allow_high_precision_mv : 1; + uint32_t is_motion_mode_switchable : 1; + uint32_t use_ref_frame_mvs : 1; + /* disable_frame_end_update_cdf is coded as refresh_frame_context. */ + uint32_t disable_frame_end_update_cdf : 1; + uint32_t uniform_tile_spacing_flag : 1; + uint32_t allow_warped_motion : 1; + /** \brief indicate if current frame in large scale tile mode */ + uint32_t large_scale_tile : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 15; + } bits; + uint32_t value; + } pic_info_fields; + + /** \brief Supper resolution scale denominator. + * When use_superres=1, superres_scale_denominator must be in the range [9..16]. + * When use_superres=0, superres_scale_denominator must be 8. + */ + uint8_t superres_scale_denominator; + + /** \brief Interpolation filter. + * value range [0..4] + */ + uint8_t interp_filter; + + /** \brief luma loop filter levels. + * value range [0..63]. + */ + uint8_t filter_level[2]; + + /** \brief chroma loop filter levels. + * value range [0..63]. + */ + uint8_t filter_level_u; + uint8_t filter_level_v; + + union { + struct { + /** \brief flags for reference pictures + * same syntax and semantic as those in AV1 code + */ + uint8_t sharpness_level : 3; + uint8_t mode_ref_delta_enabled : 1; + uint8_t mode_ref_delta_update : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint8_t reserved : 3; + } bits; + uint8_t value; + } loop_filter_info_fields; + + /** \brief The adjustment needed for the filter level based on + * the chosen reference frame. + * value range [-64..63]. + */ + int8_t ref_deltas[8]; + + /** \brief The adjustment needed for the filter level based on + * the chosen mode. + * value range [-64..63]. + */ + int8_t mode_deltas[2]; + + /** \brief quantization + */ + /** \brief Y AC index + * value range [0..255] + */ + uint8_t base_qindex; + /** \brief Y DC delta from Y AC + * value range [-64..63] + */ + int8_t y_dc_delta_q; + /** \brief U DC delta from Y AC + * value range [-64..63] + */ + int8_t u_dc_delta_q; + /** \brief U AC delta from Y AC + * value range [-64..63] + */ + int8_t u_ac_delta_q; + /** \brief V DC delta from Y AC + * value range [-64..63] + */ + int8_t v_dc_delta_q; + /** \brief V AC delta from Y AC + * value range [-64..63] + */ + int8_t v_ac_delta_q; + + /** \brief quantization_matrix + */ + union { + struct { + uint16_t using_qmatrix : 1; + /** \brief qm level + * value range [0..15] + * Invalid if using_qmatrix equals 0. + */ + uint16_t qm_y : 4; + uint16_t qm_u : 4; + uint16_t qm_v : 4; + + /** \brief Reserved bytes for future use, must be zero */ + uint16_t reserved : 3; + } bits; + uint16_t value; + } qmatrix_fields; + + union { + struct { + /** \brief delta_q parameters + */ + uint32_t delta_q_present_flag : 1; + uint32_t log2_delta_q_res : 2; + + /** \brief delta_lf parameters + */ + uint32_t delta_lf_present_flag : 1; + uint32_t log2_delta_lf_res : 2; + + /** \brief CONFIG_LOOPFILTER_LEVEL + */ + uint32_t delta_lf_multi : 1; + + /** \brief read_tx_mode + * value range [0..2] + */ + uint32_t tx_mode : 2; + + /* AV1 frame reference mode semantic */ + uint32_t reference_select : 1; + + uint32_t reduced_tx_set_used : 1; + + uint32_t skip_mode_present : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 20; + } bits; + uint32_t value; + } mode_control_fields; + + /** \brief CDEF parameters + */ + /* value range [0..3] */ + uint8_t cdef_damping_minus_3; + /* value range [0..3] */ + uint8_t cdef_bits; + + /** Encode cdef strength: + * + * The cdef_y_strengths[] and cdef_uv_strengths[] are expected to be packed + * with both primary and secondary strength. The secondary strength is + * given in the lower two bits and the primary strength is given in the next + * four bits. + * + * cdef_y_strengths[] & cdef_uv_strengths[] should be derived as: + * (cdef_y_strengths[]) = (cdef_y_pri_strength[] << 2) | (cdef_y_sec_strength[] & 0x03) + * (cdef_uv_strengths[]) = (cdef_uv_pri_strength[] << 2) | (cdef_uv_sec_strength[] & 0x03) + * In which, cdef_y_pri_strength[]/cdef_y_sec_strength[]/cdef_uv_pri_strength[]/cdef_uv_sec_strength[] + * are variables defined in AV1 Spec 5.9.19. The cdef_y_strengths[] & cdef_uv_strengths[] + * are corresponding to LIBAOM variables cm->cdef_strengths[] & cm->cdef_uv_strengths[] respectively. + */ + /* value range [0..63] */ + uint8_t cdef_y_strengths[8]; + /* value range [0..63] */ + uint8_t cdef_uv_strengths[8]; + + /** \brief loop restoration parameters + */ + union { + struct { + uint16_t yframe_restoration_type : 2; + uint16_t cbframe_restoration_type : 2; + uint16_t crframe_restoration_type : 2; + uint16_t lr_unit_shift : 2; + uint16_t lr_uv_shift : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint16_t reserved : 7; + } bits; + uint16_t value; + } loop_restoration_fields; + + /** \brief global motion + */ + VAWarpedMotionParamsAV1 wm[7]; + + /**@}*/ + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VADecPictureParameterBufferAV1; + + +/** + * \brief AV1 Slice Parameter Buffer Structure + * + * This structure conveys parameters related to bit stream data and should be + * sent once per tile. + * + * It uses the name VASliceParameterBufferAV1 to be consistent with other codec, + * but actually means VATileParameterBufferAV1. + * + * Slice data buffer of VASliceDataBufferType is used + * to send the bitstream. + * + * Please note that host decoder is responsible to parse out the + * per tile information. And the bit stream in sent to driver in per + * tile granularity. + */ +typedef struct _VASliceParameterBufferAV1 { + /**@{*/ + /** \brief The byte count of current tile in the bitstream buffer, + * starting from first byte of the buffer. + * It uses the name slice_data_size to be consistent with other codec, + * but actually means tile_data_size. + */ + uint32_t slice_data_size; + /** + * offset to the first byte of the data buffer. + */ + uint32_t slice_data_offset; + /** + * see VA_SLICE_DATA_FLAG_XXX definitions + */ + uint32_t slice_data_flag; + + uint16_t tile_row; + uint16_t tile_column; + + va_deprecated uint16_t tg_start; + va_deprecated uint16_t tg_end; + /** \brief anchor frame index for large scale tile. + * index into an array AnchorFrames of the frames that the tile uses + * for prediction. + * valid only when large_scale_tile equals 1. + */ + uint8_t anchor_frame_idx; + + /** \brief tile index in the tile list. + * Valid only when large_scale_tile is enabled. + * Driver uses this field to decide the tile output location. + */ + uint16_t tile_idx_in_tile_list; + + /**@}*/ + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferAV1; + + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DEC_AV1_H */ diff --git a/rs/moq-vaapi/libva/va/va_dec_hevc.h b/rs/moq-vaapi/libva/va/va_dec_hevc.h new file mode 100644 index 00000000000..eef053078df --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_dec_hevc.h @@ -0,0 +1,616 @@ +/* + * Copyright (c) 2014 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_dec_hevc.h + * \brief The HEVC decoding API + * + * This file contains the \ref api_dec_hevc "HEVC decoding API". + */ + +#ifndef VA_DEC_HEVC_H +#define VA_DEC_HEVC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_dec_hevc HEVC decoding API + * + * This HEVC decoding API supports Main and Main Still Picture profiles. + * And it supports both short slice format and long slice format. + * + * @{ + */ + +/** + * \brief HEVC Decoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters and should be sent once + * per frame. + * + */ +typedef struct _VAPictureParameterBufferHEVC { + /** \brief buffer description of decoded current picture + * only VA_PICTURE_HEVC_FIELD_PIC and VA_PICTURE_HEVC_BOTTOM_FIELD + * of "flags" fields are meaningful. + */ + VAPictureHEVC CurrPic; + /** \brief buffer description of reference frames in DPB */ + VAPictureHEVC ReferenceFrames[15]; + /** \brief picture width, shall be integer multiple of minimum CB size. */ + uint16_t pic_width_in_luma_samples; + /** \brief picture height, shall be integer multiple of minimum CB size. */ + uint16_t pic_height_in_luma_samples; + + + union { + struct { + /** following flags have same syntax and semantic as those in HEVC spec */ + uint32_t chroma_format_idc : 2; + uint32_t separate_colour_plane_flag : 1; + uint32_t pcm_enabled_flag : 1; + uint32_t scaling_list_enabled_flag : 1; + uint32_t transform_skip_enabled_flag : 1; + uint32_t amp_enabled_flag : 1; + uint32_t strong_intra_smoothing_enabled_flag : 1; + uint32_t sign_data_hiding_enabled_flag : 1; + uint32_t constrained_intra_pred_flag : 1; + uint32_t cu_qp_delta_enabled_flag : 1; + uint32_t weighted_pred_flag : 1; + uint32_t weighted_bipred_flag : 1; + uint32_t transquant_bypass_enabled_flag : 1; + uint32_t tiles_enabled_flag : 1; + uint32_t entropy_coding_sync_enabled_flag : 1; + uint32_t pps_loop_filter_across_slices_enabled_flag : 1; + uint32_t loop_filter_across_tiles_enabled_flag : 1; + uint32_t pcm_loop_filter_disabled_flag : 1; + /** set based on sps_max_num_reorder_pics of current temporal layer. */ + uint32_t NoPicReorderingFlag : 1; + /** picture has no B slices */ + uint32_t NoBiPredFlag : 1; + + uint32_t ReservedBits : 11; + } bits; + uint32_t value; + } pic_fields; + + /** following parameters have same syntax with those in HEVC spec */ + /** \brief DPB size for current temporal layer */ + uint8_t sps_max_dec_pic_buffering_minus1; + uint8_t bit_depth_luma_minus8; + uint8_t bit_depth_chroma_minus8; + uint8_t pcm_sample_bit_depth_luma_minus1; + uint8_t pcm_sample_bit_depth_chroma_minus1; + uint8_t log2_min_luma_coding_block_size_minus3; + uint8_t log2_diff_max_min_luma_coding_block_size; + uint8_t log2_min_transform_block_size_minus2; + uint8_t log2_diff_max_min_transform_block_size; + uint8_t log2_min_pcm_luma_coding_block_size_minus3; + uint8_t log2_diff_max_min_pcm_luma_coding_block_size; + uint8_t max_transform_hierarchy_depth_intra; + uint8_t max_transform_hierarchy_depth_inter; + int8_t init_qp_minus26; + uint8_t diff_cu_qp_delta_depth; + int8_t pps_cb_qp_offset; + int8_t pps_cr_qp_offset; + uint8_t log2_parallel_merge_level_minus2; + uint8_t num_tile_columns_minus1; + uint8_t num_tile_rows_minus1; + /** + * when uniform_spacing_flag equals 1, application should populate + * column_width_minus[], and row_height_minus1[] with approperiate values. + */ + uint16_t column_width_minus1[19]; + uint16_t row_height_minus1[21]; + + /** + * The Following Parameters are needed for Short Slice Format Only. + * Only format decoding can ignore them. + */ + + /** + * \brief Parameters needed for parsing slice segment headers + */ + union { + struct { + /** following parameters have same syntax with those in HEVC spec */ + uint32_t lists_modification_present_flag : 1; + uint32_t long_term_ref_pics_present_flag : 1; + uint32_t sps_temporal_mvp_enabled_flag : 1; + uint32_t cabac_init_present_flag : 1; + uint32_t output_flag_present_flag : 1; + uint32_t dependent_slice_segments_enabled_flag : 1; + uint32_t pps_slice_chroma_qp_offsets_present_flag : 1; + uint32_t sample_adaptive_offset_enabled_flag : 1; + uint32_t deblocking_filter_override_enabled_flag : 1; + uint32_t pps_disable_deblocking_filter_flag : 1; + uint32_t slice_segment_header_extension_present_flag : 1; + + /** current picture with NUT between 16 and 21 inclusive */ + uint32_t RapPicFlag : 1; + /** current picture with NUT between 19 and 20 inclusive */ + uint32_t IdrPicFlag : 1; + /** current picture has only intra slices */ + uint32_t IntraPicFlag : 1; + + uint32_t ReservedBits : 18; + } bits; + uint32_t value; + } slice_parsing_fields; + + /** following parameters have same syntax with those in HEVC spec */ + uint8_t log2_max_pic_order_cnt_lsb_minus4; + uint8_t num_short_term_ref_pic_sets; + uint8_t num_long_term_ref_pic_sps; + uint8_t num_ref_idx_l0_default_active_minus1; + uint8_t num_ref_idx_l1_default_active_minus1; + int8_t pps_beta_offset_div2; + int8_t pps_tc_offset_div2; + uint8_t num_extra_slice_header_bits; + + /** + * \brief number of bits that structure + * short_term_ref_pic_set( num_short_term_ref_pic_sets ) takes in slice + * segment header when short_term_ref_pic_set_sps_flag equals 0. + * if short_term_ref_pic_set_sps_flag equals 1, the value should be 0. + * the bit count is calculated after emulation prevention bytes are removed + * from bit streams. + * This variable is used for accelorater to skip parsing the + * short_term_ref_pic_set( num_short_term_ref_pic_sets ) structure. + */ + uint32_t st_rps_bits; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAPictureParameterBufferHEVC; + +/** + * \brief HEVC Decoding Picture Parameter Buffer Structure for Range Extension + * + * This structure conveys picture level HEVC Range Extension parameters + * and should be sent once per frame. This data structure should be sent + * together with VAPictureParameterBufferHEVC in a single buffer of + * \ref VAPictureParameterBufferHEVCExtension since each frame + * of HEVC range extension contains both picture level parameters and picture + * level range extension parameters. They should be parsed together. The buffer + * type is same as \ref VAPictureParameterBufferHEVC. + * + */ +typedef struct _VAPictureParameterBufferHEVCRext { + union { + struct { + /** \brief HEVC range extension flags + * The following flags bears the same syntax and semantics as + * those defined in HEVC bit stream spec. + */ + uint32_t transform_skip_rotation_enabled_flag : 1; + uint32_t transform_skip_context_enabled_flag : 1; + uint32_t implicit_rdpcm_enabled_flag : 1; + uint32_t explicit_rdpcm_enabled_flag : 1; + uint32_t extended_precision_processing_flag : 1; + uint32_t intra_smoothing_disabled_flag : 1; + uint32_t high_precision_offsets_enabled_flag : 1; + uint32_t persistent_rice_adaptation_enabled_flag : 1; + uint32_t cabac_bypass_alignment_enabled_flag : 1; + uint32_t cross_component_prediction_enabled_flag : 1; + uint32_t chroma_qp_offset_list_enabled_flag : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 21; + } bits; + uint32_t value; + } range_extension_pic_fields; + + /** \brief HEVC range extension flags + * The following flags bears the same syntax and semantics as + * those defined in HEVC bit stream spec. + */ + uint8_t diff_cu_chroma_qp_offset_depth; + uint8_t chroma_qp_offset_list_len_minus1; + uint8_t log2_sao_offset_scale_luma; + uint8_t log2_sao_offset_scale_chroma; + uint8_t log2_max_transform_skip_block_size_minus2; + int8_t cb_qp_offset_list[6]; + int8_t cr_qp_offset_list[6]; +} VAPictureParameterBufferHEVCRext; + +/** + *\brief HEVC Decoding Picture Parameter Buffer Structure for + *Screen Content extension + * + *This structure conveys picture level HEVC Scc parameters + *and should be sent once per frame. This data structure should be sent + *together with VAPictureParameterBufferHEVC and VAPictureParameterBufferHEVCRext + *in a single buffer of \ref VAPictureParameterBufferHEVCExtension since each + *frame of HEVC SCC contains picture level parameters, picture level range + *extension parameters and picture level Scc parameters. They should be parsed + *together and the buffer type is same as \ref VAPictureParameterBufferHEVC. + * + */ +typedef struct _VAPictureParameterBufferHEVCScc { + union { + struct { + /** \brief HEVC Scc extension flags + * The following flags bears the same syntax and semantics as + * those defined in HEVC bit stream spec. + */ + /* indicates if intra block copy (IBC) is enabled or not. */ + uint32_t pps_curr_pic_ref_enabled_flag : 1; + /* indicates if Palette Mode is enabled or not. */ + uint32_t palette_mode_enabled_flag : 1; + /* controls the presence and inference of the use_integer_mv_flag syntax + * in slice segment header that specifies the resolution of motion + * vectors for inter prediction. + */ + uint32_t motion_vector_resolution_control_idc : 2; + /* specifies that the intra boundary filtering process is + * disabled or not for intra prediction. + */ + uint32_t intra_boundary_filtering_disabled_flag : 1; + /* specifies that an adaptive colour transform may be applied + * to the residual in the decoding process. + */ + uint32_t residual_adaptive_colour_transform_enabled_flag : 1; + + /* specifies that slice_act_y_qp_offset, slice_act_cb_qp_offset, + * slice_act_cr_qp_offset are present in the slice header + */ + uint32_t pps_slice_act_qp_offsets_present_flag : 1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 25; + } bits; + uint32_t value; + } screen_content_pic_fields; + + /* specifies the maximum allowed palette size. */ + uint8_t palette_max_size; + /* Correspond to HEVC syntax elements of the same names. + * It specifies the difference between the maximum allowed palette + * predictor size and the maximum allowed palette size. + * App needs to enforce that the variable PaletteMaxPredictorSize, + * which is derived as follows: + * PaletteMaxPredictorSize = palette_max_size + delta_palette_max_predictor_size + * should have a value range of [0..128]. + */ + uint8_t delta_palette_max_predictor_size; + /** \brief Size of initial palette predictor. + * It is derived from pps_num_palette_predictor_initializer or + * sps_num_palette_predictor_initializer_minus1. + * Details in HEVC SCC spec section 9.3.2.3. + */ + uint8_t predictor_palette_size; + /** \brief Palette predictor initializer. + * It is derived from pps_palette_predictor_initializers[][] + * or sps_palette_predictor_initializers[][]. + * Details in HEVC SCC spec section 9.3.2.3. + */ + uint16_t predictor_palette_entries[3][128]; + /* are used to determine the offsets that are applied to the + * quantization parameter values for the luma, Cb and Cr + * components, respectively. + */ + int8_t pps_act_y_qp_offset_plus5; + int8_t pps_act_cb_qp_offset_plus5; + int8_t pps_act_cr_qp_offset_plus3; +} VAPictureParameterBufferHEVCScc; + +/** + * \brief HEVC Decoding Picture Parameter Buffer Structure including Extensions + * + * This structure conveys picture level HEVC parameters including basic version 1 + * and range extension and screen content extension. + * The data buffer should be sent once per frame. + * + */ +typedef struct _VAPictureParameterBufferHEVCExtension { + /** \brief basic HEVC picture parameters data structure + */ + VAPictureParameterBufferHEVC base; + + /** \brief HEVC range extension picture parameters data structure + */ + VAPictureParameterBufferHEVCRext rext; + + /** \brief HEVC screen content picture parameters data structure + */ + VAPictureParameterBufferHEVCScc scc; +} VAPictureParameterBufferHEVCExtension; + +/** + * \brief HEVC Slice Parameter Buffer Structure For Long Format + * + * VASliceParameterBufferHEVC structure should be accompanied by a + * slice data buffer, which holds the whole raw slice NAL unit bit streams + * including start code prefix and emulation prevention bytes not removed. + * + * This structure conveys parameters related to slice segment header and should + * be sent once per slice. + * + * For short format, this data structure is not sent by application. + * + */ +typedef struct _VASliceParameterBufferHEVC { + /** @name Codec-independent Slice Parameter Buffer base. */ + + /**@{*/ + + /** \brief Number of bytes in the slice data buffer for this slice + * counting from and including NAL unit header. + */ + uint32_t slice_data_size; + /** \brief The offset to the NAL unit header for this slice */ + uint32_t slice_data_offset; + /** \brief Slice data buffer flags. See \c VA_SLICE_DATA_FLAG_XXX. */ + uint32_t slice_data_flag; + /** + * \brief Byte offset from NAL unit header to the begining of slice_data(). + * + * This byte offset is relative to and includes the NAL unit header + * and represents the number of bytes parsed in the slice_header() + * after the removal of any emulation prevention bytes in + * there. However, the slice data buffer passed to the hardware is + * the original bitstream, thus including any emulation prevention + * bytes. + */ + uint32_t slice_data_byte_offset; + /** HEVC syntax element. */ + uint32_t slice_segment_address; + /** \brief index into ReferenceFrames[] + * RefPicList[0][] corresponds to RefPicList0[] of HEVC variable. + * RefPicList[1][] corresponds to RefPicList1[] of HEVC variable. + * value range [0..14, 0xFF], where 0xFF indicates invalid entry. + */ + uint8_t RefPicList[2][15]; + union { + uint32_t value; + struct { + /** current slice is last slice of picture. */ + uint32_t LastSliceOfPic : 1; + /** HEVC syntax element. */ + uint32_t dependent_slice_segment_flag : 1; + /** HEVC syntax element. */ + uint32_t slice_type : 2; + /** HEVC syntax element. */ + uint32_t color_plane_id : 2; + /** HEVC syntax element. */ + uint32_t slice_sao_luma_flag : 1; + /** HEVC syntax element. */ + uint32_t slice_sao_chroma_flag : 1; + /** HEVC syntax element. */ + uint32_t mvd_l1_zero_flag : 1; + /** HEVC syntax element. */ + uint32_t cabac_init_flag : 1; + /** HEVC syntax element. */ + uint32_t slice_temporal_mvp_enabled_flag : 1; + /** HEVC syntax element. */ + uint32_t slice_deblocking_filter_disabled_flag : 1; + /** HEVC syntax element. */ + uint32_t collocated_from_l0_flag : 1; + /** HEVC syntax element. */ + uint32_t slice_loop_filter_across_slices_enabled_flag : 1; + uint32_t reserved : 18; + } fields; + } LongSliceFlags; + + /** HEVC syntax element. Collocated Reference Picture Index. + * index to RefPicList[0][] or RefPicList[1][]. + * when slice_temporal_mvp_enabled_flag equals 0, it should take value 0xFF. + * value range [0..14, 0xFF]. + */ + uint8_t collocated_ref_idx; + /** HEVC syntax element. + * if num_ref_idx_active_override_flag equals 0, host decoder should + * set its value to num_ref_idx_l0_default_active_minus1. + */ + uint8_t num_ref_idx_l0_active_minus1; + /** HEVC syntax element. + * if num_ref_idx_active_override_flag equals 0, host decoder should + * set its value to num_ref_idx_l1_default_active_minus1. + */ + uint8_t num_ref_idx_l1_active_minus1; + /** HEVC syntax element. */ + int8_t slice_qp_delta; + /** HEVC syntax element. */ + int8_t slice_cb_qp_offset; + /** HEVC syntax element. */ + int8_t slice_cr_qp_offset; + /** HEVC syntax element. */ + int8_t slice_beta_offset_div2; + /** HEVC syntax element. */ + int8_t slice_tc_offset_div2; + /** HEVC syntax element. */ + uint8_t luma_log2_weight_denom; + /** HEVC syntax element. */ + int8_t delta_chroma_log2_weight_denom; + /** HEVC syntax element. */ + int8_t delta_luma_weight_l0[15]; + /** HEVC syntax element. */ + int8_t luma_offset_l0[15]; + /** HEVC syntax element. */ + int8_t delta_chroma_weight_l0[15][2]; + /** corresponds to HEVC spec variable of the same name. */ + int8_t ChromaOffsetL0[15][2]; + /** HEVC syntax element. */ + int8_t delta_luma_weight_l1[15]; + /** HEVC syntax element. */ + int8_t luma_offset_l1[15]; + /** HEVC syntax element. */ + int8_t delta_chroma_weight_l1[15][2]; + /** corresponds to HEVC spec variable of the same name. */ + int8_t ChromaOffsetL1[15][2]; + /** HEVC syntax element. */ + uint8_t five_minus_max_num_merge_cand; + /** HEVC syntax element. */ + uint16_t num_entry_point_offsets; + /** HEVC syntax element. */ + uint16_t entry_offset_to_subset_array; + /** \brief Number of emulation prevention bytes in slice header. */ + uint16_t slice_data_num_emu_prevn_bytes; + /**@}*/ + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW - 2]; +} VASliceParameterBufferHEVC; + +/** + * \brief HEVC Extented Slice Parameter Buffer Structure For Long Format + * + * This data structure contains extension profiles (range extension and screen content). + * + * VASliceParameterBufferHEVCRext structure should be accompanied by a + * slice data buffer, which holds the whole raw slice NAL unit bit streams + * including start code prefix and emulation prevention bytes not removed. + * + * This structure conveys parameters related to slice segment header and should + * be sent once per slice with VASliceParameterBufferHEVC in a single buffer of + * \ref VASliceParameterBufferHEVCExtension and the buffer type is same as \ref + * VASliceParameterBufferHEVC. + * + * For short format, this data structure is not sent by application. + * + */ +typedef struct _VASliceParameterBufferHEVCRext { + /* below four parameters are used to replace data types of the + * corresponding parameters of those in \# VASliceParameterBufferHEVC. + */ + int16_t luma_offset_l0[15]; + int16_t ChromaOffsetL0[15][2]; + int16_t luma_offset_l1[15]; + int16_t ChromaOffsetL1[15][2]; + + union { + struct { + uint32_t cu_chroma_qp_offset_enabled_flag : 1; + uint32_t use_integer_mv_flag : 1; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved : 30; + } bits; + uint32_t value; + } slice_ext_flags; + + /** \brief Screen Content Extension parameters. + * data range [-12..12] + */ + int8_t slice_act_y_qp_offset; + int8_t slice_act_cb_qp_offset; + int8_t slice_act_cr_qp_offset; +} VASliceParameterBufferHEVCRext; + +/** + * \brief HEVC Decoding Slice Parameter Buffer Structure For Long Format including Extensions + * + * This data structure contains both baseline HEVC profiles (main, main10) + * and extension profiles (range extension and screen content). + * + * VASliceParameterBufferHEVCExtension structure should be accompanied by a + * slice data buffer, which holds the whole raw slice NAL unit bit streams + * including start code prefix and emulation prevention bytes not removed. + * + * This structure conveys parameters related to slice segment header and should + * be sent once per slice. For HEVC range extension and HEVC Scc decoding, + * application should parse both basic slice parameters and extented slice + * parameters into this buffer structure and sent it. + * + * For short format, this data structure is not sent by application. + * + */ +typedef struct _VASliceParameterBufferHEVCExtension { + /** \brief baseline HEVC slice parameters data structure */ + VASliceParameterBufferHEVC base; + + /** \brief extented HEVC slice parameters data structure */ + VASliceParameterBufferHEVCRext rext; +} VASliceParameterBufferHEVCExtension; + +/** + * \brief HEVC Inverse Quantization Matrix Buffer Structure + * + * This structure is sent once per frame, + * and only when scaling_list_enabled_flag = 1. + * When sps_scaling_list_data_present_flag = 0, app still + * needs to send in this structure with default matrix values. + * + * Matrix entries are in raster scan order which follows HEVC spec. + */ +typedef struct _VAIQMatrixBufferHEVC { + /** + * \brief scaling lists, + * corresponds to same HEVC spec syntax element + * ScalingList[ i ][ MatrixID ][ j ]. + * + * \brief 4x4 scaling, + * correspongs i = 0, MatrixID is in the range of 0 to 5, + * inclusive. And j is in the range of 0 to 15, inclusive. + */ + uint8_t ScalingList4x4[6][16]; + /** + * \brief 8x8 scaling, + * correspongs i = 1, MatrixID is in the range of 0 to 5, + * inclusive. And j is in the range of 0 to 63, inclusive. + */ + uint8_t ScalingList8x8[6][64]; + /** + * \brief 16x16 scaling, + * correspongs i = 2, MatrixID is in the range of 0 to 5, + * inclusive. And j is in the range of 0 to 63, inclusive. + */ + uint8_t ScalingList16x16[6][64]; + /** + * \brief 32x32 scaling, + * correspongs i = 3, MatrixID is in the range of 0 to 1, + * inclusive. And j is in the range of 0 to 63, inclusive. + */ + uint8_t ScalingList32x32[2][64]; + /** + * \brief DC values of the 16x16 scaling lists, + * corresponds to HEVC spec syntax + * scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8 + * with sizeID = 2 and matrixID in the range of 0 to 5, inclusive. + */ + uint8_t ScalingListDC16x16[6]; + /** + * \brief DC values of the 32x32 scaling lists, + * corresponds to HEVC spec syntax + * scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8 + * with sizeID = 3 and matrixID in the range of 0 to 1, inclusive. + */ + uint8_t ScalingListDC32x32[2]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAIQMatrixBufferHEVC; + + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DEC_HEVC_H */ diff --git a/rs/moq-vaapi/libva/va/va_dec_jpeg.h b/rs/moq-vaapi/libva/va/va_dec_jpeg.h new file mode 100644 index 00000000000..2cd6b42c419 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_dec_jpeg.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2007-2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_dec_jpeg.h + * \brief The JPEG decoding API + * + * This file contains the \ref api_dec_jpeg "JPEG decoding API". + */ + +#ifndef VA_DEC_JPEG_H +#define VA_DEC_JPEG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * \defgroup api_dec_jpeg JPEG decoding API + * + * This JPEG decoding API supports Baseline profile only. + * + * @{ + */ + +/** + * \brief Picture parameter for JPEG decoding. + * + * This structure holds information from the frame header, along with + * definitions from additional segments. + */ +typedef struct _VAPictureParameterBufferJPEGBaseline { + /** \brief Picture width in pixels. */ + uint16_t picture_width; + /** \brief Picture height in pixels. */ + uint16_t picture_height; + + struct { + /** \brief Component identifier (Ci). */ + uint8_t component_id; + /** \brief Horizontal sampling factor (Hi). */ + uint8_t h_sampling_factor; + /** \brief Vertical sampling factor (Vi). */ + uint8_t v_sampling_factor; + /* \brief Quantization table selector (Tqi). */ + uint8_t quantiser_table_selector; + } components[255]; + /** \brief Number of components in frame (Nf). */ + uint8_t num_components; + + /** \brief Input color space 0: YUV, 1: RGB, 2: BGR, others: reserved */ + uint8_t color_space; + /** \brief Set to VA_ROTATION_* for a single rotation angle reported by VAConfigAttribDecJPEG. */ + uint32_t rotation; + /** \brief crop rectangle boundary in pixels */ + VARectangle crop_rectangle; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM - 3]; +} VAPictureParameterBufferJPEGBaseline; + +/** + * \brief Quantization table for JPEG decoding. + * + * This structure holds the complete quantization tables. This is an + * aggregation of all quantization table (DQT) segments maintained by + * the application. i.e. up to 4 quantization tables are stored in + * there for baseline profile. + * + * The #load_quantization_table array can be used as a hint to notify + * the VA driver implementation about which table(s) actually changed + * since the last submission of this buffer. + * + * The #quantiser_table values are specified in zig-zag scan order. + */ +typedef struct _VAIQMatrixBufferJPEGBaseline { + /** \brief Specifies which #quantiser_table is valid. */ + uint8_t load_quantiser_table[4]; + /** \brief Quanziation tables indexed by table identifier (Tqi). */ + uint8_t quantiser_table[4][64]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAIQMatrixBufferJPEGBaseline; + +/** + * \brief Slice parameter for JPEG decoding. + * + * This structure holds information from the scan header, along with + * definitions from additional segments. The associated slice data + * buffer holds all entropy coded segments (ECS) in the scan. + */ +typedef struct _VASliceParameterBufferJPEGBaseline { + /** @name Codec-independent Slice Parameter Buffer base. */ + /**@{*/ + /** \brief Number of bytes in the slice data buffer for this slice. */ + uint32_t slice_data_size; + /** \brief The offset to the first byte of the first MCU. */ + uint32_t slice_data_offset; + /** \brief Slice data buffer flags. See \c VA_SLICE_DATA_FLAG_xxx. */ + uint32_t slice_data_flag; + /**@}*/ + + /** \brief Scan horizontal position. */ + uint32_t slice_horizontal_position; + /** \brief Scan vertical position. */ + uint32_t slice_vertical_position; + + struct { + /** \brief Scan component selector (Csj). */ + uint8_t component_selector; + /** \brief DC entropy coding table selector (Tdj). */ + uint8_t dc_table_selector; + /** \brief AC entropy coding table selector (Taj). */ + uint8_t ac_table_selector; + } components[4]; + /** \brief Number of components in scan (Ns). */ + uint8_t num_components; + + /** \brief Restart interval definition (Ri). */ + uint16_t restart_interval; + /** \brief Number of MCUs in a scan. */ + uint32_t num_mcus; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceParameterBufferJPEGBaseline; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DEC_JPEG_H */ diff --git a/rs/moq-vaapi/libva/va/va_dec_vp8.h b/rs/moq-vaapi/libva/va/va_dec_vp8.h new file mode 100644 index 00000000000..750e8afe203 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_dec_vp8.h @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2007-2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_dec_vp8.h + * \brief VP8 decoding API + * + * This file contains the \ref api_dec_vp8 "VP8 decoding API". + */ + +#ifndef VA_DEC_VP8_H +#define VA_DEC_VP8_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_dec_vp8 VP8 decoding API + * + * @{ + */ + +/** + * \brief VPX Bool Coder Context structure + * + * This common structure is defined for potential sharing by other VP formats + * + */ +typedef struct _VABoolCoderContextVPX { + /* partition 0 "range" */ + uint8_t range; + /* partition 0 "value" */ + uint8_t value; + /* + * 'partition 0 number of shifts before an output byte is available' + * it is the number of remaining bits in 'value' for decoding, range [0, 7]. + */ + + uint8_t count; +} VABoolCoderContextVPX; + +/** + * \brief VP8 Decoding Picture Parameter Buffer Structure + * + * This structure conveys frame level parameters and should be sent once + * per frame. + * + */ +typedef struct _VAPictureParameterBufferVP8 { + /* frame width in pixels */ + uint32_t frame_width; + /* frame height in pixels */ + uint32_t frame_height; + + /* specifies the "last" reference frame */ + VASurfaceID last_ref_frame; + /* specifies the "golden" reference frame */ + VASurfaceID golden_ref_frame; + /* specifies the "alternate" referrence frame */ + VASurfaceID alt_ref_frame; + /* specifies the out-of-loop deblocked frame, not used currently */ + VASurfaceID out_of_loop_frame; + + union { + struct { + /* same as key_frame in bitstream syntax, 0 means a key frame */ + uint32_t key_frame : 1; + /* same as version in bitstream syntax */ + uint32_t version : 3; + /* same as segmentation_enabled in bitstream syntax */ + uint32_t segmentation_enabled : 1; + /* same as update_mb_segmentation_map in bitstream syntax */ + uint32_t update_mb_segmentation_map : 1; + /* same as update_segment_feature_data in bitstream syntax */ + uint32_t update_segment_feature_data : 1; + /* same as filter_type in bitstream syntax */ + uint32_t filter_type : 1; + /* same as sharpness_level in bitstream syntax */ + uint32_t sharpness_level : 3; + /* same as loop_filter_adj_enable in bitstream syntax */ + uint32_t loop_filter_adj_enable : 1; + /* same as mode_ref_lf_delta_update in bitstream syntax */ + uint32_t mode_ref_lf_delta_update : 1; + /* same as sign_bias_golden in bitstream syntax */ + uint32_t sign_bias_golden : 1; + /* same as sign_bias_alternate in bitstream syntax */ + uint32_t sign_bias_alternate : 1; + /* same as mb_no_coeff_skip in bitstream syntax */ + uint32_t mb_no_coeff_skip : 1; + /* flag to indicate that loop filter should be disabled */ + uint32_t loop_filter_disable : 1; + } bits; + uint32_t value; + } pic_fields; + + /* + * probabilities of the segment_id decoding tree and same as + * mb_segment_tree_probs in the spec. + */ + uint8_t mb_segment_tree_probs[3]; + + /* Post-adjustment loop filter levels for the 4 segments */ + uint8_t loop_filter_level[4]; + /* loop filter deltas for reference frame based MB level adjustment */ + int8_t loop_filter_deltas_ref_frame[4]; + /* loop filter deltas for coding mode based MB level adjustment */ + int8_t loop_filter_deltas_mode[4]; + + /* same as prob_skip_false in bitstream syntax */ + uint8_t prob_skip_false; + /* same as prob_intra in bitstream syntax */ + uint8_t prob_intra; + /* same as prob_last in bitstream syntax */ + uint8_t prob_last; + /* same as prob_gf in bitstream syntax */ + uint8_t prob_gf; + + /* + * list of 4 probabilities of the luma intra prediction mode decoding + * tree and same as y_mode_probs in frame header + */ + uint8_t y_mode_probs[4]; + /* + * list of 3 probabilities of the chroma intra prediction mode decoding + * tree and same as uv_mode_probs in frame header + */ + uint8_t uv_mode_probs[3]; + /* + * updated mv decoding probabilities and same as mv_probs in + * frame header + */ + uint8_t mv_probs[2][19]; + + VABoolCoderContextVPX bool_coder_ctx; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAPictureParameterBufferVP8; + +/** + * \brief VP8 Slice Parameter Buffer Structure + * + * This structure conveys parameters related to data partitions and should be + * sent once per frame. Slice data buffer of VASliceDataBufferType is used + * to send the partition data. + * + */ +typedef struct _VASliceParameterBufferVP8 { + /* + * number of bytes in the slice data buffer for the partitions + */ + uint32_t slice_data_size; + /* + * offset to the first byte of partition data (control partition) + */ + uint32_t slice_data_offset; + /* + * see VA_SLICE_DATA_FLAG_XXX definitions + */ + uint32_t slice_data_flag; + /* + * offset to the first bit of MB from the first byte of partition data(slice_data_offset) + */ + uint32_t macroblock_offset; + + /* + * Partitions + * (1<lvl[seg][ref][mode] in VP9 code, + * where m is [ref], and n is [mode] in FilterLevel[m][n]. + */ + uint8_t filter_level[4][2]; + /** \brief Specifies per segment Luma AC quantization scale. + * Corresponding to y_dequant[qindex][1] in vp9_mb_init_quantizer() + * function of VP9 code. + */ + int16_t luma_ac_quant_scale; + /** \brief Specifies per segment Luma DC quantization scale. + * Corresponding to y_dequant[qindex][0] in vp9_mb_init_quantizer() + * function of VP9 code. + */ + int16_t luma_dc_quant_scale; + /** \brief Specifies per segment Chroma AC quantization scale. + * Corresponding to uv_dequant[qindex][1] in vp9_mb_init_quantizer() + * function of VP9 code. + */ + int16_t chroma_ac_quant_scale; + /** \brief Specifies per segment Chroma DC quantization scale. + * Corresponding to uv_dequant[qindex][0] in vp9_mb_init_quantizer() + * function of VP9 code. + */ + int16_t chroma_dc_quant_scale; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VASegmentParameterVP9; + + + +/** + * \brief VP9 Slice Parameter Buffer Structure + * + * This structure conveys parameters related to segmentation data and should be + * sent once per frame. + * + * When segmentation is disabled, only SegParam[0] has valid values, + * all other entries should be populated with 0. + * Otherwise, all eight entries should be valid. + * + * Slice data buffer of VASliceDataBufferType is used + * to send the bitstream which should include whole or part of partition 0 + * (at least compressed header) to the end of frame. + * + */ +typedef struct _VASliceParameterBufferVP9 { + /** \brief The byte count of current frame in the bitstream buffer, + * starting from first byte of the buffer. + * It uses the name slice_data_size to be consitent with other codec, + * but actually means frame_data_size. + */ + uint32_t slice_data_size; + /** + * offset to the first byte of partition data (control partition) + */ + uint32_t slice_data_offset; + /** + * see VA_SLICE_DATA_FLAG_XXX definitions + */ + uint32_t slice_data_flag; + + /** + * \brief per segment information + */ + VASegmentParameterVP9 seg_param[8]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VASliceParameterBufferVP9; + + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DEC_VP9_H */ diff --git a/rs/moq-vaapi/libva/va/va_dec_vvc.h b/rs/moq-vaapi/libva/va/va_dec_vvc.h new file mode 100644 index 00000000000..bbd40399481 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_dec_vvc.h @@ -0,0 +1,688 @@ +/* + * Copyright (c) 2024 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_dec_vvc.h + * \brief The VVC decoding API + * + * This file contains the \ref api_dec_vvc "VVC decoding API". + */ + +#ifndef VA_DEC_VVC_H +#define VA_DEC_VVC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_dec_vvc VVC decoding API + * + * This VVC decoding API supports Main 10 profile and Multilayer Main 10 profile. + * And it supports only long slice format. + * + * @{ + */ + +/** + * \brief Weighted Prediction Parameters. + */ +typedef struct _VAWeightedPredInfo { + /** \brief Weighted Prediction parameters. + * All the parameters except reserved bytes are VVC syntax. + */ + uint8_t luma_log2_weight_denom; + int8_t delta_chroma_log2_weight_denom; + uint8_t num_l0_weights; + uint8_t luma_weight_l0_flag[15]; + uint8_t chroma_weight_l0_flag[15]; + int8_t delta_luma_weight_l0[15]; + int8_t luma_offset_l0[15]; + int8_t delta_chroma_weight_l0[15][2]; + int16_t delta_chroma_offset_l0[15][2]; + uint8_t num_l1_weights; + uint8_t luma_weight_l1_flag[15]; + uint8_t chroma_weight_l1_flag[15]; + int8_t delta_luma_weight_l1[15]; + int8_t luma_offset_l1[15]; + int8_t delta_chroma_weight_l1[15][2]; + int16_t delta_chroma_offset_l1[15][2]; + /** \brief Reserved for future use, must be zero */ + uint16_t reserved16b; + uint32_t reserved32b; +} VAWeightedPredInfo; + +/** + * \brief VVC Decoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters and should be sent once + * per frame. + * + * Host decoder is required to send in a buffer of VAPictureParameterBufferVVC + * as the first va buffer for each frame. + * + */ +typedef struct _VAPictureParameterBufferVVC { + /** \brief buffer description of decoded current picture + */ + VAPictureVVC CurrPic; + /** \brief buffer description of reference frames in DPB */ + VAPictureVVC ReferenceFrames[15]; + /** \brief picture width, shall be integer multiple of Max(8, MinCbSizeY). */ + uint16_t pps_pic_width_in_luma_samples; + /** \brief picture height, shall be integer multiple of Max(8, MinCbSizeY). */ + uint16_t pps_pic_height_in_luma_samples; + + /** \brief sequence level parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + uint16_t sps_num_subpics_minus1; + uint8_t sps_chroma_format_idc; + uint8_t sps_bitdepth_minus8; + uint8_t sps_log2_ctu_size_minus5; + uint8_t sps_log2_min_luma_coding_block_size_minus2; + uint8_t sps_log2_transform_skip_max_size_minus2; + /** \brief chroma QP mapping table. + * ChromaQpTable[][] corresponds to VVC spec variable with the same name. + * It is derived according to formula (57) in VVC spec section 7.4.3.4. + */ + int8_t ChromaQpTable[3][111]; + uint8_t sps_six_minus_max_num_merge_cand; + uint8_t sps_five_minus_max_num_subblock_merge_cand; + uint8_t sps_max_num_merge_cand_minus_max_num_gpm_cand; + uint8_t sps_log2_parallel_merge_level_minus2; + uint8_t sps_min_qp_prime_ts; + uint8_t sps_six_minus_max_num_ibc_merge_cand; + uint8_t sps_num_ladf_intervals_minus2; + int8_t sps_ladf_lowest_interval_qp_offset; + int8_t sps_ladf_qp_offset[4]; + uint16_t sps_ladf_delta_threshold_minus1[4]; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved32b01[VA_PADDING_LOW - 2]; + + union { + struct { + uint64_t sps_subpic_info_present_flag : 1; + uint64_t sps_independent_subpics_flag : 1; + uint64_t sps_subpic_same_size_flag : 1; + uint64_t sps_entropy_coding_sync_enabled_flag : 1; + uint64_t sps_qtbtt_dual_tree_intra_flag : 1; + uint64_t sps_max_luma_transform_size_64_flag : 1; + uint64_t sps_transform_skip_enabled_flag : 1; + uint64_t sps_bdpcm_enabled_flag : 1; + uint64_t sps_mts_enabled_flag : 1; + uint64_t sps_explicit_mts_intra_enabled_flag : 1; + uint64_t sps_explicit_mts_inter_enabled_flag : 1; + uint64_t sps_lfnst_enabled_flag : 1; + uint64_t sps_joint_cbcr_enabled_flag : 1; + uint64_t sps_same_qp_table_for_chroma_flag : 1; + uint64_t sps_sao_enabled_flag : 1; + uint64_t sps_alf_enabled_flag : 1; + uint64_t sps_ccalf_enabled_flag : 1; + uint64_t sps_lmcs_enabled_flag : 1; + uint64_t sps_sbtmvp_enabled_flag : 1; + uint64_t sps_amvr_enabled_flag : 1; + uint64_t sps_smvd_enabled_flag : 1; + uint64_t sps_mmvd_enabled_flag : 1; + uint64_t sps_sbt_enabled_flag : 1; + uint64_t sps_affine_enabled_flag : 1; + uint64_t sps_6param_affine_enabled_flag : 1; + uint64_t sps_affine_amvr_enabled_flag : 1; + uint64_t sps_affine_prof_enabled_flag : 1; + uint64_t sps_bcw_enabled_flag : 1; + uint64_t sps_ciip_enabled_flag : 1; + uint64_t sps_gpm_enabled_flag : 1; + uint64_t sps_isp_enabled_flag : 1; + uint64_t sps_mrl_enabled_flag : 1; + uint64_t sps_mip_enabled_flag : 1; + uint64_t sps_cclm_enabled_flag : 1; + uint64_t sps_chroma_horizontal_collocated_flag : 1; + uint64_t sps_chroma_vertical_collocated_flag : 1; + uint64_t sps_palette_enabled_flag : 1; + uint64_t sps_act_enabled_flag : 1; + uint64_t sps_ibc_enabled_flag : 1; + uint64_t sps_ladf_enabled_flag : 1; + uint64_t sps_explicit_scaling_list_enabled_flag : 1; + uint64_t sps_scaling_matrix_for_lfnst_disabled_flag : 1; + uint64_t sps_scaling_matrix_for_alternative_colour_space_disabled_flag : 1; + uint64_t sps_scaling_matrix_designated_colour_space_flag : 1; + uint64_t sps_virtual_boundaries_enabled_flag : 1; + uint64_t sps_virtual_boundaries_present_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint64_t reserved : 18; + } bits; + uint64_t value; + } sps_flags; + + /** \brief picture level parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + /** \brief number of vertical virtual boundaries on the picture. + * NumVerVirtualBoundaries corresponds to VVC spec variable with the same name. + * It is derived according to formula (78) in VVC spec section 7.4.3.8. + */ + uint8_t NumVerVirtualBoundaries; + /** \brief number of horizontal virtual boundaries on the picture. + * NumHorVirtualBoundaries corresponds to VVC spec variable with the same name. + * It is derived according to formula (80) in VVC spec section 7.4.3.8. + */ + uint8_t NumHorVirtualBoundaries; + /** \brief location of the vertical virtual boundary in units of luma samples. + * VirtualBoundaryPosX[] corresponds to VVC spec variable with the same name. + * It is derived according to formula (79) in VVC spec section 7.4.3.8. + */ + uint16_t VirtualBoundaryPosX[3]; + /** \brief location of the horizontal virtual boundary in units of luma samples. + * VirtualBoundaryPosY[] corresponds to VVC spec variable with the same name. + * It is derived according to formula (81) in VVC spec section 7.4.3.8. + */ + uint16_t VirtualBoundaryPosY[3]; + + int32_t pps_scaling_win_left_offset; + int32_t pps_scaling_win_right_offset; + int32_t pps_scaling_win_top_offset; + int32_t pps_scaling_win_bottom_offset; + + int8_t pps_num_exp_tile_columns_minus1; + uint16_t pps_num_exp_tile_rows_minus1; + uint16_t pps_num_slices_in_pic_minus1; + uint16_t pps_pic_width_minus_wraparound_offset; + int8_t pps_cb_qp_offset; + int8_t pps_cr_qp_offset; + int8_t pps_joint_cbcr_qp_offset_value; + uint8_t pps_chroma_qp_offset_list_len_minus1; + int8_t pps_cb_qp_offset_list[6]; + int8_t pps_cr_qp_offset_list[6]; + int8_t pps_joint_cbcr_qp_offset_list[6]; + /** \brief Reserved for future use, must be zero */ + uint16_t reserved16b01; + uint32_t reserved32b02[VA_PADDING_LOW - 2]; + + union { + struct { + uint32_t pps_loop_filter_across_tiles_enabled_flag : 1; + uint32_t pps_rect_slice_flag : 1; + uint32_t pps_single_slice_per_subpic_flag : 1; + uint32_t pps_loop_filter_across_slices_enabled_flag : 1; + uint32_t pps_weighted_pred_flag : 1; + uint32_t pps_weighted_bipred_flag : 1; + uint32_t pps_ref_wraparound_enabled_flag : 1; + uint32_t pps_cu_qp_delta_enabled_flag : 1; + uint32_t pps_cu_chroma_qp_offset_list_enabled_flag : 1; + uint32_t pps_deblocking_filter_override_enabled_flag : 1; + uint32_t pps_deblocking_filter_disabled_flag : 1; + uint32_t pps_dbf_info_in_ph_flag : 1; + uint32_t pps_sao_info_in_ph_flag : 1; + uint32_t pps_alf_info_in_ph_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 18; + } bits; + uint32_t value; + } pps_flags; + + /** \brief picture header parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + uint8_t ph_lmcs_aps_id; + uint8_t ph_scaling_list_aps_id; + uint8_t ph_log2_diff_min_qt_min_cb_intra_slice_luma; + uint8_t ph_max_mtt_hierarchy_depth_intra_slice_luma; + uint8_t ph_log2_diff_max_bt_min_qt_intra_slice_luma; + uint8_t ph_log2_diff_max_tt_min_qt_intra_slice_luma; + uint8_t ph_log2_diff_min_qt_min_cb_intra_slice_chroma; + uint8_t ph_max_mtt_hierarchy_depth_intra_slice_chroma; + uint8_t ph_log2_diff_max_bt_min_qt_intra_slice_chroma; + uint8_t ph_log2_diff_max_tt_min_qt_intra_slice_chroma; + uint8_t ph_cu_qp_delta_subdiv_intra_slice; + uint8_t ph_cu_chroma_qp_offset_subdiv_intra_slice; + uint8_t ph_log2_diff_min_qt_min_cb_inter_slice; + uint8_t ph_max_mtt_hierarchy_depth_inter_slice; + uint8_t ph_log2_diff_max_bt_min_qt_inter_slice; + uint8_t ph_log2_diff_max_tt_min_qt_inter_slice; + uint8_t ph_cu_qp_delta_subdiv_inter_slice; + uint8_t ph_cu_chroma_qp_offset_subdiv_inter_slice; + /** \brief Reserved for future use, must be zero */ + uint16_t reserved16b02; + uint32_t reserved32b03[VA_PADDING_LOW - 2]; + + union { + struct { + uint32_t ph_non_ref_pic_flag : 1; + uint32_t ph_alf_enabled_flag : 1; + uint32_t ph_alf_cb_enabled_flag : 1; + uint32_t ph_alf_cr_enabled_flag : 1; + uint32_t ph_alf_cc_cb_enabled_flag : 1; + uint32_t ph_alf_cc_cr_enabled_flag : 1; + uint32_t ph_lmcs_enabled_flag : 1; + uint32_t ph_chroma_residual_scale_flag : 1; + uint32_t ph_explicit_scaling_list_enabled_flag : 1; + uint32_t ph_virtual_boundaries_present_flag : 1; + uint32_t ph_temporal_mvp_enabled_flag : 1; + uint32_t ph_mmvd_fullpel_only_flag : 1; + uint32_t ph_mvd_l1_zero_flag : 1; + uint32_t ph_bdof_disabled_flag : 1; + uint32_t ph_dmvr_disabled_flag : 1; + uint32_t ph_prof_disabled_flag : 1; + uint32_t ph_joint_cbcr_sign_flag : 1; + uint32_t ph_sao_luma_enabled_flag : 1; + uint32_t ph_sao_chroma_enabled_flag : 1; + uint32_t ph_deblocking_filter_disabled_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 12; + } bits; + uint32_t value; + } ph_flags; + + /** \brief Reserved for future use, must be zero */ + uint32_t reserved32b04; + + union { + struct { + /** \brief Flag to indicate if current picture is an intra picture. + * Takes value 1 when all slices of current picture are intra slices. + * Takes value 0 when some slices of current picture may not be + * intra slices. + */ + uint32_t IntraPicFlag : 1; // [0..1] + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 31; + } fields; + uint32_t value; + } PicMiscFlags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved32b[VA_PADDING_HIGH + 1]; + +} VAPictureParameterBufferVVC; + +/** + * \brief VVC Slice Parameter Buffer Structure + * + * VASliceParameterBufferVVC structure should be accompanied by a + * slice data buffer, which holds the whole packed slice NAL unit bit stream + * with emulation prevention bytes not removed. + * + * This structure conveys parameters related to slice header and should + * be sent once per slice. + */ +typedef struct _VASliceParameterBufferVVC { + /** @name Codec-independent Slice Parameter Buffer base. */ + + /**@{*/ + + /** \brief Number of bytes in the slice data buffer for this slice + * counting from and including NAL unit header. + */ + uint32_t slice_data_size; + /** \brief The offset to the NAL unit header for this slice */ + uint32_t slice_data_offset; + /** \brief Slice data buffer flags. See \c VA_SLICE_DATA_FLAG_XXX. */ + uint32_t slice_data_flag; + /** + * \brief Byte offset from NAL unit header to the beginning of slice_data(). + * + * This byte offset is relative to and includes the NAL unit header + * and represents the number of bytes parsed in the slice_header() + * after the removal of any emulation prevention bytes in + * there. However, the slice data buffer passed to the hardware is + * the original bitstream, thus including any emulation prevention + * bytes. + */ + uint32_t slice_data_byte_offset; + /** \brief index into ReferenceFrames[] + * RefPicList[][] corresponds to VVC spec variable with the same name. + * Value range [0..14, 0xFF], where 0xFF indicates invalid entry. + */ + uint8_t RefPicList[2][15]; + + /** + * \brief the subpicture ID of the subpicture that contains the slice. + * The value of the variable CurrSubpicIdx + * is derived to be such that SubpicIdVal[CurrSubpicIdx] is equal + * to sh_subpic_id. CurrSubpicIdx is the index of array VASubPicArrayBufferVVC.SubPicSet[]. + * And it is the spec variable with the same name. + */ + uint16_t sh_subpic_id; + /* parameters below are VVC syntax or spec variables. */ + uint16_t sh_slice_address; + uint16_t sh_num_tiles_in_slice_minus1; + uint8_t sh_slice_type; + uint8_t sh_num_alf_aps_ids_luma; + uint8_t sh_alf_aps_id_luma[7]; + uint8_t sh_alf_aps_id_chroma; + uint8_t sh_alf_cc_cb_aps_id; + uint8_t sh_alf_cc_cr_aps_id; + /** + * \brief NumRefIdxActive[i] - 1 specifies the maximum reference index + * for RPL i that may be used to decode the slice. When NumRefIdxActive[i] + * is equal to 0, no reference index for RPL i is used to decode the slice. + * NumRefIdxActive[] corresponds to VVC spec variable with the same name. + * It is derived according to formula (138) in VVC spec section 7.4.8. + */ + uint8_t NumRefIdxActive[2]; + uint8_t sh_collocated_ref_idx; + /** + * \brief initial value of the QpY quantization parameter for the slice. + * SliceQpY corresponds to VVC spec variable with the same name. + * It is derived according to formula (86) in VVC spec section 7.4.3.8 + * and formula (139) in VVC Spec section 7.4.8. + */ + int8_t SliceQpY; + /* parameters below are VVC syntax. */ + int8_t sh_cb_qp_offset; + int8_t sh_cr_qp_offset; + int8_t sh_joint_cbcr_qp_offset; + int8_t sh_luma_beta_offset_div2; + int8_t sh_luma_tc_offset_div2; + int8_t sh_cb_beta_offset_div2; + int8_t sh_cb_tc_offset_div2; + int8_t sh_cr_beta_offset_div2; + int8_t sh_cr_tc_offset_div2; + /** \brief Reserved bytes for future use, must be zero */ + uint8_t reserved8b[VA_PADDING_LOW - 1]; + uint32_t reserved32b; + + // weighted prediction info + VAWeightedPredInfo WPInfo; + + union { + struct { + /* flags below are VVC syntax. */ + uint32_t sh_alf_enabled_flag : 1; + uint32_t sh_alf_cb_enabled_flag : 1; + uint32_t sh_alf_cr_enabled_flag : 1; + uint32_t sh_alf_cc_cb_enabled_flag : 1; + uint32_t sh_alf_cc_cr_enabled_flag : 1; + uint32_t sh_lmcs_used_flag : 1; + uint32_t sh_explicit_scaling_list_used_flag : 1; + uint32_t sh_cabac_init_flag : 1; + uint32_t sh_collocated_from_l0_flag : 1; + uint32_t sh_cu_chroma_qp_offset_enabled_flag : 1; + uint32_t sh_sao_luma_used_flag : 1; + uint32_t sh_sao_chroma_used_flag : 1; + uint32_t sh_deblocking_filter_disabled_flag : 1; + uint32_t sh_dep_quant_used_flag : 1; + uint32_t sh_sign_data_hiding_used_flag : 1; + uint32_t sh_ts_residual_coding_disabled_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 16; + } bits; + uint32_t value; + } sh_flags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VASliceParameterBufferVVC; + +/** + * \brief VVC Scaling List Data Structure + * + * Host decoder sends in an array of VVC Scaling Lists through one or multiple + * buffers which may contain 1 to 8 VAScalingListVVC data structures in total. + * Each buffer contains an integer number of VAScalingListVVC data structures + * with no gap in between. + * Driver may store the data internally. Host decoder may choose not to + * send the same scaling list data for each frame. When a VAScalingListVVC + * structure carries a same value of aps_adaptation_parameter_set_id + * as a previously stored structure, driver should override the old structure + * with values in the new structure. + * VAIQMatrixBufferType is used to send this buffer. + */ +typedef struct _VAScalingListVVC { + /** \brief VVC syntax to specify the identifier for the APS.*/ + uint8_t aps_adaptation_parameter_set_id; + /** \brief Reserved for future use, must be zero */ + uint8_t reserved8b; + /** + * \brief Specifies the spec variable ScalingMatrixDCRec[id−14], + * where id = [14..27]. + */ + uint8_t ScalingMatrixDCRec[14]; + /** + * \brief Specifies the spec variable ScalingMatrixRec[id][x][y], + * where id = [0..1]. Check section 7.4.3.20 for derivation process. + */ + uint8_t ScalingMatrixRec2x2[2][2][2]; + /** + * \brief Specifies the spec variable ScalingMatrixRec[id][x][y], + * where id = [2..7]. Check section 7.4.3.20 for derivation process. + */ + uint8_t ScalingMatrixRec4x4[6][4][4]; + /** + * \brief Specifies the spec variable ScalingMatrixRec[id][x][y], + * where id = [8..27]. Check section 7.4.3.20 for derivation process. + */ + uint8_t ScalingMatrixRec8x8[20][8][8]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAScalingListVVC; + +/** + * \brief VVC Adaptive Loop Filter Data Structure + * + * Host decoder sends in an array of VVC ALF sets through one or multiple + * buffers which may contain 1 to 8 VAAlfDataVVC data structures in total. + * Each buffer contains an integer number of VAAlfDataVVC data structures + * with no gap in between. + * Driver may store the data internally. Host decoder may choose not to + * send the same ALF data for each frame. When a VAAlfDataVVC structure + * carries a same value of aps_adaptation_parameter_set_id as a previously + * stored structure, driver should override the old structure + * with values in the new structure. + * VAAlfBufferType is used to send this buffer. + */ +typedef struct _VAAlfDataVVC { + /** + * \brief VVC Adaptive Loop Filter parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + uint8_t aps_adaptation_parameter_set_id; + uint8_t alf_luma_num_filters_signalled_minus1; + uint8_t alf_luma_coeff_delta_idx[25]; + int8_t filtCoeff[25][12]; + uint8_t alf_luma_clip_idx[25][12]; + uint8_t alf_chroma_num_alt_filters_minus1; + int8_t AlfCoeffC[8][6]; + uint8_t alf_chroma_clip_idx[8][6]; + uint8_t alf_cc_cb_filters_signalled_minus1; + int8_t CcAlfApsCoeffCb[4][7]; + uint8_t alf_cc_cr_filters_signalled_minus1; + int8_t CcAlfApsCoeffCr[4][7]; + /** \brief Reserved bytes for future use, must be zero */ + uint16_t reserved16b; + uint32_t reserved32b; + + union { + struct { + uint32_t alf_luma_filter_signal_flag : 1; + uint32_t alf_chroma_filter_signal_flag : 1; + uint32_t alf_cc_cb_filter_signal_flag : 1; + uint32_t alf_cc_cr_filter_signal_flag : 1; + uint32_t alf_luma_clip_flag : 1; + uint32_t alf_chroma_clip_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 26; + } bits; + uint32_t value; + } alf_flags; + + /** \brief Reserved for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VAAlfDataVVC; + +/** + * \brief VVC Luma Mapping with Chroma Scaling Data Structure + * + * Host decoder sends in an array of VVC LMCS sets through one or multiple + * buffers which may contain 1 to 4 VALmcsDataVVC data structures in total. + * Each buffer contains an integer number of VALmcsDataVVC data structures + * with no gap in between. + * Driver may store the data internally. Host decoder may choose not to + * send the same LMCS data for each frame. When a VALmcsDataVVC structure + * carries a same value of aps_adaptation_parameter_set_id as a previously + * stored structure, driver should override the old structure + * with values in the new structure. + * VALmcsBufferType is used to send this buffer. + */ +typedef struct _VALmcsDataVVC { + /** + * \brief VVC Luma Mapping with Chroma Scaling parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + uint8_t aps_adaptation_parameter_set_id; + uint8_t lmcs_min_bin_idx; + uint8_t lmcs_delta_max_bin_idx; + int16_t lmcsDeltaCW[16]; + int8_t lmcsDeltaCrs; + /** \brief Reserved for future use, must be zero */ + uint8_t reserved8b[VA_PADDING_LOW - 1]; + uint32_t va_reserved[VA_PADDING_MEDIUM]; +} VALmcsDataVVC; + +/** + * \brief VVC SubPicture Data Structure + * + * Host decoder sends in an array of VVC SubPic sets through one or + * multiple buffers which contain sps_num_subpics_minus1 + 1 + * VASubPicVVC data structures in total. Each buffer contains + * an integer number of VASubPicVVC data structures with no gap in between. + * The Subpic sets are sent sequentially in the order of indices + * from 0 to sps_num_subpics_minus1 according to the bitstream. + * VASubPicBufferType is used to send this buffer. + */ +typedef struct _VASubPicVVC { + /** + * \brief VVC SubPicture layout parameters. + * All the parameters except reserved bytes are VVC syntax or spec variables. + */ + uint16_t sps_subpic_ctu_top_left_x; + uint16_t sps_subpic_ctu_top_left_y; + uint16_t sps_subpic_width_minus1; + uint16_t sps_subpic_height_minus1; + /** \brief the subpicture ID of the i-th subpicture. + * It is same variable as in VVC spec. + */ + uint16_t SubpicIdVal; + + union { + struct { + uint16_t sps_subpic_treated_as_pic_flag : 1; + uint16_t sps_loop_filter_across_subpic_enabled_flag : 1; + /** \brief Reserved for future use, must be zero */ + uint16_t reserved : 14; + } bits; + uint16_t value; + } subpic_flags; + + /** \brief Reserved for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASubPicVVC; + +/** + * \brief data buffer of tile widths and heights. + * VATileBufferType is used to send this buffer. + * + * Host decoder sends in number of pps_num_exp_tile_columns_minus1 + 1 + * tile column widths of pps_tile_column_width_minus1[i], followed by + * number of pps_num_exp_tile_rows_minus1 + 1 of tile row heights of + * pps_tile_row_height_minus1[i], through one or multiple buffers. + * Each tile width or height is formatted as + uint16_t tile_dimension; + * Each buffer contains an integer number of tile_dimension with + * no gap in between. + * The buffers with type VATileBufferType should be submitted for each + * picture. And driver will derive the tile structure from it. + * When pps_num_exp_tile_columns_minus1 + pps_num_exp_tile_rows_minus1 equals 0, + * this buffer is still submitted by app to driver. + */ + + +/** + * \brief VVC SliceStruct Data Structure + * + * Host decoder sends in an array of SliceStruct sets through one or multiple + * buffers. These SliceStruct sets contain only the "explicit" slices parsed + * from PPS header. + * Each SliceStruct set is described by VASliceStructVVC data structure. + * Each buffer contains an integer number of VASliceStructVVC data structures, + * which are laid out sequentially in the order of + * ascending slice indices according to the spec with no gap in between. + * + * When pps_rect_slice_flag equals 0 or there are no explicit slices, + * this buffer is not submitted by app to driver. Otherwise, for each picture, + * this buffer should be submitted. + * + * Note: When pps_slice_width_in_tiles_minus1 + pps_slice_height_in_tiles_minus1 + * equals 0, if the sum of pps_exp_slice_height_in_ctus_minus1 + 1 of all those + * slices with same SliceTopLeftTileIdx value is less than the height of tile + * SliceTopLeftTileIdx in unit of CTUs, driver should derive the rest slices in + * that tile according to equation (21) in spec section 6.5.1. And VASliceStructVVC + * for these (derived) slices are not passed in to LibVA by App. + * + * App should populate the data entries regardless of values of + * pps_single_slice_per_subpic_flag or sps_subpic_info_present_flag. + * + * VASliceStructBufferType is used to send this buffer. + */ +typedef struct _VASliceStructVVC { + /** \brief the tile index of which the starting CTU (top-left) of + * the slice belongs to. The tile index is in raster scan order. + * Same syntax variable as in VVC spec. + */ + uint16_t SliceTopLeftTileIdx; + /* plus 1 specifies the width of the rectangular slice in units + * of tile columns. + */ + uint16_t pps_slice_width_in_tiles_minus1; + /* plus 1 specifies the height of the rectangular slice in units + * of tile rows. If the slice does not cover the whole tile, + * pps_slice_height_in_tiles_minus1 shall be 0. + */ + uint16_t pps_slice_height_in_tiles_minus1; + /* plus 1 specifies the height of the rectangular slice in units + * of CTU rows. + * If pps_slice_width_in_tiles_minus1 + pps_slice_height_in_tiles_minus1 > 0, + * set this value to 0. + * If pps_slice_width_in_tiles_minus1 + pps_slice_height_in_tiles_minus1 == 0, + * and if there is only one slice in tile, set this value to the number of + * CTU rows of the tile minus 1, otherwise, set the value equal to + * corresponding pps_exp_slice_height_in_ctus_minus1 from bitstream. + */ + uint16_t pps_exp_slice_height_in_ctus_minus1; + + /** \brief Reserved for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VASliceStructVVC; + + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_DEC_VVC_H */ diff --git a/rs/moq-vaapi/libva/va/va_drmcommon.h b/rs/moq-vaapi/libva/va/va_drmcommon.h new file mode 100644 index 00000000000..4f93f8cf24b --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_drmcommon.h @@ -0,0 +1,234 @@ +/* + * va_drmcommon.h - Common utilities for DRM-based drivers + * + * Copyright (c) 2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_DRM_COMMON_H +#define VA_DRM_COMMON_H + +#include +#include + + +/** \brief DRM authentication type. */ +enum { + /** \brief Disconnected. */ + VA_DRM_AUTH_NONE = 0, + /** + * \brief Connected. Authenticated with DRI1 protocol. + * + * @deprecated + * This is a deprecated authentication type. All DRI-based drivers have + * been migrated to use the DRI2 protocol. Newly written drivers shall + * use DRI2 protocol only, or a custom authentication means. e.g. opt + * for authenticating on the VA driver side, instead of libva side. + */ + VA_DRM_AUTH_DRI1 = 1, + /** + * \brief Connected. Authenticated with DRI2 protocol. + * + * This is only useful to VA/X11 drivers. The libva-x11 library provides + * a helper function VA_DRI2Authenticate() for authenticating the + * connection. However, DRI2 conformant drivers don't need to call that + * function since authentication happens on the libva side, implicitly. + */ + VA_DRM_AUTH_DRI2 = 2, + /** + * \brief Connected. Authenticated with some alternate raw protocol. + * + * This authentication mode is mainly used in non-VA/X11 drivers. + * Authentication happens through some alternative method, at the + * discretion of the VA driver implementation. + */ + VA_DRM_AUTH_CUSTOM = 3 +}; + +/** \brief Base DRM state. */ +struct drm_state { + /** \brief DRM connection descriptor. */ + int fd; + /** \brief DRM authentication type. */ + int auth_type; + /** \brief Reserved bytes for future use, must be zero */ + int va_reserved[8]; +}; + +/** \brief Kernel DRM buffer memory type. */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM 0x10000000 +/** \brief DRM PRIME memory type (old version) + * + * This supports only single objects with restricted memory layout. + * Used with VASurfaceAttribExternalBuffers. + */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME 0x20000000 +/** \brief DRM PRIME memory type + * + * Used with VADRMPRIMESurfaceDescriptor. + */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 0x40000000 +/** \brief DRM PRIME3 memory type + * + * Used with VADRMPRIME3SurfaceDescriptor. + */ +#define VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_3 0x08000000 + +/** + * \brief External buffer descriptor for a DRM PRIME surface. + * + * For export, call vaExportSurfaceHandle() with mem_type set to + * VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and pass a pointer to an + * instance of this structure to fill. + * If VA_EXPORT_SURFACE_SEPARATE_LAYERS is specified on export, each + * layer will contain exactly one plane. For example, an NV12 + * surface will be exported as two layers, one of DRM_FORMAT_R8 and + * one of DRM_FORMAT_GR88. + * If VA_EXPORT_SURFACE_COMPOSED_LAYERS is specified on export, + * there will be exactly one layer. + * + * For import, call vaCreateSurfaces() with the MemoryType attribute + * set to VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and the + * ExternalBufferDescriptor attribute set to point to an array of + * num_surfaces instances of this structure. + * The number of planes which need to be provided for a given layer + * is dependent on both the format and the format modifier used for + * the objects containing it. For example, the format DRM_FORMAT_RGBA + * normally requires one plane, but with the format modifier + * I915_FORMAT_MOD_Y_TILED_CCS it requires two planes - the first + * being the main data plane and the second containing the color + * control surface. + * Note that a given driver may only support a subset of possible + * representations of a particular format. For example, it may only + * support NV12 surfaces when they are contained within a single DRM + * object, and therefore fail to create such surfaces if the two + * planes are in different DRM objects. + * Note that backend driver will retrieve the resource represent by fd, + * and a valid surface ID is generated. Backend driver will not close + * the file descriptor. Application should handle the release of the fd. + * releasing the fd will not impact the existence of the surface. + */ +typedef struct _VADRMPRIMESurfaceDescriptor { + /** Pixel format fourcc of the whole surface (VA_FOURCC_*). */ + uint32_t fourcc; + /** Width of the surface in pixels. */ + uint32_t width; + /** Height of the surface in pixels. */ + uint32_t height; + /** Number of distinct DRM objects making up the surface. */ + uint32_t num_objects; + /** Description of each object. */ + struct { + /** DRM PRIME file descriptor for this object. */ + int fd; + /** Total size of this object (may include regions which are + * not part of the surface). */ + uint32_t size; + /** Format modifier applied to this object. */ + uint64_t drm_format_modifier; + } objects[4]; + /** Number of layers making up the surface. */ + uint32_t num_layers; + /** Description of each layer in the surface. */ + struct { + /** DRM format fourcc of this layer (DRM_FOURCC_*). */ + uint32_t drm_format; + /** Number of planes in this layer. */ + uint32_t num_planes; + /** Index in the objects array of the object containing each + * plane. */ + uint32_t object_index[4]; + /** Offset within the object of each plane. */ + uint32_t offset[4]; + /** Pitch of each plane. */ + uint32_t pitch[4]; + } layers[4]; +} VADRMPRIMESurfaceDescriptor; + +/** + * \brief External buffer descriptor for a DRM PRIME surface with flags + * + * This structure is an extention for VADRMPRIMESurfaceDescriptor, + * it has the same behavior as if used with VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2. + * + * The field "flags" is added, see "Surface external buffer descriptor flags". + * To use this structure, use VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_3 instead. + */ +typedef struct _VADRMPRIME3SurfaceDescriptor { + /** Pixel format fourcc of the whole surface (VA_FOURCC_*). */ + uint32_t fourcc; + /** Width of the surface in pixels. */ + uint32_t width; + /** Height of the surface in pixels. */ + uint32_t height; + /** Number of distinct DRM objects making up the surface. */ + uint32_t num_objects; + /** Description of each object. */ + struct { + /** DRM PRIME file descriptor for this object. */ + int fd; + /** Total size of this object (may include regions which are + * not part of the surface). */ + uint32_t size; + /** Format modifier applied to this object. */ + uint64_t drm_format_modifier; + } objects[4]; + /** Number of layers making up the surface. */ + uint32_t num_layers; + /** Description of each layer in the surface. */ + struct { + /** DRM format fourcc of this layer (DRM_FOURCC_*). */ + uint32_t drm_format; + /** Number of planes in this layer. */ + uint32_t num_planes; + /** Index in the objects array of the object containing each + * plane. */ + uint32_t object_index[4]; + /** Offset within the object of each plane. */ + uint32_t offset[4]; + /** Pitch of each plane. */ + uint32_t pitch[4]; + } layers[4]; + /** \brief flags. See "Surface external buffer descriptor flags". */ + uint32_t flags; + /** reserved bytes, must be zero */ + uint32_t reserved[VA_PADDING_MEDIUM - 1]; +} VADRMPRIME3SurfaceDescriptor; +/** + * \brief List of DRM format modifiers. + * + * To allocate surfaces with one of the modifiers specified in the array, call + * vaCreateSurfaces() with the VASurfaceAttribDRMFormatModifiers attribute set + * to point to an array of num_surfaces instances of this structure. The driver + * will select the optimal modifier in the list. + * + * DRM format modifiers are defined in drm_fourcc.h in the Linux kernel. + */ +typedef struct _VADRMFormatModifierList { + /** Number of modifiers. */ + uint32_t num_modifiers; + /** Array of modifiers. */ + uint64_t *modifiers; +} VADRMFormatModifierList; + + +#endif /* VA_DRM_COMMON_H */ diff --git a/rs/moq-vaapi/libva/va/va_egl.h b/rs/moq-vaapi/libva/va/va_egl.h new file mode 100644 index 00000000000..d6acb7daf78 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_egl.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2007 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef _VA_EGL_H_ +#define _VA_EGL_H_ + +#warning The APIs / data structures included in this file are deprecated + +#endif /* _VA_EGL_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_enc_av1.h b/rs/moq-vaapi/libva/va/va_enc_av1.h new file mode 100644 index 00000000000..9d7f67f1e1d --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_av1.h @@ -0,0 +1,1010 @@ +/* + * Copyright (c) 2021 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_av1.h + * \brief AV1 encoding API + * + * This file contains the \ref api_enc_av1 "AV1 encoding API". + * + */ + +#ifndef VA_ENC_AV1_H +#define VA_ENC_AV1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * \defgroup api_enc_av1 AV1 encoding API + * + * This AV1 encoding API supports 8-bit/10bit 420 format only. + * + * @{ + */ + +/** \brief Attribute value for VAConfigAttribEncAV1. + * + * This attribute decribes the supported features of an AV1 + * encoder configuration. + * + * All of the field values in this attribute are VA_FEATURE_* values, + * indicating support for the corresponding feature. + * + */ +typedef union _VAConfigAttribValEncAV1 { + struct { + /** + * \brief Use 128x128 superblock. + * + * Allows setting use_128x128_superblock in the SPS. + */ + uint32_t support_128x128_superblock : 2; + /** + * \brief Intra filter. + * Allows setting enable_filter_intra in the SPS. + */ + uint32_t support_filter_intra : 2; + /** + * \brief Intra edge filter. + * Allows setting enable_intra_edge_filter in the SPS. + */ + uint32_t support_intra_edge_filter : 2; + /** + * \brief Interintra compound. + * Allows setting enable_interintra_compound in the SPS. + */ + uint32_t support_interintra_compound : 2; + /** + * \brief Masked compound. + * Allows setting enable_masked_compound in the SPS. + */ + uint32_t support_masked_compound : 2; + /** + * \brief Warped motion. + * Allows setting enable_warped_motion in the SPS. + */ + uint32_t support_warped_motion : 2; + /** + * \brief Palette mode. + * Allows setting palette_mode in the PPS. + */ + uint32_t support_palette_mode : 2; + /** + * \brief Dual filter. + * Allows setting enable_dual_filter in the SPS. + */ + uint32_t support_dual_filter : 2; + /** + * \brief Jnt compound. + * Allows setting enable_jnt_comp in the SPS. + */ + uint32_t support_jnt_comp : 2; + /** + * \brief Refrence frame mvs. + * Allows setting enable_ref_frame_mvs in the SPS. + */ + uint32_t support_ref_frame_mvs : 2; + /** + * \brief Super resolution. + * Allows setting enable_superres in the SPS. + */ + uint32_t support_superres : 2; + /** + * \brief Restoration. + * Allows setting enable_restoration in the SPS. + */ + uint32_t support_restoration : 2; + /** + * \brief Allow intraBC. + * Allows setting allow_intrabc in the PPS. + */ + uint32_t support_allow_intrabc : 2; + /** + * \brief Cdef channel strength. + * Allows setting cdef_y_strengths and cdef_uv_strengths in PPS. + */ + uint32_t support_cdef_channel_strength : 2; + /** \brief Reserved bits for future, must be zero. */ + uint32_t reserved : 4; + } bits; + uint32_t value; +} VAConfigAttribValEncAV1; + +/** \brief Attribute value for VAConfigAttribEncAV1Ext1. */ +typedef union _VAConfigAttribValEncAV1Ext1 { + struct { + /** + * \brief Fields indicate which types of interpolation filter are supported. + * (interpolation_filter & 0x01) == 1: eight_tap filter is supported, 0: not. + * (interpolation_filter & 0x02) == 1: eight_tap_smooth filter is supported, 0: not. + * (interpolation_filter & 0x04) == 1: eight_sharp filter is supported, 0: not. + * (interpolation_filter & 0x08) == 1: bilinear filter is supported, 0: not. + * (interpolation_filter & 0x10) == 1: switchable filter is supported, 0: not. + */ + uint32_t interpolation_filter : 5; + /** + * \brief segmentId block size accepted. + * Application need to send seg_id_block_size in PPS equal or larger than this value. + * one bit represent one block size defined as VA_SEGID_BLOCKXXXX + * should be (1 << VA_SEGID_BLOCKXXX | 1 << VA_SEGID_BLOCKXXX ... ) + */ + uint32_t min_segid_block_size_accepted : 8; + /** + * \brief Type of segment feature supported. + * (segment_feature_support & 0x01) == 1: SEG_LVL_ALT_Q is supported, 0: not. + * (segment_feature_support & 0x02) == 1: SEG_LVL_ALT_LF_Y_V is supported, 0: not. + * (segment_feature_support & 0x04) == 1: SEG_LVL_ALT_LF_Y_H is supported, 0: not. + * (segment_feature_support & 0x08) == 1: SEG_LVL_ALT_LF_U is supported, 0: not. + * (segment_feature_support & 0x10) == 1: SEG_LVL_ALT_LF_V is supported, 0: not. + * (segment_feature_support & 0x20) == 1: SEG_LVL_REF_FRAME is supported, 0: not. + * (segment_feature_support & 0x40) == 1: SEG_LVL_SKIP is supported, 0: not. + * (segment_feature_support & 0x80) == 1: SEG_LVL_GLOBALMV is supported, 0: not. + */ + uint32_t segment_feature_support : 8; + /** \brief Reserved bits for future, must be zero. */ + uint32_t reserved : 11; + } bits; + uint32_t value; +} VAConfigAttribValEncAV1Ext1; + +/** \brief Attribute value for VAConfigAttribEncAV1Ext2. */ +typedef union _VAConfigAttribValEncAV1Ext2 { + struct { + /** + * \brief Tile size bytes minus1. + * Specify the number of bytes needed to code tile size supported. + * This value need to be set in frame header obu. + */ + uint32_t tile_size_bytes_minus1 : 2; + /** + * \brief Tile size bytes minus1. + * Specify the fixed number of bytes needed to code syntax obu_size. + */ + uint32_t obu_size_bytes_minus1 : 2; + /** + * \brief tx_mode supported. + * (tx_mode_support & 0x01) == 1: ONLY_4X4 is supported, 0: not. + * (tx_mode_support & 0x02) == 1: TX_MODE_LARGEST is supported, 0: not. + * (tx_mode_support & 0x04) == 1: TX_MODE_SELECT is supported, 0: not. + */ + uint32_t tx_mode_support : 3; + /** + * \brief Max tile num minus1. + * Specify the max number of tile supported by driver. + */ + uint32_t max_tile_num_minus1 : 13; + /** \brief Reserved bits for future, must be zero. */ + uint32_t reserved : 12; + } bits; + uint32_t value; +} VAConfigAttribValEncAV1Ext2; + +/** + * \brief Packed header types specific to AV1 encoding. + * + * Types of packed headers generally used for AV1 encoding. + * + */ +typedef enum { + /** + * \brief Packed Sequence Parameter Set (SPS). + * + * The corresponding packed header data buffer shall contain the + * complete sequence_header_obu() syntax element. + * + */ + VAEncPackedHeaderAV1_SPS = VAEncPackedHeaderSequence, + /** + * \brief Packed Picture Parameter Set (PPS). + * + * The corresponding packed header data buffer shall contain the + * complete frame_header_obu() syntax element. + * + */ + VAEncPackedHeaderAV1_PPS = VAEncPackedHeaderPicture, +} VAEncPackedHeaderTypeAV1; + +/** + * \brief AV1 Encoding Sequence Parameter Buffer Structure. + * + * This structure conveys sequence level parameters. + * + */ +typedef struct _VAEncSequenceParameterBufferAV1 { + /** \brief AV1 profile setting. + * value range [0..2]. + */ + uint8_t seq_profile; + + /** \brief Level Setting of current operation point. + * value range [0..23]. + */ + uint8_t seq_level_idx; + + /** \brief Tier Setting of current operation point. + * value range [0..1]. + */ + uint8_t seq_tier; + + /** \brief Indicates whether or not the encoding is in dyadic hierarchical GOP structure. + * value range [0..1]. + */ + uint8_t hierarchical_flag; + + /** \brief Period between intra_only frames. */ + uint32_t intra_period; + + /** \brief Period between I/P frames. + * For hierarchical structure, this is the anchor frame distance. + */ + uint32_t ip_period; + + /* \brief RC related fields. RC modes are set with VAConfigAttribRateControl. */ + /* For AV1, CBR implies HRD conformance and VBR implies no HRD conformance. */ + + /** + * \brief Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for CBR mode or + * initial max bitrate value for VBR mode in this sequence. + * i.e. if the encoder pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * The bitrate can be modified later on through + * #VAEncMiscParameterRateControl buffers. + */ + uint32_t bits_per_second; + + union { + struct { + /** \brief Still picture encoding, no inter frame referencing. */ + uint32_t still_picture : 1; + /** \brief Force using 128x128 or 64x64 Supper block */ + uint32_t use_128x128_superblock : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_filter_intra : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_intra_edge_filter : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_interintra_compound : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_masked_compound : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_warped_motion : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_dual_filter : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_order_hint : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_jnt_comp : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_ref_frame_mvs : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_superres : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_cdef : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t enable_restoration : 1; + /** \brief Sepcify number of bits for every channel(Y, U or V). */ + uint32_t bit_depth_minus8 : 3; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t subsampling_x : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t subsampling_y : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t mono_chrome : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t reserved_bits : 12; + } bits; + uint32_t value; + } seq_fields; + + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..7]. + */ + uint8_t order_hint_bits_minus_1; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_HIGH]; +} VAEncSequenceParameterBufferAV1; + +#define VA_AV1_MAX_SEGMENTS 8 +#define VA_AV1_SEG_LVL_MAX 8 + +/** + * \brief Segment parameters + */ +typedef struct _VAEncSegParamAV1 { + union { + struct { + /** \brief Indicates if segmentation is enabled in the current frame. + * If disabled, all the below parameters in the structure should + * be set to 0, and ignored by driver. + */ + uint8_t segmentation_enabled : 1; + + /** + * When segmentation_enabled equals 1 and segment_number > 0, + * this parameter equals 1 indicates the segmentation map may + * come from application, and that "Segment map data buffer" + * should be provided with populated segment_id. If equals 0, + * segmentation map should be inherited from a reference frame + * (specified by \c primary_ref_frame). When segmentation_enabled or + * segment_number equals 0, this parameter should be set to 0 + * and ignored by driver. + */ + uint8_t segmentation_update_map : 1; + /** + * When segmentation_update_map equals 1, this parameter equaling 1 + * indicates segment id per block will be determined either from + * reference frame or from app. Equaling 0 means segment id per block + * will come from app. When segmentation_temporal_update equals 0, + * this parameter should be set to 0 and ignored by driver. + */ + uint8_t segmentation_temporal_update : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint8_t reserved : 5; + + } bits; + uint8_t value; + } seg_flags; + + /** + * If segmentation_enabled equals 1, this parameter indicates + * the number of segments conveyed through VAAPI. In this case, + * if segment_number equals 0, it will force the driver to determine + * how many segments would be created as well as the segmentation map + * to be generated. Also the driver shall write the segmentation_params() + * syntax in the uncompressed header at \c bit_offset_segmentation (back-annotation). + * In application, the rest parameters in this structure should be all + * set to 0 and ignored by driver. And app should NOT send the + * "Segment map data buffer". In packed uncompressed header + * bitstream, app should write syntax element segmentation_enabled + * as 0 and segmentation_params() should be only 1-bit-long. + * If segment_number > 0, and segmentation_update_map = 1, app should provide + * the "Segment map data buffer" and populate the rest of the + * current data structure. And that underline encoder would honor + * the segmentation parameters feature_data[0..segment_number-1][] + * and feature_mask[0..segment_number-1], etc. + * Value range [0..8]. + */ + uint8_t segment_number; + + /** \brief segment parameters. + * feature_data[][] is equivalent to variable FeatureData[][] in spec, + * which is after clip3() operation. + * Clip3(x, y, z) = (z y)? y : z); + * The limit is defined in Segmentation_Feature_Max[ SEG_LVL_MAX ] = { + * 255, MAX_LOOP_FILTER, MAX_LOOP_FILTER, MAX_LOOP_FILTER, + * MAX_LOOP_FILTER, 7, 0, 0 } + */ + int16_t feature_data[VA_AV1_MAX_SEGMENTS][VA_AV1_SEG_LVL_MAX]; + + /** \brief Bit field to indicate each feature is enabled or not per + * segment_id. Each bit is the feature_id. + */ + uint8_t feature_mask[VA_AV1_MAX_SEGMENTS]; + + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSegParamAV1; + +/** + * \brief Segment map data buffer. + * + * This buffer is optional depending on the value of av1_segments.segmentation_enabled. + * If av1_segments.segmentation_enabled in the picture parameters equals 1, + * and RateControlMethod is not CQP and this surface is not provided by App, + * the encoder will determine the per block segmentation map. In this case, + * App should not provide the segmentation parameter data structure + * in frame header as well. If av1_segments.segmentation_enabled equals 1 + * and the segmentation map buffer is provided, app should embed the + * segmentation info in frame header, populate the VAEncSegParamAV1 structure with + * #VAEncMacroblockMapBufferType and the driver as well as the underline encoder + * should honor what is given by the app. + */ +typedef struct _VAEncSegMapBufferAV1 { + /** \brief Segment map data size. */ + uint32_t segmentMapDataSize; + + /** + * \brief Segment map. + * Size of this map is indicated by \ref segmentMapDataSize and each element + * in this map contains the segment id of a particular block. + * The element is indexed by raster scan order. + * The value of each entry should be in the range [0..7], inclusive. + */ + uint8_t *pSegmentMap; +} VAEncSegMapBufferAV1; + +typedef enum { + /** \brief Identity transformation, 0-parameter. */ + VAAV1EncTransformationIdentity = 0, + /** \brief Translational motion, 2-parameter. */ + VAAV1EncTransformationTranslation = 1, + /** \brief Simplified affine with rotation + zoom only, 4-parameter. */ + VAAV1EncTransformationRotzoom = 2, + /** \brief Affine, 6-parameter. */ + VAAV1EncTransformationAffine = 3, + /** \brief Transformation count. */ + VAAV1EncTransformationCount +} VAEncTransformationTypeAV1; + +typedef struct _VAEncWarpedMotionParamsAV1 { + + /** \brief Specify the type of warped motion. */ + VAEncTransformationTypeAV1 wmtype; + + /** \brief Specify warp motion parameters. + * wm.wmmat[] corresponds to gm_params[][] in spec. + * Details in AV1 spec section 5.9.24 or refer to libaom code + * https://aomedia.googlesource.com/aom/+/refs/heads/master/av1/decoder/decodeframe.c. + */ + int32_t wmmat[8]; + + /** \brief Valid or invalid on affine set. */ + uint8_t invalid; + + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t va_reserved[VA_PADDING_LOW]; + +} VAEncWarpedMotionParamsAV1; + +/** + * \brief Reference frame control. + * + * Suggest which frame to be used as reference along with preferred search order. + * + * search_idx#: index into ref_frame_idx[] to indicate that frame will be included + * in the reference list if value in range [1..7]. Invalid when value is 0. + * The order of the search_idx# indicates the preferred search order. + * + */ +typedef union { + struct { + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx0 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx1 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx2 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx3 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx4 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx5 : 3; + /** + * \brief Value used as index into ref_frame_idx[] to indicate that frame + * will be included in the reference list. + * valid value range: [1..7], invalid when value is 0. + */ + uint32_t search_idx6 : 3; + + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t Reserved : 11; + } fields; + uint32_t value; +} VARefFrameCtrlAV1; + +/** + * \brief AV1 Encoding Picture Parameter Buffer Structure. + * + * This structure conveys picture level parameters. + * + */ +typedef struct _VAEncPictureParameterBufferAV1 { + /** \brief AV1 encoder may support SupRes and dynamic scaling function. + * For SupRes, underline encoder is responsible to do downscaling. + * For dynamic scaling, app should provide the scaled raw source. + */ + /** \brief Raw source frame width in pixels. */ + uint16_t frame_width_minus_1; + /** \brief Raw source frame height in pixels. */ + uint16_t frame_height_minus_1; + + /** \brief Surface to store reconstructed frame, not used for enc only case. */ + VASurfaceID reconstructed_frame; + + /** \brief Buffer to store coded data. */ + VABufferID coded_buf; + + /** \brief Reference frame buffers. + * Each entry of the array specifies the surface index of the picture + * that is referred by current picture or will be referred by any future + * picture. The valid entries take value from 0 to 127, inclusive. + * Non-valid entries, those do not point to pictures which are referred + * by current picture or future pictures, should take value 0xFF. + * Other values are not allowed. + * + * Application should update this array based on the refreshing + * information expected. + */ + VASurfaceID reference_frames[8]; + + /** \brief Reference index list. + * Contains a list of indices into refernce_frames[]. + * Indice with refernce frames range: [LAST_FRAME - LAST_FRAME, + * LAST2_FRAME - LAST_FRAME, ..., ALTREF2_FRAME - LAST_FRAME]. + * #define LAST_FRAME 1 + * #define LAST2_FRAME 2 + * #define LAST3_FRAME 3 + * #define GOLDEN_FRAME 4 + * #define BWDREF_FRAME 5 + * #define ALTREF_FRAME 6 + * #define ALTREF2_FRAME 7 + * value range [0..7]. + */ + uint8_t ref_frame_idx[7]; + + /** \brief When hierarchical_level_plus1 > 0, hierarchical_level_plus1-1 indicates + * the current frame's level. If VAEncMiscParameterTemporalLayerStructure + * is valid (number_of_layers >0), hierarchical_level_plus1 shouldn't larger than number_of_layers. + */ + uint8_t hierarchical_level_plus1; + + /** \brief primary reference frame. + * Index into reference_frames[] + * segment id map, context table, etc. come from the reference + * frame pointed by this index. + * value range [0..7]. + */ + uint8_t primary_ref_frame; + + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint8_t order_hint; + + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint8_t refresh_frame_flags; + + /** \brief Reserved bytes for future use, must be zero. */ + uint8_t reserved8bits1; + + /** \brief Suggest which frames to be used as references. + * see struct #VARefFrameCtrl for details. + */ + VARefFrameCtrlAV1 ref_frame_ctrl_l0; + VARefFrameCtrlAV1 ref_frame_ctrl_l1; + + union { + struct { + /** \brief frame type. + * 0: key_frame. + * 1: inter_frame. + * 2: intra_only frame. + * 3: switch_frame (app needs to set error_resilient_mode = 1, + * refresh_frame_flags, etc approperately.). + */ + uint32_t frame_type : 2; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t error_resilient_mode : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t disable_cdf_update : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t use_superres : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t allow_high_precision_mv : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t use_ref_frame_mvs : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t disable_frame_end_update_cdf : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t reduced_tx_set : 1; + + /** \brief For single tile group, app may choose to use one frame obu + * to replace one frame header obu + one tile group obu. + * Invalid if num_tile_groups_minus1 > 0. + */ + uint32_t enable_frame_obu : 1; + + /** \brief Indicate the current frame will be used as a long term reference. */ + uint32_t long_term_reference : 1; + /** \brief If the encoded frame will not be referred by other frames, + * its recon may not be generated in order to save memory bandwidth. + */ + uint32_t disable_frame_recon : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t allow_intrabc : 1; + /** \brief Equal to 1 indicates that intra blocks may use palette encoding. + * Otherwise disable palette encoding. + */ + uint32_t palette_mode_enable : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t allow_screen_content_tools : 1; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint32_t force_integer_mv : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t reserved : 16; + } bits; + uint32_t value; + } picture_flags; + + /** \brief Block size for each Segment ID in Segment Map. + * should be \c VA_SEGID_BLOCK_XXXX; + */ + uint8_t seg_id_block_size; + + /** \brief Number of tile groups minus 1. + * value range [0..255]. + */ + uint8_t num_tile_groups_minus1; + + /** \brief Temporal id of the frame.*/ + uint8_t temporal_id; + + /** \brief Deblock filter parameters. + * value range [0..63]. + */ + uint8_t filter_level[2]; + uint8_t filter_level_u; + uint8_t filter_level_v; + + union { + struct { + /** \brief Sharpness level for deblock filter. + * value range [0..7]. + */ + uint8_t sharpness_level : 3; + uint8_t mode_ref_delta_enabled : 1; + uint8_t mode_ref_delta_update : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint8_t reserved : 3; + } bits; + uint8_t value; + } loop_filter_flags; + + /** \brief Super resolution scale denominator. + * value range [9..16]. + */ + uint8_t superres_scale_denominator; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint8_t interpolation_filter; + + /** \brief Loop filter ref deltas. + * value range [-63..63]. + */ + int8_t ref_deltas[8]; + + /** \brief Loop filter mode deltas. + * value range [-63..63]. + */ + int8_t mode_deltas[2]; + + /** \brief Quantization params. */ + uint8_t base_qindex; + int8_t y_dc_delta_q; + int8_t u_dc_delta_q; + int8_t u_ac_delta_q; + int8_t v_dc_delta_q; + int8_t v_ac_delta_q; + + /** \brief Min value for base q index for BRC. + * value range [1..255]. + */ + uint8_t min_base_qindex; + + /** \brief Max value for base q index for BRC. + * value range [1..255]. + */ + uint8_t max_base_qindex; + + /** \brief Quantization matrix. */ + union { + struct { + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint16_t using_qmatrix : 1; + /** \brief Following parameters only valid when using_qmatrix == 1. */ + uint16_t qm_y : 4; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint16_t qm_u : 4; + /** \brief Corresponds to AV1 syntax element of the same name. */ + uint16_t qm_v : 4; + /** \brief Reserved bytes for future use, must be zero. */ + uint16_t reserved : 3; + } bits; + uint16_t value; + } qmatrix_flags; + + /** \brief Reserved bytes for future use, must be zero. */ + uint16_t reserved16bits1; + + union { + struct { + /** \brief Specify whether quantizer index delta values are present. + * value range [0..1]. */ + uint32_t delta_q_present : 1; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..3]. */ + uint32_t delta_q_res : 2; + + /** \brief Specify whether loop filter delta values are present. + * value range [0..1]. */ + uint32_t delta_lf_present : 1; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..3]. */ + uint32_t delta_lf_res : 2; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..1]. */ + uint32_t delta_lf_multi : 1; + + /** \brief Corresponds to AV1 syntax element of the same name. + * 0: ONLY_4X4; + * 1: TX_MODE_LARGEST; + * 2: TX_MODE_SELECT; + * 3: Invalid. + */ + uint32_t tx_mode : 2; + + /** \brief Indicates whether to use single or compound reference prediction. + * 0: SINGLE_REFERENCE; + * 1: COMPOUND_REFERENCE; + * 2: REFERENCE_MODE_SELECT. + * 3: Invalid. + * + * Value 2 means driver make decision to use single reference or compound reference. + */ + uint32_t reference_mode : 2; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..1]. + */ + uint32_t skip_mode_present : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t reserved : 20; + } bits; + uint32_t value; + } mode_control_flags; + + /** \brief Segmentation parameters. */ + VAEncSegParamAV1 segments; + + /** \brief Number of tile columns. */ + uint8_t tile_cols; + /** \brief Number of tile rows. */ + uint8_t tile_rows; + + /** \brief Reserved bytes for future use, must be zero. */ + uint16_t reserved16bits2; + + /** \brief The last tile column or row size needs to be derived. */ + uint16_t width_in_sbs_minus_1[63]; + uint16_t height_in_sbs_minus_1[63]; + + /** \brief specify which tile to use for the CDF update. + * value range [0..127]*/ + uint16_t context_update_tile_id; + + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..3]. + */ + uint8_t cdef_damping_minus_3; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..3]. + */ + uint8_t cdef_bits; + /** \brief CDEF Y strengths. + * value range [0..63]*/ + uint8_t cdef_y_strengths[8]; + /** \brief CDEF UV strengths. + * value range [0..63]*/ + uint8_t cdef_uv_strengths[8]; + + union { + struct { + /** \brief Restoration type for Y frame. + * value range [0..3]. + */ + uint16_t yframe_restoration_type : 2; + /** \brief Restoration type for Cb frame. + * value range [0..3]. + */ + uint16_t cbframe_restoration_type : 2; + /** \brief Restoration type for Cr frame. + * value range [0..3]. + */ + uint16_t crframe_restoration_type : 2; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..2]. + */ + uint16_t lr_unit_shift : 2; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..1]. + */ + uint16_t lr_uv_shift : 1; + /** \brief Reserved bytes for future use, must be zero. */ + uint16_t reserved : 7; + } bits; + uint16_t value; + } loop_restoration_flags; + + /** \brief Global motion. */ + VAEncWarpedMotionParamsAV1 wm[7]; + + /** + * Offset in bits for syntax base_q_idx in packed frame header bit stream + * from the start of the packed header data. + * In BRC mode, this parameter should be set and driver will update base_q_idx in + * uncompressed header according to this offset. + * In CQP mode, this parameter should be set to 0 and ignored by driver. + */ + uint32_t bit_offset_qindex; + /** + * Offset in bits for syntax segmentation_enabled of frame header OBU + * in packed frame header bit stream from the start of the packed header data. + * Valid only in auto segmentation mode. Other than that, this parameter + * should be set to 0 and ignored by driver. + */ + uint32_t bit_offset_segmentation; + /** + * Offset in bits for syntax loop_filter_params() in packed frame + * header bit stream from the start of the packed header data. + * In BRC mode, this parameter should be set and driver will update filter params + * in packed frame header according to this offset. + * In CQP mode, this parameter should be set to 0 and ignored by driver. + */ + uint32_t bit_offset_loopfilter_params; + /** + * In BRC mode, underline encoder should generate the approperiate + * CDEF values and write back into uncompressed header. And app + * should provide default CDEF values in packed header. This parameter + * should point to the starting bit of cdef_params() syntax structure + * in packed header. + * In CQP mode, this parameter should be set to 0 and ignored by driver. + */ + uint32_t bit_offset_cdef_params; + /** + * In BRC mode, this parameter indicates the actual bit usage of + * cdef_params() syntax structure in packed uncompressed header. + * In CQP mode, this parameter should be set to 0 and ignored by driver. + */ + uint32_t size_in_bits_cdef_params; + + /** + * Offset in bytes for syntax obu_size of frame header OBU in packed + * frame header bit stream from the start of the packed header. The frame + * header OBU size depends on the encoded tile sizes. It applies to both + * Frame Header OBU and Frame OBU if obu_size needs to be updated by + * underline encoder. Otherwise, app can set it to 0 and ignored by driver. + * + * In BRC mode, obu_size needs to be updated and this parameter should be set. + * In CQP mode, obu_size needs to be updated if \c enable_frame_obu == 1. Otherwise + * this parameter should be set to 0 and ignored by driver. + */ + uint32_t byte_offset_frame_hdr_obu_size; + + /** + * Frame header OBU bit stream size in bits. The frame header obu packed bit + * stream contains an obu header, a 4-byte long obu_size field, frame_header_obu() + * syntax chain, and a trailing bit if not inside a frame obu. If \c enable_frame_obu == 1, + * the value should include and up to the last bit of frame_header_obu() and + * excluding the bits generated by byte_alignment(). If \c enable_frame_obu == 0, + * the value should include and up to the trailing bit at the end of the frame + * header obu. The size will be used by encoder to calculate the final frame + * header size after bit shifting due to auto segmentation. + * In CQP mode, this parameter should be set to 0 and ignored by driver. + */ + uint32_t size_in_bits_frame_hdr_obu; + + /** \brief Tile Group OBU header */ + union { + struct { + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..1]. + */ + uint8_t obu_extension_flag : 1; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..1]. + */ + uint8_t obu_has_size_field : 1; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..7]. + */ + uint8_t temporal_id : 3; + /** \brief Corresponds to AV1 syntax element of the same name. + * value range [0..2]. + */ + uint8_t spatial_id : 2; + /** \brief Reserved bytes for future use, must be zero. */ + uint8_t reserved : 1; + } bits; + uint8_t value; + } tile_group_obu_hdr_info; + + /** \brief The number of frames skipped prior to the current frame. + * It includes only the skipped frames that were not counted before. + * App may generate the "show_existing_frame" short frame header OBUs + * and send to driver with the next frame. Default value 0. + */ + uint8_t number_skip_frames; + + /** \brief Reserved bytes for future use, must be zero. */ + uint16_t reserved16bits3; + + /** \brief Indicates the application forced frame size change in bytes. + * When the value is positive, the frame size is reduced. Otherwise, the frame + * size increases. The parameter can be used when application skips frames with + * setting of NumSkipFrames. And application can also use it for other scenarios + * such as inserting "show_existing_frame" at very end of the sequence. + */ + int32_t skip_frames_reduced_size; + + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t va_reserved[VA_PADDING_HIGH]; +} VAEncPictureParameterBufferAV1; + +/** + * \brief Tile Group Buffer. + */ +typedef struct _VAEncTileGroupBufferAV1 { + /** \brief Tile group start location. + * The position of the first tile in current tile group + * in raster scan order across the frame. + * value range [0..127]. + */ + uint8_t tg_start; + /** \brief Tile group end location. + * The position of the last tile in current tile group + * in raster scan order across the frame. + * value range [0..127]. + */ + uint8_t tg_end; + + /** \brief Reserved bytes for future use, must be zero. */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncTileGroupBufferAV1; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_AV1_H */ diff --git a/rs/moq-vaapi/libva/va/va_enc_h264.h b/rs/moq-vaapi/libva/va/va_enc_h264.h new file mode 100644 index 00000000000..46a6704ecef --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_h264.h @@ -0,0 +1,659 @@ +/* + * Copyright (c) 2007-2011 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_h264.h + * \brief The H.264 encoding API + * + * This file contains the \ref api_enc_h264 "H.264 encoding API". + */ + +#ifndef VA_ENC_H264_H +#define VA_ENC_H264_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_enc_h264 H.264 encoding API + * + * @{ + */ + +/** + * @name Picture flags + * + * Those flags flags are meant to signal when a picture marks the end + * of a sequence, a stream, or even both at once. + * + * @{ + */ +/** + * \brief Marks the last picture in the sequence. + * + * i.e. the driver appends \c end_of_seq() NAL unit to the encoded frame. + */ +#define H264_LAST_PICTURE_EOSEQ 0x01 +/** + * \brief Marks the last picture in the stream. + * + * i.e. the driver appends \c end_of_stream() NAL unit to the encoded frame. + */ +#define H264_LAST_PICTURE_EOSTREAM 0x02 +/**@}*/ + +/** + * \brief Packed header types specific to H.264 encoding. + * + * Types of packed headers generally used for H.264 encoding. Each + * associated packed header data buffer shall contain the start code + * prefix 0x000001 followed by the complete NAL unit, thus also + * including the \c nal_unit_type. + * + * Note: the start code prefix can contain an arbitrary number of leading + * zeros. The driver will skip them for emulation prevention bytes insertion, + * if necessary. + */ +typedef enum { + /** + * \brief Packed Sequence Parameter Set (SPS). + * + * The corresponding packed header data buffer shall contain the + * complete seq_parameter_set_rbsp() syntax element. + * + * Note: packed \c nal_unit_type shall be equal to 7. + */ + VAEncPackedHeaderH264_SPS = VAEncPackedHeaderSequence, + /** + * \brief Packed Picture Parameter Set (PPS). + * + * The corresponding packed header data buffer shall contain the + * complete pic_parameter_set_rbsp() syntax element. + * + * Note: packed \c nal_unit_type shall be equal to 8. + */ + VAEncPackedHeaderH264_PPS = VAEncPackedHeaderPicture, + /** + * \brief Packed slice header. + * + * The corresponding packed header data buffer shall contain the + * \c slice_header() syntax element only, along with any start + * code prefix and NAL unit type preceeding it. i.e. this means + * that the buffer does not contain any of the \c slice_data() or + * the \c rbsp_slice_trailing_bits(). + * + * Note: packed \c nal_unit_type shall be equal to 1 (non-IDR + * picture), or 5 (IDR picture). + */ + VAEncPackedHeaderH264_Slice = VAEncPackedHeaderSlice, + /** + * \brief Packed Supplemental Enhancement Information (SEI). + * + * The corresponding packed header data buffer shall contain the + * complete sei_rbsp() syntax element, thus including several + * sei_message() elements if necessary. + * + * Note: packed \c nal_unit_type shall be equal to 6. + * + * @deprecated + * This is a deprecated packed header flag, All applications can use + * \c VA_ENC_PACKED_HEADER_RAW_DATA to pass the corresponding packed + * SEI header data buffer to the driver + */ + VAEncPackedHeaderH264_SEI va_deprecated_enum = (0x80000000 | 1), +} VAEncPackedHeaderTypeH264; + +/** + * \brief Sequence parameter for H.264 encoding in baseline, main & high + * profiles. + * + * This structure holds information for \c seq_parameter_set_data() as + * defined by the H.264 specification. + * + * If packed sequence headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderSequence ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + * If \c seq_scaling_matrix_present_flag is set to \c 1, then a + * #VAIQMatrixBufferH264 buffer shall also be provided within the same + * \c vaRenderPicture() call as this sequence parameter buffer. + */ +typedef struct _VAEncSequenceParameterBufferH264 { + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t seq_parameter_set_id; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t level_idc; + /** \brief Period between I frames. */ + uint32_t intra_period; + /** \brief Period between IDR frames. */ + uint32_t intra_idr_period; + /** \brief Period between I/P frames. */ + uint32_t ip_period; + /** + * \brief Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for this + * sequence if CBR or VBR mode is used, i.e. if the encoder + * pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * The bitrate can be modified later on through + * #VAEncMiscParameterRateControl buffers. + */ + uint32_t bits_per_second; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t max_num_ref_frames; + /** \brief Picture width in macroblocks. */ + uint16_t picture_width_in_mbs; + /** \brief Picture height in macroblocks. */ + uint16_t picture_height_in_mbs; + + union { + struct { + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t chroma_format_idc : 2; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t frame_mbs_only_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t mb_adaptive_frame_field_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t seq_scaling_matrix_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t direct_8x8_inference_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t log2_max_frame_num_minus4 : 4; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t pic_order_cnt_type : 2; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t log2_max_pic_order_cnt_lsb_minus4 : 4; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t delta_pic_order_always_zero_flag : 1; + } bits; + uint32_t value; + } seq_fields; + + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t bit_depth_luma_minus8; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t bit_depth_chroma_minus8; + + /** if pic_order_cnt_type == 1 */ + /**@{*/ + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t num_ref_frames_in_pic_order_cnt_cycle; + /** \brief Same as the H.264 bitstream syntax element. */ + int32_t offset_for_non_ref_pic; + /** \brief Same as the H.264 bitstream syntax element. */ + int32_t offset_for_top_to_bottom_field; + /** \brief Same as the H.264 bitstream syntax element. */ + int32_t offset_for_ref_frame[256]; + /**@}*/ + + /** @name Cropping (optional) */ + /**@{*/ + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t frame_cropping_flag; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t frame_crop_left_offset; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t frame_crop_right_offset; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t frame_crop_top_offset; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t frame_crop_bottom_offset; + /**@}*/ + + /** @name VUI parameters (optional) */ + /**@{*/ + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t vui_parameters_present_flag; + union { + struct { + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t aspect_ratio_info_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t timing_info_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t bitstream_restriction_flag : 1; + /** \brief Range: 0 to 16, inclusive. */ + uint32_t log2_max_mv_length_horizontal : 5; + /** \brief Range: 0 to 16, inclusive. */ + uint32_t log2_max_mv_length_vertical : 5; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t fixed_frame_rate_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t low_delay_hrd_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t motion_vectors_over_pic_boundaries_flag: 1; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 16; + } bits; + uint32_t value; + } vui_fields; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t aspect_ratio_idc; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t sar_width; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t sar_height; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t num_units_in_tick; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t time_scale; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + /**@}*/ +} VAEncSequenceParameterBufferH264; + +/** + * \brief Picture parameter for H.264 encoding in baseline, main & high + * profiles. + * + * This structure holds information for \c pic_parameter_set_rbsp() as + * defined by the H.264 specification. + * + * If packed picture headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderPicture ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + * If \c pic_scaling_matrix_present_flag is set to \c 1, then a + * #VAIQMatrixBufferH264 buffer shall also be provided within the same + * \c vaRenderPicture() call as this picture parameter buffer. + */ +typedef struct _VAEncPictureParameterBufferH264 { + /** + * \brief Information about the picture to be encoded. + * + * See #VAPictureH264 for further description of each field. + * Note that CurrPic.picture_id represents the reconstructed + * (decoded) picture. User provides a scratch VA surface ID here. + */ + VAPictureH264 CurrPic; + /** + * \brief Decoded Picture Buffer (DPB). + * + * This array represents the list of reconstructed (decoded) + * frames used as reference. It is important to keep track of + * reconstructed frames so that they can be used later on as + * reference for P or B-frames encoding. + */ + VAPictureH264 ReferenceFrames[16]; + /** + * \brief Output encoded bitstream. + * + * \ref coded_buf has type #VAEncCodedBufferType. It should be + * large enough to hold the compressed NAL slice and possibly SPS + * and PPS NAL units. + */ + VABufferID coded_buf; + + /** \brief The picture parameter set referred to in the slice header. */ + uint8_t pic_parameter_set_id; + /** \brief The active sequence parameter set. Range: 0 to 31, inclusive. */ + uint8_t seq_parameter_set_id; + + /** + * \brief OR'd flags describing whether the picture is the last one or not. + * + * This fields holds 0 if the picture to be encoded is not the last + * one in the stream or sequence. Otherwise, it is a combination of + * \ref H264_LAST_PICTURE_EOSEQ or \ref H264_LAST_PICTURE_EOSTREAM. + */ + uint8_t last_picture; + + /** \brief The picture identifier. + * Range: 0 to \f$2^{log2\_max\_frame\_num\_minus4 + 4} - 1\f$, inclusive. + */ + uint16_t frame_num; + + /** \brief \c pic_init_qp_minus26 + 26. */ + uint8_t pic_init_qp; + /** \brief Maximum reference index for reference picture list 0. + * Range: 0 to 31, inclusive. + */ + uint8_t num_ref_idx_l0_active_minus1; + /** \brief Maximum reference index for reference picture list 1. + * Range: 0 to 31, inclusive. + */ + uint8_t num_ref_idx_l1_active_minus1; + + /** \brief Range: -12 to 12, inclusive. */ + int8_t chroma_qp_index_offset; + /** \brief Range: -12 to 12, inclusive. */ + int8_t second_chroma_qp_index_offset; + + union { + struct { + /** \brief Is picture an IDR picture? */ + uint32_t idr_pic_flag : 1; + /** \brief Is picture a reference picture? */ + uint32_t reference_pic_flag : 2; + /** \brief Selects CAVLC (0) or CABAC (1) entropy coding mode. */ + uint32_t entropy_coding_mode_flag : 1; + /** \brief Is weighted prediction applied to P slices? */ + uint32_t weighted_pred_flag : 1; + /** \brief Range: 0 to 2, inclusive. */ + uint32_t weighted_bipred_idc : 2; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t constrained_intra_pred_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t transform_8x8_mode_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t deblocking_filter_control_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t redundant_pic_cnt_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t pic_order_present_flag : 1; + /** \brief Same as the H.264 bitstream syntax element. */ + uint32_t pic_scaling_matrix_present_flag : 1; + } bits; + uint32_t value; + } pic_fields; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferH264; + +typedef struct _VAEncQPBufferH264 { + /* + * \brief This structure holds QP per 16x16 macroblock. Buffer size shall be + * sufficient to fit the slice or frame to be encoded depending on if it is a + * slice level or frame level encoding. + */ + uint8_t qp; +} VAEncQPBufferH264; + +/** + * \brief Slice parameter for H.264 encoding in baseline, main & high profiles. + * + * This structure holds information for \c + * slice_layer_without_partitioning_rbsp() as defined by the H.264 + * specification. + * + * If packed slice headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderSlice ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + * If per-macroblock encoder configuration is needed, \c macroblock_info + * references a buffer of type #VAEncMacroblockParameterBufferH264. This + * buffer is not passed to vaRenderPicture() and it can be re-used + * without re-allocating the whole buffer. + */ +typedef struct _VAEncSliceParameterBufferH264 { + /** \brief Starting MB address for this slice. */ + uint32_t macroblock_address; + /** \brief Number of macroblocks in this slice. */ + uint32_t num_macroblocks; + /** + * \brief Per-MB encoder configuration buffer, or \c VA_INVALID_ID. + * + * If per-MB encoder configuration is needed, then \ref macroblock_info + * references a buffer of type #VAEncMacroblockParameterBufferH264 + * (\c VAEncMacroblockParameterBufferType). Otherwise, buffer id + * is set to \c VA_INVALID_ID and per-MB configuration is derived + * from this slice parameter. + * + * The \c macroblock_info buffer must hold \ref num_macroblocks + * elements. + */ + VABufferID macroblock_info; + /** \brief Slice type. + * Range: 0..2, 5..7, i.e. no switching slices. + */ + uint8_t slice_type; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t pic_parameter_set_id; + /** \brief Same as the H.264 bitstream syntax element. */ + uint16_t idr_pic_id; + + /** @name If pic_order_cnt_type == 0 */ + /**@{*/ + /** \brief The picture order count modulo MaxPicOrderCntLsb. */ + uint16_t pic_order_cnt_lsb; + /** \brief Valid if \c pic_order_present_flag and this is a bottom field. */ + int32_t delta_pic_order_cnt_bottom; + /**@}*/ + /** @name If pic_order_cnt_type == 1 && !delta_pic_order_always_zero_flag */ + /**@{*/ + /** \brief [0]: top, [1]: bottom. */ + int32_t delta_pic_order_cnt[2]; + /**@}*/ + + /** @name If slice_type == B */ + /**@{*/ + uint8_t direct_spatial_mv_pred_flag; + /**@}*/ + + /** @name If slice_type == P */ + /**@{*/ + /** \brief Specifies if + * \ref _VAEncPictureParameterBufferH264::num_ref_idx_l0_active_minus1 or + * \ref _VAEncPictureParameterBufferH264::num_ref_idx_l1_active_minus1 are + * overriden by the values for this slice. + */ + uint8_t num_ref_idx_active_override_flag; + /** \brief Maximum reference index for reference picture list 0. + * Range: 0 to 31, inclusive. + */ + uint8_t num_ref_idx_l0_active_minus1; + /** \brief Maximum reference index for reference picture list 1. + * Range: 0 to 31, inclusive. + */ + uint8_t num_ref_idx_l1_active_minus1; + /** \brief Reference picture list 0 (for P slices). */ + VAPictureH264 RefPicList0[32]; + /** \brief Reference picture list 1 (for B slices). */ + VAPictureH264 RefPicList1[32]; + /**@}*/ + + /** @name pred_weight_table() */ + /**@{*/ + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t luma_log2_weight_denom; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t chroma_log2_weight_denom; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t luma_weight_l0_flag; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short luma_weight_l0[32]; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short luma_offset_l0[32]; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t chroma_weight_l0_flag; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short chroma_weight_l0[32][2]; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short chroma_offset_l0[32][2]; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t luma_weight_l1_flag; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short luma_weight_l1[32]; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short luma_offset_l1[32]; + /** \brief Same as the H.264 bitstream syntax element. */ + uint8_t chroma_weight_l1_flag; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short chroma_weight_l1[32][2]; + /** \brief Same as the H.264 bitstream syntax element. */ + signed short chroma_offset_l1[32][2]; + /**@}*/ + + /** \brief Range: 0 to 2, inclusive. */ + uint8_t cabac_init_idc; + /** \brief Same as the H.264 bitstream syntax element. */ + int8_t slice_qp_delta; + /** @name If deblocking_filter_control_present_flag */ + /**@{*/ + /** \brief Range: 0 to 2, inclusive. */ + uint8_t disable_deblocking_filter_idc; + /** \brief Same as the H.264 bitstream syntax element. */ + int8_t slice_alpha_c0_offset_div2; + /** \brief Same as the H.264 bitstream syntax element. */ + int8_t slice_beta_offset_div2; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; + /**@}*/ +} VAEncSliceParameterBufferH264; + +/** + * @name Macroblock neighbour availability bits + * + * \anchor api_enc_h264_mb_pred_avail_bits + * Definitions for macroblock neighbour availability bits used in + * intra prediction mode (non MBAFF only). + * + * @{ + */ +/** \brief References macroblock in the top-left corner. */ +#define VA_MB_PRED_AVAIL_TOP_LEFT (1 << 2) +/** \brief References macroblock above the current macroblock. */ +#define VA_MB_PRED_AVAIL_TOP (1 << 4) +/** \brief References macroblock in the top-right corner. */ +#define VA_MB_PRED_AVAIL_TOP_RIGHT (1 << 3) +/** \brief References macroblock on the left of the current macroblock. */ +#define VA_MB_PRED_AVAIL_LEFT (1 << 6) +/**@}*/ + +/** + * \brief Macroblock parameter for H.264 encoding in baseline, main & high + * profiles. + * + * This structure holds per-macroblock information. The buffer must be + * allocated with as many elements (macroblocks) as necessary to fit + * the slice to be encoded. Besides, the per-macroblock records must + * be written in a strict raster order and with no gap. i.e. every + * macroblock, regardless of its type, shall have an entry. + */ +typedef struct _VAEncMacroblockParameterBufferH264 { + /** + * \brief Quantization parameter. + * + * Requested quantization parameter. Range: 0 to 51, inclusive. + * If \ref qp is set to 0xff, then the actual value is derived + * from the slice-level value: \c pic_init_qp + \c slice_qp_delta. + */ + uint8_t qp; + + union { + /** @name Data for intra macroblock */ + /**@{*/ + union { + struct { + /** + * \brief Flag specified to override MB neighbour + * availability bits from VME stage. + * + * This flag specifies that macroblock neighbour + * availability bits from the VME stage are overriden + * by the \ref pred_avail_flags hereunder. + */ + uint32_t pred_avail_override_flag : 1; + /** + * \brief Bitwise representation of which macroblocks + * are available for intra prediction. + * + * If the slice is intra-coded, this field represents + * the macroblocks available for intra prediction. + * See \ref api_enc_h264_mb_pred_avail_bits + * "macroblock neighbour availability" bit definitions. + */ + uint32_t pred_avail_flags : 8; + } bits; + uint32_t value; + } intra_fields; + /**@}*/ + + /** @name Data for inter macroblock */ + /**@{*/ + union { + struct { + uint32_t reserved; + } bits; + uint32_t value; + } inter_fields; + /**@}*/ + } info; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMacroblockParameterBufferH264; + +/** + * \brief MB partition modes and 1/2 1/4 motion search configuration + * + * Specifies MB partition modes that are disabled. Specifies Half-pel + * mode and Quarter-pel mode searching + */ +typedef struct _VAEncMiscParameterSubMbPartPelH264 { + uint32_t disable_inter_sub_mb_partition; + union { + struct { + uint32_t disable_16x16_inter_mb_partition : 1; + uint32_t disable_16x8_inter_mb_partition : 1; + uint32_t disable_8x16_inter_mb_partition : 1; + uint32_t disable_8x8_inter_mb_partition : 1; + uint32_t disable_8x4_inter_mb_partition : 1; + uint32_t disable_4x8_inter_mb_partition : 1; + uint32_t disable_4x4_inter_mb_partition : 1; + uint32_t reserved : 1; + } bits; + uint8_t value; + } inter_sub_mb_partition_mask; + + /** + * \brief Precison of motion search + * 0:Integer mode searching + * 1:Half-pel mode searching + * 2:Reserved + * 3:Quarter-pel mode searching + */ + uint32_t enable_sub_pel_mode; + uint8_t sub_pel_mode; + uint8_t reserved[3]; +} VAEncMiscParameterSubMbPartPelH264; +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_H264_H */ diff --git a/rs/moq-vaapi/libva/va/va_enc_hevc.h b/rs/moq-vaapi/libva/va/va_enc_hevc.h new file mode 100644 index 00000000000..96b5ae568cd --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_hevc.h @@ -0,0 +1,958 @@ +/* + * Copyright (c) 2007-2014 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_hevc.h + * \brief The HEVC encoding API + * + * This file contains the \ref api_enc_hevc "HEVC encoding API". + * + */ + +#ifndef VA_ENC_HEVC_H +#define VA_ENC_HEVC_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * \defgroup api_enc_hevc HEVC encoding API + * + * @{ + */ + +/** Attribute value for VAConfigAttribEncHEVCFeatures. + * + * This attribute decribes the supported features of an HEVC/H.265 + * encoder configuration. + * + * All of the field values in this attribute are VA_FEATURE_* values, + * indicating support for the corresponding feature. + */ +typedef union VAConfigAttribValEncHEVCFeatures { + struct { + /** Separate colour planes. + * + * Allows setting separate_colour_plane_flag in the SPS. + */ + uint32_t separate_colour_planes : 2; + /** Scaling lists. + * + * Allows scaling_list() elements to be present in both the SPS + * and the PPS. The decoded form of the scaling lists must also + * be supplied in a VAQMatrixBufferHEVC buffer when scaling lists + * are enabled. + */ + uint32_t scaling_lists : 2; + /** Asymmetric motion partitions. + * + * Allows setting amp_enabled_flag in the SPS. + */ + uint32_t amp : 2; + /** Sample adaptive offset filter. + * + * Allows setting slice_sao_luma_flag and slice_sao_chroma_flag + * in slice headers. + */ + uint32_t sao : 2; + /** PCM sample blocks. + * + * Allows setting pcm_enabled_flag in the SPS. When enabled + * PCM parameters must be supplied with the sequence parameters, + * including block sizes which may be further constrained as + * noted in the VAConfigAttribEncHEVCBlockSizes attribute. + */ + uint32_t pcm : 2; + /** Temporal motion vector Prediction. + * + * Allows setting slice_temporal_mvp_enabled_flag in slice + * headers. + */ + uint32_t temporal_mvp : 2; + /** Strong intra smoothing. + * + * Allows setting strong_intra_smoothing_enabled_flag in the SPS. + */ + uint32_t strong_intra_smoothing : 2; + /** Dependent slices. + * + * Allows setting dependent_slice_segment_flag in slice headers. + */ + uint32_t dependent_slices : 2; + /** Sign data hiding. + * + * Allows setting sign_data_hiding_enable_flag in the PPS. + */ + uint32_t sign_data_hiding : 2; + /** Constrained intra prediction. + * + * Allows setting constrained_intra_pred_flag in the PPS. + */ + uint32_t constrained_intra_pred : 2; + /** Transform skipping. + * + * Allows setting transform_skip_enabled_flag in the PPS. + */ + uint32_t transform_skip : 2; + /** QP delta within coding units. + * + * Allows setting cu_qp_delta_enabled_flag in the PPS. + */ + uint32_t cu_qp_delta : 2; + /** Weighted prediction. + * + * Allows setting weighted_pred_flag and weighted_bipred_flag in + * the PPS. The pred_weight_table() data must be supplied with + * every slice header when weighted prediction is enabled. + */ + uint32_t weighted_prediction : 2; + /** Transform and quantisation bypass. + * + * Allows setting transquant_bypass_enabled_flag in the PPS. + */ + uint32_t transquant_bypass : 2; + /** Deblocking filter disable. + * + * Allows setting slice_deblocking_filter_disabled_flag. + */ + uint32_t deblocking_filter_disable : 2; + /* Reserved,should not be used, avoid conflict with VA_ATTRIB_NOT_SUPPORTED. */ + uint32_t reserved : 2; + } bits; + uint32_t value; +} VAConfigAttribValEncHEVCFeatures; + +/** Attribute value for VAConfigAttribEncHEVCBlockSizes. + * + * This attribute describes the supported coding tree and transform block + * sizes of an HEVC/H.265 encoder configuration + */ +typedef union VAConfigAttribValEncHEVCBlockSizes { + struct { + /** Largest supported size of coding tree blocks. + * + * CtbLog2SizeY must not be larger than this. + */ + uint32_t log2_max_coding_tree_block_size_minus3 : 2; + /** Smallest supported size of coding tree blocks. + * + * CtbLog2SizeY must not be smaller than this. + * + * This may be the same as the maximum size, indicating that only + * one CTB size is supported. + */ + uint32_t log2_min_coding_tree_block_size_minus3 : 2; + + /** Smallest supported size of luma coding blocks. + * + * MinCbLog2SizeY must not be smaller than this. + */ + uint32_t log2_min_luma_coding_block_size_minus3 : 2; + + /** Largest supported size of luma transform blocks. + * + * MaxTbLog2SizeY must not be larger than this. + */ + uint32_t log2_max_luma_transform_block_size_minus2 : 2; + /** Smallest supported size of luma transform blocks. + * + * MinTbLog2SizeY must not be smaller than this. + */ + uint32_t log2_min_luma_transform_block_size_minus2 : 2; + + /** Largest supported transform hierarchy depth in inter + * coding units. + * + * max_transform_hierarchy_depth_inter must not be larger + * than this. + */ + uint32_t max_max_transform_hierarchy_depth_inter : 2; + /** Smallest supported transform hierarchy depth in inter + * coding units. + * + * max_transform_hierarchy_depth_inter must not be smaller + * than this. + */ + uint32_t min_max_transform_hierarchy_depth_inter : 2; + + /** Largest supported transform hierarchy depth in intra + * coding units. + * + * max_transform_hierarchy_depth_intra must not be larger + * than this. + */ + uint32_t max_max_transform_hierarchy_depth_intra : 2; + /** Smallest supported transform hierarchy depth in intra + * coding units. + * + * max_transform_hierarchy_depth_intra must not be smaller + * than this. + */ + uint32_t min_max_transform_hierarchy_depth_intra : 2; + + /** Largest supported size of PCM coding blocks. + * + * Log2MaxIpcmCbSizeY must not be larger than this. + */ + uint32_t log2_max_pcm_coding_block_size_minus3 : 2; + /** Smallest supported size of PCM coding blocks. + * + * Log2MinIpcmCbSizeY must not be smaller than this. + */ + uint32_t log2_min_pcm_coding_block_size_minus3 : 2; + + /** Reserved for future use. */ + uint32_t reserved : 10; + } bits; + uint32_t value; +} VAConfigAttribValEncHEVCBlockSizes; + +/** + * @name Picture flags + * + * Those flags flags are meant to signal when a picture marks the end + * of a sequence, a stream, or even both at once. + * + * @{ + */ +/** + * \brief Marks the last picture in the sequence. + * + * i.e. the driver appends \c end_of_seq() NAL unit to the encoded frame. + */ +#define HEVC_LAST_PICTURE_EOSEQ 0x01 +/** + * \brief Marks the last picture in the stream. + * + * i.e. the driver appends \c end_of_stream() NAL unit to the encoded frame. + */ +#define HEVC_LAST_PICTURE_EOSTREAM 0x02 +/**@}*/ + +/** + * \brief Packed header types specific to HEVC encoding. + * + * Types of packed headers generally used for HEVC encoding. Each + * associated packed header data buffer shall contain the start code + * prefix 0x000001 followed by the complete NAL unit, thus also + * including the \c nal_unit_type. + * + * Note: the start code prefix can contain an arbitrary number of leading + * zeros. The driver will skip them for emulation prevention bytes insertion, + * if necessary. + */ +typedef enum { + /** + * \brief Packed Video Parameter Set (VPS). + * + * The corresponding packed header data buffer shall contain the + * complete video_parameter_set_rbsp() syntax element. + * + * Note: packed \c nal_unit_type shall be equal to 32. + */ + VAEncPackedHeaderHEVC_VPS = VAEncPackedHeaderSequence, + /** + * \brief Packed Sequence Parameter Set (SPS). + * + * The corresponding packed header data buffer shall contain the + * complete seq_parameter_set_rbsp() syntax element. + * + * Note: packed \c nal_unit_type shall be equal to 33. + */ + VAEncPackedHeaderHEVC_SPS = VAEncPackedHeaderSequence, + /** + * \brief Packed Picture Parameter Set (PPS). + * + * The corresponding packed header data buffer shall contain the + * complete pic_parameter_set_rbsp() syntax element. + * + * Note: packed \c nal_unit_type shall be equal to 34. + */ + VAEncPackedHeaderHEVC_PPS = VAEncPackedHeaderPicture, + /** + * \brief Packed slice header. + * + * The corresponding packed header data buffer shall contain the + * \c slice_header() syntax element only, along with any start + * code prefix and NAL unit type preceeding it. i.e. this means + * that the buffer does not contain any of the \c slice_data() or + * the \c rbsp_slice_trailing_bits(). + * + * Note: packed \c nal_unit_type shall be equal to 0 to 9 (non-IRAP + * picture), or 16 to 21 (IRAP picture). + */ + VAEncPackedHeaderHEVC_Slice = VAEncPackedHeaderSlice, + /** + * \brief Packed Supplemental Enhancement Information (SEI). + * + * The corresponding packed header data buffer shall contain the + * complete sei_rbsp() syntax element, thus including several + * sei_message() elements if necessary. + * + * Note: packed \c nal_unit_type shall be equal to 39 or 40. + * + * @deprecated + * This is a deprecated packed header flag, All applications can use + * \c VA_ENC_PACKED_HEADER_RAW_DATA to pass the corresponding packed + * SEI header data buffer to the driver + */ + VAEncPackedHeaderHEVC_SEI va_deprecated_enum = (0x80000000 | 1), +} VAEncPackedHeaderTypeHEVC; + +/** + * \brief Sequence parameter for HEVC encoding in main & main 10 + * profiles. + * + * This structure holds information for \c seq_parameter_set_data() as + * defined by the HEVC specification. + * + * If packed sequence headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderSequence ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + * If \c seq_scaling_matrix_present_flag is set to \c 1, then a + * #VAQMatrixBufferHEVC buffer shall also be provided within the same + * \c vaRenderPicture() call as this sequence parameter buffer. + */ +typedef struct _VAEncSequenceParameterBufferHEVC { + /** \brief Same as the HEVC bitstream syntax element. + * value range [1..2]. + */ + uint8_t general_profile_idc; + /** \brief Same as the HEVC bitstream syntax element. + * general_level_idc shall be set equal to a value of 30 times the level + * numbers allowed [1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2] + */ + uint8_t general_level_idc; + /** \brief Same as the HEVC bitstream syntax element. + * Only value 0 is allowed for level value below 4, exclusive. + */ + uint8_t general_tier_flag; + /** \brief Period between I frames. */ + uint32_t intra_period; + /** \brief Period between IDR frames. */ + uint32_t intra_idr_period; + /** \brief Period between I/P frames. */ + uint32_t ip_period; + /** + * \brief Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for this + * sequence if CBR or VBR mode is used, i.e. if the encoder + * pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * The bitrate can be modified later on through + * #VAEncMiscParameterRateControl buffers. + */ + uint32_t bits_per_second; + /** \brief Picture width in pixel samples. + * Its value must be multiple of min CU size. + */ + uint16_t pic_width_in_luma_samples; + /** \brief Picture height in pixel samples. + * Its value must be multiple of min CU size. + */ + uint16_t pic_height_in_luma_samples; + + union { + struct { + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t chroma_format_idc : 2; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t separate_colour_plane_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t bit_depth_luma_minus8 : 3; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t bit_depth_chroma_minus8 : 3; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t scaling_list_enabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t strong_intra_smoothing_enabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t amp_enabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t sample_adaptive_offset_enabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t pcm_enabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t pcm_loop_filter_disabled_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t sps_temporal_mvp_enabled_flag : 1; + /** \brief Indicates whether or not the encoding is in low delay mode. + * 0 normal sequence + * 1 no random access B will be coded . and the coding type could be only I, P or LDB + * this flag only indicates the frame coding type of the sequence. + */ + uint32_t low_delay_seq : 1; + /** \brief Indicates whether or not the encoding is in dyadic hierarchical GOP structure + * the default value 0, BRC would treat is as flat structure. if HierachicalFlag == 1, + * application would enable Qp Modulation + */ + uint32_t hierachical_flag : 1; + /** \brief keep for future , should be set to 0 */ + uint32_t reserved_bits : 14; + } bits; + uint32_t value; + } seq_fields; + + /** \brief Same as the HEVC bitstream syntax element. + * value range [0..3] + */ + uint8_t log2_min_luma_coding_block_size_minus3; + + /** \brief Same as the HEVC bitstream syntax element. + */ + uint8_t log2_diff_max_min_luma_coding_block_size; + + /** \brief Same as the HEVC bitstream syntax element. + * value range [0..3] + */ + uint8_t log2_min_transform_block_size_minus2; + + /** \brief Same as the HEVC bitstream syntax element. + */ + uint8_t log2_diff_max_min_transform_block_size; + + /** \brief Same as the HEVC bitstream syntax element. + * value range [2] + */ + uint8_t max_transform_hierarchy_depth_inter; + + /** \brief Same as the HEVC bitstream syntax element. + * value range [2] + */ + uint8_t max_transform_hierarchy_depth_intra; + + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t pcm_sample_bit_depth_luma_minus1; + + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t pcm_sample_bit_depth_chroma_minus1; + + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t log2_min_pcm_luma_coding_block_size_minus3; + + /** \brief Derived from the HEVC bitstream syntax element. + * log2_min_pcm_luma_coding_block_size_minus3 + + * log2_diff_max_min_pcm_luma_coding_block_size + */ + uint32_t log2_max_pcm_luma_coding_block_size_minus3; + + /** @name VUI parameters (optional) */ + /**@{*/ + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t vui_parameters_present_flag; + union { + struct { + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t aspect_ratio_info_present_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t neutral_chroma_indication_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t field_seq_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t vui_timing_info_present_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t bitstream_restriction_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t tiles_fixed_structure_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t motion_vectors_over_pic_boundaries_flag : 1; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t restricted_ref_pic_lists_flag : 1; + /** \brief Range: 0 to 16, inclusive. */ + uint32_t log2_max_mv_length_horizontal : 5; + /** \brief Range: 0 to 16, inclusive. */ + uint32_t log2_max_mv_length_vertical : 5; + } bits; + uint32_t value; + } vui_fields; + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t aspect_ratio_idc; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t sar_width; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t sar_height; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t vui_num_units_in_tick; + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t vui_time_scale; + /** \brief Same as the HEVC bitstream syntax element. */ + uint16_t min_spatial_segmentation_idc; + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t max_bytes_per_pic_denom; + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t max_bits_per_min_cu_denom; + + /** \brief SCC flags to enable/disable features, including IBC and palette mode at present.*/ + union { + struct { + /** \brief Same as the HEVC bitstream syntax element. */ + uint32_t palette_mode_enabled_flag : 1; + /** \brief Reserved bits for future use, must be zero */ + uint32_t reserved : 31; + } bits; + uint32_t value; + } scc_fields; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM - 1]; + /**@}*/ +} VAEncSequenceParameterBufferHEVC; + +/**************************** + * HEVC data structures + ****************************/ +/** + * \brief Picture parameter for HEVC encoding in main & main 10 + * profiles. + * + * This structure holds information for \c pic_parameter_set_rbsp() as + * defined by the HEVC specification. + * + * If packed picture headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderPicture ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + * If \c pic_scaling_matrix_present_flag is set to \c 1, then a + * #VAQMatrixBufferHEVC buffer shall also be provided within the same + * \c vaRenderPicture() call as this picture parameter buffer. + */ +typedef struct _VAEncPictureParameterBufferHEVC { + /** + * \brief Information about the picture to be encoded. + * + * See #VAPictureHEVC for further description of each field. + * Note that decoded_curr_pic.picture_id represents the reconstructed + * (decoded) picture. User provides a scratch VA surface ID here. + * Long term reference and RPS related fields should be set to 0 + * and ignored. + */ + VAPictureHEVC decoded_curr_pic; + /** + * \brief Decoded Picture Buffer (DPB). + * + * This array represents the list of reconstructed (decoded) + * frames used as reference. It is important to keep track of + * reconstructed frames so that they can be used later on as + * reference for P or B-frames encoding. + */ + VAPictureHEVC reference_frames[15]; + /** + * \brief Output encoded bitstream. + * + * \ref coded_buf has type #VAEncCodedBufferType. It should be + * large enough to hold the compressed NAL slice and possibly VPS, SPS + * and PPS NAL units, and other NAL units such as SEI. + */ + VABufferID coded_buf; + + /** \brief collocated reference picture buffer index of ReferenceFrames[]. + * Please note it is different from HEVC syntac element collocated_ref_idx. + * When the HEVC syntax element slice_temporal_mvp_enable_flag takes value 0, + * collocated_ref_pic_index should take value 0xFF. . + * Range: [0..14, 0xFF] + */ + uint8_t collocated_ref_pic_index; + + /** + * \brief OR'd flags describing whether the picture is the last one or not. + * + * This fields holds 0 if the picture to be encoded is not the last + * one in the stream or sequence. Otherwise, it is a combination of + * \ref HEVC_LAST_PICTURE_EOSEQ or \ref HEVC_LAST_PICTURE_EOSTREAM. + */ + uint8_t last_picture; + + /** \brief \c init_qp_minus26 + 26. */ + uint8_t pic_init_qp; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t diff_cu_qp_delta_depth; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + int8_t pps_cb_qp_offset; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + int8_t pps_cr_qp_offset; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t num_tile_columns_minus1; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t num_tile_rows_minus1; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t column_width_minus1[19]; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t row_height_minus1[21]; + + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint8_t log2_parallel_merge_level_minus2; + + /** \brief Application may set the CTU bit size limit based on + * spec requirement (A.3.2), or other value for special purpose. + * If the value is set 0, no bit size limit is checked. + */ + uint8_t ctu_max_bitsize_allowed; + + /** \brief Maximum reference index for reference picture list 0. + * value range: [0..14]. + */ + uint8_t num_ref_idx_l0_default_active_minus1; + + /** \brief Maximum reference index for reference picture list 1. + * value range: [0..14]. + */ + uint8_t num_ref_idx_l1_default_active_minus1; + + /** \brief PPS header + * Used by GPU to generate new slice headers in slice size control. + * value range: [0..63]. + */ + uint8_t slice_pic_parameter_set_id; + + /** \brief NAL unit type + * Used by GPU to generate new slice headers in slice size control. + * value range: [0..63]. + */ + uint8_t nal_unit_type; + + union { + struct { + /** \brief Is picture an IDR picture? */ + uint32_t idr_pic_flag : 1; + /** \brief Picture type. + * I - 1; + * P - 2; + * B - 3; + * B1 - 4; + * B2 - 5; + * B1 and B2 are frame types for hierachical B, explanation + * can refer to num_b_in_gop[]. + */ + uint32_t coding_type : 3; + /** \brief Is picture a reference picture? */ + uint32_t reference_pic_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t dependent_slice_segments_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t sign_data_hiding_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t constrained_intra_pred_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t transform_skip_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t cu_qp_delta_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t weighted_pred_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t weighted_bipred_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t transquant_bypass_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t tiles_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t entropy_coding_sync_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t loop_filter_across_tiles_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t pps_loop_filter_across_slices_enabled_flag : 1; + /** \brief A combination of HEVC syntax element of + * sps_scaling_list_data_present_flag and + * pps_scaling_list_data_present_flag + * when scaling_list_enable_flag is 0, it must be 0. + */ + uint32_t scaling_list_data_present_flag : 1; + /** \brief indicate the current picture contains significant + * screen contents (text, characters, etc.) or animated image. + * GPU may want to treat them differently from normal video. + * For example, encoder may choose a small transform unit size + * and may use transform skip mode. + */ + uint32_t screen_content_flag : 1; + /** + * When either weighted_pred_flag or weighted_bipred_flag is + * turned on, the flag enable_gpu_weighted_prediction requests + * GPU to determine weighted prediction factors. In this case, + * the following parameters in slice control data structure + * shall be ignored: + * luma_log2_weight_denom, delta_chroma_log2_weight_denom, + * luma_offset_l0[15], luma_offset_l1[15], + * delta_luma_weight_l0[15], delta_luma_weight_l1[15], + * chroma_offset_l0[15][2], chroma_offset_l1[15][2], + * and delta_chroma_weight_l0[15][2], delta_chroma_weight_l1[15][2]. + */ + uint32_t enable_gpu_weighted_prediction : 1; + /** \brief HEVC syntax element in slice segment header + * GPU uses it to generate new slice headers in slice size control. + */ + uint32_t no_output_of_prior_pics_flag : 1; + uint32_t reserved : 11; + } bits; + uint32_t value; + } pic_fields; + + /** \brief When hierachical_level_plus1 > 0, hierachical_level_plus1-1 indicates + *the current frame's level.when it > 0. B1, B2 setting in CodingType can be treated as B, + *hirachical level is determined by this variable.When hierachical_level_plus1 == 0, + *hierarchical level information still comes from coding_type. + */ + uint8_t hierarchical_level_plus1; + /** \brief Reserved bytes for future use, must be zero */ + uint8_t va_byte_reserved; + /** \brief SCC flags to enable/disable feature, only IBC at present.*/ + union { + struct { + /** \brief Same as the HEVC bitstream syntax element. */ + uint16_t pps_curr_pic_ref_enabled_flag : 1; + /** \brief Reserved bits for future use, must be zero */ + uint16_t reserved : 15; + } bits; + uint16_t value; + } scc_fields; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_HIGH - 1]; +} VAEncPictureParameterBufferHEVC; + +/** + * \brief Slice parameter for HEVC encoding in main & main 10 profiles. + * + * This structure holds information for \c + * slice_segment_layer_rbsp() as defined by the HEVC + * specification. + * + * If packed slice headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderSlice ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + */ +typedef struct _VAEncSliceParameterBufferHEVC { + /** \brief Starting CTU address for this slice. */ + uint32_t slice_segment_address; + /** \brief Number of CTUs in this slice. */ + uint32_t num_ctu_in_slice; + + /** \brief Slice type. + * Corresponds to HEVC syntax element of the same name. + */ + uint8_t slice_type; + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t slice_pic_parameter_set_id; + + /** \brief Maximum reference index for reference picture list 0. + * Range: 0 to 14, inclusive. + */ + uint8_t num_ref_idx_l0_active_minus1; + /** \brief Maximum reference index for reference picture list 1. + * Range: 0 to 14, inclusive. + */ + uint8_t num_ref_idx_l1_active_minus1; + /** \brief Reference picture list 0 (for P slices). */ + VAPictureHEVC ref_pic_list0[15]; + /** \brief Reference picture list 1 (for B slices). */ + VAPictureHEVC ref_pic_list1[15]; + /**@}*/ + + /** @name pred_weight_table() */ + /**@{*/ + /** \brief Same as the HEVC bitstream syntax element. */ + uint8_t luma_log2_weight_denom; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t delta_chroma_log2_weight_denom; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t delta_luma_weight_l0[15]; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t luma_offset_l0[15]; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t delta_chroma_weight_l0[15][2]; + /** \brief Same as the HEVC spec variable ChromaOffsetL0[]. */ + int8_t chroma_offset_l0[15][2]; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t delta_luma_weight_l1[15]; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t luma_offset_l1[15]; + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t delta_chroma_weight_l1[15][2]; + /** \brief Same as the HEVC spec variable ChromaOffsetL1[]. */ + int8_t chroma_offset_l1[15][2]; + /**@}*/ + + /** \brief Corresponds to HEVC spec variable MaxNumMergeCand. + * Range: [1..5]. + */ + uint8_t max_num_merge_cand; + + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t slice_qp_delta; + + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t slice_cb_qp_offset; + + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t slice_cr_qp_offset; + + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t slice_beta_offset_div2; + + /** \brief Same as the HEVC bitstream syntax element. */ + int8_t slice_tc_offset_div2; + + union { + struct { + /** \brief Indicates if current slice is the last one in picture */ + uint32_t last_slice_of_pic_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name */ + uint32_t dependent_slice_segment_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name */ + uint32_t colour_plane_id : 2; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t slice_temporal_mvp_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t slice_sao_luma_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t slice_sao_chroma_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. + * if this flag is set to 0, num_ref_idx_l0_active_minus1 should be + * equal to num_ref_idx_l0_default_active_minus1 + * as well as for that for l1. + */ + uint32_t num_ref_idx_active_override_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t mvd_l1_zero_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t cabac_init_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t slice_deblocking_filter_disabled_flag : 2; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t slice_loop_filter_across_slices_enabled_flag : 1; + /** \brief Corresponds to HEVC syntax element of the same name. */ + uint32_t collocated_from_l0_flag : 1; + } bits; + uint32_t value; + } slice_fields; + + + /** + * \brief bit offset of syntax element pred_weight_table() in slice segment header. + * It aligns with the starting position of the current packed slice header. + * It is used when encoder prefers to override the weighted prediction parameters passed in + * from application. + * Please refer to enable_gpu_weighted_prediction in VAEncPictureParameterBufferHEVC. + */ + uint32_t pred_weight_table_bit_offset; + /** + * \brief bit length of syntax element pred_weight_table() in slice segment header. + * It is used when encoder prefers to override the weighted prediction parameters passed in + * from application. + * Please refer to enable_gpu_weighted_prediction in VAEncPictureParameterBufferHEVC. + */ + uint32_t pred_weight_table_bit_length; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM - 2]; + /**@}*/ +} VAEncSliceParameterBufferHEVC; + +/** + * \brief HEVC Quantization Matrix Buffer Structure + * + * This structure is sent once per frame, + * and only when scaling_list_enabled_flag = 1 and scaling_list_data_present_flag = 1. + * Only when scaling_list_data_present_flag = 1, app still + * needs to send in this structure. When scaling_list_enabled_flag = 1 and + * scaling_list_data_present_flag = 0, driver is responsible to generate + * the default scaling list values. + * + * Matrix entries are in raster scan order which follows HEVC spec. + */ +typedef struct _VAQMatrixBufferHEVC { + /** + * \brief scaling lists, + * corresponds to same HEVC spec syntax element + * ScalingList[ i ][ MatrixID ][ j ]. + * + * \brief 4x4 scaling, + */ + uint8_t scaling_lists_4x4[3][2][16]; + /** + * \brief 8x8 scaling, + */ + uint8_t scaling_lists_8x8[3][2][64]; + /** + * \brief 16x16 scaling, + * correspongs i = 2, MatrixID is in the range of 0 to 5, + * inclusive. And j is in the range of 0 to 63, inclusive. + */ + uint8_t scaling_lists_16x16[3][2][64]; + /** + * \brief 32x32 scaling, + * correspongs i = 3, MatrixID is in the range of 0 to 1, + * inclusive. And j is in the range of 0 to 63, inclusive. + */ + uint8_t scaling_lists_32x32[2][64]; + /** + * \brief DC values of the 16x16 scaling lists, + * corresponds to HEVC spec syntax + * scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8 + * with sizeID = 2 and matrixID in the range of 0 to 5, inclusive. + */ + uint8_t scaling_list_dc_16x16[3][2]; + /** + * \brief DC values of the 32x32 scaling lists, + * corresponds to HEVC spec syntax + * scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8 + * with sizeID = 3 and matrixID in the range of 0 to 1, inclusive. + */ + uint8_t scaling_list_dc_32x32[2]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAQMatrixBufferHEVC; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_HEVC_H */ diff --git a/rs/moq-vaapi/libva/va/va_enc_jpeg.h b/rs/moq-vaapi/libva/va/va_enc_jpeg.h new file mode 100644 index 00000000000..ec02191cea2 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_jpeg.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2007-2013 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_jpeg.h + * \brief JPEG encoding API + * + * This file contains the \ref api_enc_jpeg "JPEG encoding API". + */ + +#ifndef VA_ENC_JPEG_H +#define VA_ENC_JPEG_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_enc_jpeg JPEG encoding API + * + * @{ + */ + +/** + * \brief JPEG Encoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters. + * + */ +typedef struct _VAEncPictureParameterBufferJPEG { + /** \brief holds reconstructed picture. */ + VASurfaceID reconstructed_picture; + /** \brief picture width. */ + uint16_t picture_width; + /** \brief picture height. */ + uint16_t picture_height; + /** \brief holds coded data. */ + VABufferID coded_buf; + + /** + * \brief pic_flags + * + */ + union { + struct { + /** + * \brief profile: + * 0 - Baseline, 1 - Extended, 2 - Lossless, 3 - Hierarchical + */ + uint32_t profile : 2; + /** + * \brief progressive: + * 0 - sequential, 1 - extended, 2 - progressive + */ + uint32_t progressive : 1; + /** + * \brief huffman: + * 0 - arithmetic, 1 - huffman + */ + uint32_t huffman : 1; + /** + * \brief interleaved: + * 0 - non interleaved, 1 - interleaved + */ + uint32_t interleaved : 1; + /** + * \brief differential: + * 0 - non differential, 1 - differential + */ + uint32_t differential : 1; + } bits; + uint32_t value; + } pic_flags; + + /** \brief number of bits per sample. */ + uint8_t sample_bit_depth; + /** \brief total number of scans in image. */ + uint8_t num_scan; + /** \brief number of image components in frame. */ + uint16_t num_components; + /** \brief Component identifier (Ci). */ + uint8_t component_id[4]; + /** \brief Quantization table selector (Tqi). */ + uint8_t quantiser_table_selector[4]; + /** \brief number from 1 to 100 that specifies quality of image. */ + uint8_t quality; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferJPEG; + + +/** + * \brief Slice parameter for JPEG encoding. + * + * This structure conveys slice (scan) level parameters. + * + */ +typedef struct _VAEncSliceParameterBufferJPEG { + /** \brief Restart interval definition (Ri). */ + uint16_t restart_interval; + /** \brief number of image components in a scan. */ + uint16_t num_components; + struct { + /** \brief Scan component selector (Csj). */ + uint8_t component_selector; + /** \brief DC entropy coding table selector (Tdj). */ + uint8_t dc_table_selector; + /** \brief AC entropy coding table selector (Taj). */ + uint8_t ac_table_selector; + } components[4]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSliceParameterBufferJPEG; + +/** + * \brief Quantization table for JPEG encoding. + * + */ +typedef struct _VAQMatrixBufferJPEG { + /** \brief load luma quantization table. */ + int32_t load_lum_quantiser_matrix; + /** \brief load chroma quantization table. */ + int32_t load_chroma_quantiser_matrix; + /** \brief luma quantization table. */ + uint8_t lum_quantiser_matrix[64]; + /** \brief chroma quantization table. */ + uint8_t chroma_quantiser_matrix[64]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAQMatrixBufferJPEG; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_JPEG_H */ diff --git a/rs/moq-vaapi/libva/va/va_enc_mpeg2.h b/rs/moq-vaapi/libva/va/va_enc_mpeg2.h new file mode 100644 index 00000000000..669df0323ca --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_mpeg2.h @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_mpeg2.h + * \brief The MPEG-2 encoding API + * + * This file contains the \ref api_enc_mpeg2 "MPEG-2 encoding API". + */ + +#ifndef _VA_ENC_MPEG2_H_ +#define _VA_ENC_MPEG2_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_enc_mpeg2 MPEG-2 encoding API + * + * @{ + */ + +/** + * \brief MPEG-2 Quantization Matrix Buffer + * + */ +typedef VAIQMatrixBufferMPEG2 VAQMatrixBufferMPEG2; + +/** + * \brief Packed header types specific to MPEG-2 encoding. + * + * Types of packed headers generally used for MPEG-2 encoding. + */ +typedef enum { + /** + * \brief Packed Sequence Parameter Set (SPS). + * + */ + VAEncPackedHeaderMPEG2_SPS = VAEncPackedHeaderSequence, + /** + * \brief Packed Picture Parameter Set (PPS). + * + */ + VAEncPackedHeaderMPEG2_PPS = VAEncPackedHeaderPicture, + /** + * \brief Packed slice header. + * + */ + VAEncPackedHeaderMPEG2_Slice = VAEncPackedHeaderSlice, +} VAEncPackedHeaderTypeMPEG2; + +/** + * \brief Sequence parameter for MPEG-2 encoding + * + * This structure holds information for \c sequence_header() and + * sequence_extension(). + * + * If packed sequence headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderSequence ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + */ +typedef struct _VAEncSequenceParameterBufferMPEG2 { + /** \brief Period between I frames. */ + uint32_t intra_period; + /** \brief Period between I/P frames. */ + uint32_t ip_period; + /** \brief Picture width. + * + * A 14bits unsigned inter, the lower 12bits + * is horizontal_size_value, and the upper + * 2bits is \c horizontal_size_extension + * + */ + uint16_t picture_width; + /** \brief Picture height. + * + * A 14bits unsigned inter, the lower 12bits + * is vertical_size_value, and the upper 2bits is + * vertical_size_size_extension + * + */ + uint16_t picture_height; + /** + * \brief Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for this + * sequence if CBR or VBR mode is used, i.e. if the encoder + * pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * bits_per_second may be derived from bit_rate. + * + */ + uint32_t bits_per_second; + /** + * \brief Frame rate + * + * Derived from frame_rate_value, frame_rate_extension_n and + * frame_rate_extension_d + * + */ + float frame_rate; + /** \brief Same as the element in sequence_header() */ + uint16_t aspect_ratio_information; + /** \brief Define the size of VBV */ + uint32_t vbv_buffer_size; + + union { + struct { + /** \brief Same as the element in Sequence extension() */ + uint32_t profile_and_level_indication : 8; + /** \brief Same as the element in Sequence extension() */ + uint32_t progressive_sequence : 1; + /** \brief Same as the element in Sequence extension() */ + uint32_t chroma_format : 2; + /** \brief Same as the element in Sequence extension() */ + uint32_t low_delay : 1; + /** \brief Same as the element in Sequence extension() */ + uint32_t frame_rate_extension_n : 2; + /** \brief Same as the element in Sequence extension() */ + uint32_t frame_rate_extension_d : 5; + } bits; + uint32_t value; + } sequence_extension; + + /** \brief Flag to indicate the following GOP header are being updated */ + uint32_t new_gop_header; + + union { + struct { + /** \brief Time code */ + uint32_t time_code : 25; + /** \brief Same as the element in GOP header */ + uint32_t closed_gop : 1; + /** \brief SAme as the element in GOP header */ + uint32_t broken_link : 1; + } bits; + uint32_t value; + } gop_header; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSequenceParameterBufferMPEG2; + +/** + * \brief Picture parameter for MPEG-2 encoding + * + * This structure holds information for picture_header() and + * picture_coding_extension() + * + * If packed picture headers mode is used, i.e. if the encoding + * pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE + * flag, then the driver expects two more buffers to be provided to + * the same \c vaRenderPicture() as this buffer: + * - a #VAEncPackedHeaderParameterBuffer with type set to + * VAEncPackedHeaderType::VAEncPackedHeaderPicture ; + * - a #VAEncPackedHeaderDataBuffer which holds the actual packed + * header data. + * + */ +typedef struct _VAEncPictureParameterBufferMPEG2 { + /** \brief Forward reference picture */ + VASurfaceID forward_reference_picture; + /** \brief Backward reference picture */ + VASurfaceID backward_reference_picture; + /** \brief Reconstructed(decoded) picture */ + VASurfaceID reconstructed_picture; + /** + * \brief Output encoded bitstream. + * + * \ref coded_buf has type #VAEncCodedBufferType. It should be + * large enough to hold the compressed NAL slice and possibly SPS + * and PPS NAL units. + */ + VABufferID coded_buf; + /** + * \brief Flag to indicate the picture is the last one or not. + * + * This fields holds 0 if the picture to be encoded is not + * the last one in the stream. Otherwise, it + * is \ref MPEG2_LAST_PICTURE_EOSTREAM. + */ + uint8_t last_picture; + /** \brief Picture type */ + VAEncPictureType picture_type; + /** \brief Same as the element in picture_header() */ + uint32_t temporal_reference; + /** \brief Same as the element in picture_header() */ + uint32_t vbv_delay; + /** \brief Same as the element in Picture coding extension */ + uint8_t f_code[2][2]; + union { + struct { + /** \brief Same as the element in Picture coding extension */ + uint32_t intra_dc_precision : 2; + /** \brief Same as the element in Picture coding extension */ + uint32_t picture_structure : 2; + /** \brief Same as the element in Picture coding extension */ + uint32_t top_field_first : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t frame_pred_frame_dct : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t concealment_motion_vectors : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t q_scale_type : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t intra_vlc_format : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t alternate_scan : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t repeat_first_field : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t progressive_frame : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t composite_display_flag : 1; + } bits; + uint32_t value; + } picture_coding_extension; + + /* \brief Parameters for composite display + * + * Valid only when omposite_display_flag is 1 + */ + union { + struct { + /** \brief Same as the element in Picture coding extension */ + uint32_t v_axis : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t field_sequence : 3; + /** \brief Same as the element in Picture coding extension */ + uint32_t sub_carrier : 1; + /** \brief Same as the element in Picture coding extension */ + uint32_t burst_amplitude : 7; + /** \brief Same as the element in Picture coding extension */ + uint32_t sub_carrier_phase : 8; + } bits; + uint32_t value; + } composite_display; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferMPEG2; + +/** + * \brief Slice parameter for MPEG-2 encoding + * + */ +typedef struct _VAEncSliceParameterBufferMPEG2 { + /** \brief Starting MB address for this slice. */ + uint32_t macroblock_address; + /** \brief Number of macroblocks in this slice. */ + uint32_t num_macroblocks; + /** \brief Same as the element in slice() */ + int32_t quantiser_scale_code; + /** \brief Flag to indicate intra slice */ + int32_t is_intra_slice; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSliceParameterBufferMPEG2; + +typedef struct _VAEncMiscParameterExtensionDataSeqDisplayMPEG2 { + /** should always be 0x02 to identify it is Sequence Display Extension ISO-13818 */ + uint8_t extension_start_code_identifier; + /** these field should follow ISO-13818 6.3.6 */ + uint8_t video_format; + uint8_t colour_description; + uint8_t colour_primaries; + uint8_t transfer_characteristics; + uint8_t matrix_coefficients; + uint16_t display_horizontal_size; + uint16_t display_vertical_size; +} VAEncMiscParameterExtensionDataSeqDisplayMPEG2; +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* _VA_ENC_MPEG2_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_enc_vp8.h b/rs/moq-vaapi/libva/va/va_enc_vp8.h new file mode 100644 index 00000000000..84ce05f4e64 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_vp8.h @@ -0,0 +1,350 @@ +/* + * Copyright (c) 2007-2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_vp8.h + * \brief VP8 encoding API + * + * This file contains the \ref api_enc_vp8 "VP8 encoding API". + */ + +#ifndef VA_ENC_VP8_H +#define VA_ENC_VP8_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_enc_vp8 VP8 encoding API + * + * @{ + */ + +/** + * \brief VP8 Encoding Sequence Parameter Buffer Structure + * + * This structure conveys sequence level parameters. + * + */ +typedef struct _VAEncSequenceParameterBufferVP8 { + /* frame width in pixels */ + uint32_t frame_width; + /* frame height in pixels */ + uint32_t frame_height; + /* horizontal scale */ + uint32_t frame_width_scale; + /* vertical scale */ + uint32_t frame_height_scale; + + /* whether to enable error resilience features */ + uint32_t error_resilient; + /* auto keyframe placement, non-zero means enable auto keyframe placement */ + uint32_t kf_auto; + /* keyframe minimum interval */ + uint32_t kf_min_dist; + /* keyframe maximum interval */ + uint32_t kf_max_dist; + + + /* RC related fields. RC modes are set with VAConfigAttribRateControl */ + /* For VP8, CBR implies HRD conformance and VBR implies no HRD conformance */ + + /** + * Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for this + * sequence if CBR or VBR mode is used, i.e. if the encoder + * pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * The bitrate can be modified later on through + * #VAEncMiscParameterRateControl buffers. + */ + uint32_t bits_per_second; + /* Period between I frames. */ + uint32_t intra_period; + + /* reference and reconstructed frame buffers + * Used for driver auto reference management when configured through + * VAConfigAttribEncAutoReference. + */ + VASurfaceID reference_frames[4]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSequenceParameterBufferVP8; + + +/** + * \brief VP8 Encoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters. + * + */ +typedef struct _VAEncPictureParameterBufferVP8 { + /* surface to store reconstructed frame */ + VASurfaceID reconstructed_frame; + + /* + * surfaces to store reference frames in non auto reference mode + * VA_INVALID_SURFACE can be used to denote an invalid reference frame. + */ + VASurfaceID ref_last_frame; + VASurfaceID ref_gf_frame; + VASurfaceID ref_arf_frame; + + /* buffer to store coded data */ + VABufferID coded_buf; + + union { + struct { + /* force this frame to be a keyframe */ + uint32_t force_kf : 1; + /* don't reference the last frame */ + uint32_t no_ref_last : 1; + /* don't reference the golden frame */ + uint32_t no_ref_gf : 1; + /* don't reference the alternate reference frame */ + uint32_t no_ref_arf : 1; + /* The temporal id the frame belongs to. */ + uint32_t temporal_id : 8; + /** + * following two flags indicate the reference order + * LastRef is specified by 01b; + * GoldRef is specified by 10b; + * AltRef is specified by 11b; + * first_ref specifies the reference frame which is searched first. + * second_ref specifies the reference frame which is searched second + * if there is. + */ + uint32_t first_ref : 2; + uint32_t second_ref : 2; + /** \brief Reserved for future use, must be zero */ + uint32_t reserved : 16; + } bits; + uint32_t value; + } ref_flags; + + union { + struct { + /* version */ + uint32_t frame_type : 1; + uint32_t version : 3; + /* show_frame */ + uint32_t show_frame : 1; + /* color_space */ + uint32_t color_space : 1; + /* 0: bicubic, 1: bilinear, other: none */ + uint32_t recon_filter_type : 2; + /* 0: no loop fitler, 1: simple loop filter */ + uint32_t loop_filter_type : 2; + /* 0: disabled, 1: normal, 2: simple */ + uint32_t auto_partitions : 1; + /* same as log2_nbr_of_dct_partitions in frame header syntax */ + uint32_t num_token_partitions : 2; + + /** + * The following fields correspond to the same VP8 syntax elements + * in the frame header. + */ + /** + * 0: clamping of reconstruction pixels is disabled, + * 1: clamping enabled. + */ + uint32_t clamping_type : 1; + /* indicate segmentation is enabled for the current frame. */ + uint32_t segmentation_enabled : 1; + /** + * Determines if the MB segmentation map is updated in the current + * frame. + */ + uint32_t update_mb_segmentation_map : 1; + /** + * Indicates if the segment feature data is updated in the current + * frame. + */ + uint32_t update_segment_feature_data : 1; + /** + * indicates if the MB level loop filter adjustment is enabled for + * the current frame (0 off, 1 on). + */ + uint32_t loop_filter_adj_enable : 1; + /** + * Determines whether updated token probabilities are used only for + * this frame or until further update. + * It may be used by application to enable error resilient mode. + * In this mode probability updates are allowed only at Key Frames. + */ + uint32_t refresh_entropy_probs : 1; + /** + * Determines if the current decoded frame refreshes the golden frame. + */ + uint32_t refresh_golden_frame : 1; + /** + * Determines if the current decoded frame refreshes the alternate + * reference frame. + */ + uint32_t refresh_alternate_frame : 1; + /** + * Determines if the current decoded frame refreshes the last frame + * reference buffer. + */ + uint32_t refresh_last : 1; + /** + * Determines if the golden reference is replaced by another reference. + */ + uint32_t copy_buffer_to_golden : 2; + /** + * Determines if the alternate reference is replaced by another reference. + */ + uint32_t copy_buffer_to_alternate : 2; + /** + * Controls the sign of motion vectors when the golden frame is referenced. + */ + uint32_t sign_bias_golden : 1; + /** + * Controls the sign of motion vectors when the alternate frame is + * referenced. + */ + uint32_t sign_bias_alternate : 1; + /** + * Enables or disables the skipping of macroblocks containing no + * non-zero coefficients. + */ + uint32_t mb_no_coeff_skip : 1; + /** + * Enforces unconditional per-MB loop filter delta update setting frame + * header flags mode_ref_lf_delta_update, all mb_mode_delta_update_flag[4], + * and all ref_frame_delta_update_flag[4] to 1. + * Since loop filter deltas are not automatically refreshed to default + * values at key frames, dropped frame with delta update may prevent + * correct decoding from the next key frame. + * Encoder application is advised to set this flag to 1 at key frames. + */ + uint32_t forced_lf_adjustment : 1; + uint32_t reserved : 2; + } bits; + uint32_t value; + } pic_flags; + + /** + * Contains a list of 4 loop filter level values (updated value if applicable) + * controlling the deblocking filter strength. Each entry represents a segment. + * When segmentation is disabled, use entry 0. + * When loop_filter_level is 0, loop filter shall be disabled. + */ + int8_t loop_filter_level[4]; + + /** + * Contains a list of 4 delta values for reference frame based MB-level + * loop filter adjustment. + * If no update, then set to 0. + */ + int8_t ref_lf_delta[4]; + + /** + * Contains a list of 4 delta values for coding mode based MB-level loop + * filter adjustment. + * If no update, then set to 0. + */ + int8_t mode_lf_delta[4]; + + /** + * Controls the deblocking filter sensitivity. + * Corresponds to the same VP8 syntax element in frame header. + */ + uint8_t sharpness_level; + + /** + * Application supplied maximum clamp value for Qindex used in quantization. + * Qindex will not be allowed to exceed this value. + * It has a valid range [0..127] inclusive. + */ + uint8_t clamp_qindex_high; + + /** + * Application supplied minimum clamp value for Qindex used in quantization. + * Qindex will not be allowed to be lower than this value. + * It has a valid range [0..127] inclusive. + * Condition clamp_qindex_low <= clamp_qindex_high must be guaranteed, + * otherwise they are ignored. + */ + uint8_t clamp_qindex_low; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncPictureParameterBufferVP8; + + +/** + * \brief VP8 MB Segmentation ID Buffer + * + * application provides buffer containing the initial segmentation id for each + * MB, in raster scan order. Rate control may reassign it. + * For an 640x480 video, the buffer has 1200 entries. + * the value of each entry should be in the range [0..3], inclusive. + * If segmentation is not enabled, application does not need to provide it. + */ +typedef struct _VAEncMBMapBufferVP8 { + /** + * number of MBs in the frame. + * It is also the number of entries of mb_segment_id[]; + */ + uint32_t num_mbs; + /** + * per MB Segmentation ID Buffer + */ + uint8_t *mb_segment_id; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMBMapBufferVP8; + + +/** + * \brief VP8 Quantization Matrix Buffer Structure + * + * Contains quantization index for yac(0-3) for each segment and quantization + * index deltas, ydc(0), y2dc(1), y2ac(2), uvdc(3), uvac(4) that are applied + * to all segments. When segmentation is disabled, only quantization_index[0] + * will be used. This structure is sent once per frame. + */ +typedef struct _VAQMatrixBufferVP8 { + uint16_t quantization_index[4]; + int16_t quantization_index_delta[5]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAQMatrixBufferVP8; + + + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_VP8_H */ diff --git a/rs/moq-vaapi/libva/va/va_enc_vp9.h b/rs/moq-vaapi/libva/va/va_enc_vp9.h new file mode 100644 index 00000000000..40f32e3c323 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_enc_vp9.h @@ -0,0 +1,639 @@ +/* + * Copyright (c) 2007-2015 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_enc_vp9.h + * \brief VP9 encoding API + * + * This file contains the \ref api_enc_vp9 "VP9 encoding API". + * + */ + +#ifndef VA_ENC_VP9_H +#define VA_ENC_VP9_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_enc_vp9 VP9 encoding API + * + * @{ + */ + +/** + * \brief VP9 Encoding Status Data Buffer Structure + * + * This structure is used to convey status data from encoder to application. + * Driver allocates VACodedBufferVP9Status as a private data buffer. + * Driver encapsulates the status buffer with a VACodedBufferSegment, + * and sets VACodedBufferSegment.status to be VA_CODED_BUF_STATUS_CODEC_SPECIFIC. + * And driver associates status data segment to the bit stream buffer segment + * by setting VACodedBufferSegment.next of coded_buf (bit stream) to the private + * buffer segment of status data. + * Application accesses it by calling VAMapBuffer() with VAEncCodedBufferType. + */ +typedef struct _VACodedBufferVP9Status { + /** Final quantization index used (yac), determined by BRC. + * Application is providing quantization index deltas + * ydc(0), y2dc(1), y2ac(2), uvdc(3), uvac(4) that are applied to all segments + * and segmentation qi deltas, they will not be changed by BRC. + */ + uint16_t base_qp_index; + + /** Final loopfilter levels for the frame, if segmentation is disabled only + * index 0 is used. + * If loop_filter_level is 0, it indicates loop filter is disabled. + */ + uint8_t loop_filter_level; + + /** + * Long term reference frame indication from BRC. BRC recommends the + * current frame that is being queried is a good candidate for a long + * term reference. + */ + uint8_t long_term_indication; + + /* suggested next frame width */ + uint16_t next_frame_width; + + /* suggested next frame height */ + uint16_t next_frame_height; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VACodedBufferVP9Status; + +/** + * \brief VP9 Encoding Sequence Parameter Buffer Structure + * + * This structure conveys sequence level parameters. + * + */ +typedef struct _VAEncSequenceParameterBufferVP9 { + /** \brief Frame size note: + * Picture resolution may change frame by frame. + * Application needs to allocate surfaces and frame buffers based on + * max frame resolution in case resolution changes for later frames. + * The source and recon surfaces allocated should be 64x64(SB) aligned + * on both horizontal and vertical directions. + * But buffers on the surfaces need to be aligned to CU boundaries. + */ + /* maximum frame width in pixels for the whole sequence */ + uint32_t max_frame_width; + + /* maximum frame height in pixels for the whole sequence */ + uint32_t max_frame_height; + + /* auto keyframe placement, non-zero means enable auto keyframe placement */ + uint32_t kf_auto; + + /* keyframe minimum interval */ + uint32_t kf_min_dist; + + /* keyframe maximum interval */ + uint32_t kf_max_dist; + + + /* RC related fields. RC modes are set with VAConfigAttribRateControl */ + /* For VP9, CBR implies HRD conformance and VBR implies no HRD conformance */ + + /** + * Initial bitrate set for this sequence in CBR or VBR modes. + * + * This field represents the initial bitrate value for this + * sequence if CBR or VBR mode is used, i.e. if the encoder + * pipeline was created with a #VAConfigAttribRateControl + * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. + * + * The bitrate can be modified later on through + * #VAEncMiscParameterRateControl buffers. + */ + uint32_t bits_per_second; + + /* Period between key frames */ + uint32_t intra_period; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSequenceParameterBufferVP9; + + +/** + * \brief VP9 Encoding Picture Parameter Buffer Structure + * + * This structure conveys picture level parameters. + * + */ +typedef struct _VAEncPictureParameterBufferVP9 { + /** VP9 encoder may support dynamic scaling function. + * If enabled (enable_dynamic_scaling is set), application may request + * GPU encodes picture with a different resolution from the raw source. + * GPU should handle the scaling process of source and + * all reference frames. + */ + /* raw source frame width in pixels */ + uint32_t frame_width_src; + /* raw source frame height in pixels */ + uint32_t frame_height_src; + + /* to be encoded frame width in pixels */ + uint32_t frame_width_dst; + /* to be encoded frame height in pixels */ + uint32_t frame_height_dst; + + /* surface to store reconstructed frame, not used for enc only case */ + VASurfaceID reconstructed_frame; + + /** \brief reference frame buffers + * Each entry of the array specifies the surface index of the picture + * that is referred by current picture or will be referred by any future + * picture. The valid entries take value from 0 to 127, inclusive. + * Non-valid entries, those do not point to pictures which are referred + * by current picture or future pictures, should take value 0xFF. + * Other values are not allowed. + * + * Application should update this array based on the refreshing + * information expected. + */ + VASurfaceID reference_frames[8]; + + /* buffer to store coded data */ + VABufferID coded_buf; + + union { + struct { + /* force this frame to be a keyframe */ + uint32_t force_kf : 1; + + /** \brief Indiates which frames to be used as reference. + * (Ref_frame_ctrl & 0x01) ? 1: last frame as reference frame, 0: not. + * (Ref_frame_ctrl & 0x02) ? 1: golden frame as reference frame, 0: not. + * (Ref_frame_ctrl & 0x04) ? 1: alt frame as reference frame, 0: not. + * L0 is for forward prediction. + * L1 is for backward prediction. + */ + uint32_t ref_frame_ctrl_l0 : 3; + uint32_t ref_frame_ctrl_l1 : 3; + + /** \brief Last Reference Frame index + * Specifies the index to RefFrameList[] which points to the LAST + * reference frame. It corresponds to active_ref_idx[0] in VP9 code. + */ + uint32_t ref_last_idx : 3; + + /** \brief Specifies the Sign Bias of the LAST reference frame. + * It corresponds to ref_frame_sign_bias[LAST_FRAME] in VP9 code. + */ + uint32_t ref_last_sign_bias : 1; + + /** \brief GOLDEN Reference Frame index + * Specifies the index to RefFrameList[] which points to the Golden + * reference frame. It corresponds to active_ref_idx[1] in VP9 code. + */ + uint32_t ref_gf_idx : 3; + + /** \brief Specifies the Sign Bias of the GOLDEN reference frame. + * It corresponds to ref_frame_sign_bias[GOLDEN_FRAME] in VP9 code. + */ + uint32_t ref_gf_sign_bias : 1; + + /** \brief Alternate Reference Frame index + * Specifies the index to RefFrameList[] which points to the Alternate + * reference frame. It corresponds to active_ref_idx[2] in VP9 code. + */ + uint32_t ref_arf_idx : 3; + + /** \brief Specifies the Sign Bias of the ALTERNATE reference frame. + * It corresponds to ref_frame_sign_bias[ALTREF_FRAME] in VP9 code. + */ + uint32_t ref_arf_sign_bias : 1; + + /* The temporal id the frame belongs to */ + uint32_t temporal_id : 8; + + uint32_t reserved : 5; + } bits; + uint32_t value; + } ref_flags; + + union { + struct { + /** + * Indicates if the current frame is a key frame or not. + * Corresponds to the same VP9 syntax element in frame tag. + */ + uint32_t frame_type : 1; + + /** \brief show_frame + * 0: current frame is not for display + * 1: current frame is for display + */ + uint32_t show_frame : 1; + + /** + * The following fields correspond to the same VP9 syntax elements + * in the frame header. + */ + uint32_t error_resilient_mode : 1; + + /** \brief Indicate intra-only for inter pictures. + * Must be 0 for key frames. + * 0: inter frame use both intra and inter blocks + * 1: inter frame use only intra blocks. + */ + uint32_t intra_only : 1; + + /** \brief Indicate high precision mode for Motion Vector prediction + * 0: normal mode + * 1: high precision mode + */ + uint32_t allow_high_precision_mv : 1; + + /** \brief Motion Compensation Filter type + * 0: eight-tap (only this mode is supported now.) + * 1: eight-tap-smooth + * 2: eight-tap-sharp + * 3: bilinear + * 4: switchable + */ + uint32_t mcomp_filter_type : 3; + uint32_t frame_parallel_decoding_mode : 1; + uint32_t reset_frame_context : 2; + uint32_t refresh_frame_context : 1; + uint32_t frame_context_idx : 2; + uint32_t segmentation_enabled : 1; + + /* corresponds to variable temporal_update in VP9 code. + * Indicates whether Segment ID is from bitstream or from previous + * frame. + * 0: Segment ID from bitstream + * 1: Segment ID from previous frame + */ + uint32_t segmentation_temporal_update : 1; + + /* corresponds to variable update_mb_segmentation_map in VP9 code. + * Indicates how hardware determines segmentation ID + * 0: intra block - segment id is 0; + * inter block - segment id from previous frame + * 1: intra block - segment id from bitstream (app or GPU decides) + * inter block - depends on segmentation_temporal_update + */ + uint32_t segmentation_update_map : 1; + + /** \brief Specifies if the picture is coded in lossless mode. + * + * lossless_mode = base_qindex == 0 && y_dc_delta_q == 0 \ + * && uv_dc_delta_q == 0 && uv_ac_delta_q == 0; + * Where base_qindex, y_dc_delta_q, uv_dc_delta_q and uv_ac_delta_q + * are all variables in VP9 code. + * + * When enabled, tx_mode needs to be set to 4x4 only and all + * tu_size in CU record set to 4x4 for entire frame. + * Software also has to program such that final_qindex=0 and + * final_filter_level=0 following the Quant Scale and + * Filter Level Table in Segmentation State section. + * Hardware forces Hadamard Tx when this bit is set. + * When lossless_mode is on, BRC has to be turned off. + * 0: normal mode + * 1: lossless mode + */ + uint32_t lossless_mode : 1; + + /** \brief MV prediction mode. Corresponds to VP9 variable with same name. + * comp_prediction_mode = 0: single prediction ony, + * comp_prediction_mode = 1: compound prediction, + * comp_prediction_mode = 2: hybrid prediction + * + * Not mandatory. App may suggest the setting based on power or + * performance. Kernal may use it as a guildline and decide the proper + * setting on its own. + */ + uint32_t comp_prediction_mode : 2; + + /** \brief Indicate how segmentation is specified + * 0 application specifies segmentation partitioning and + * relevant parameters. + * 1 GPU may decide on segmentation. If application already + * provides segmentation information, GPU may choose to + * honor it and further split into more levels if possible. + */ + uint32_t auto_segmentation : 1; + + /** \brief Indicate super frame syntax should be inserted + * 0 current frame is not encapsulated in super frame structure + * 1 current fame is to be encapsulated in super frame structure. + * super frame index syntax will be inserted by encoder at + * the end of current frame. + */ + uint32_t super_frame_flag : 1; + + uint32_t reserved : 10; + } bits; + uint32_t value; + } pic_flags; + + /** \brief indicate which frames in DPB should be refreshed. + * same syntax and semantic as in VP9 code. + */ + uint8_t refresh_frame_flags; + + /** \brief Base Q index in the VP9 term. + * Added with per segment delta Q index to get Q index of Luma AC. + */ + uint8_t luma_ac_qindex; + + /** + * Q index delta from base Q index in the VP9 term for Luma DC. + */ + int8_t luma_dc_qindex_delta; + + /** + * Q index delta from base Q index in the VP9 term for Chroma AC. + */ + int8_t chroma_ac_qindex_delta; + + /** + * Q index delta from base Q index in the VP9 term for Chroma DC. + */ + int8_t chroma_dc_qindex_delta; + + /** \brief filter level + * Corresponds to the same VP9 syntax element in frame header. + */ + uint8_t filter_level; + + /** + * Controls the deblocking filter sensitivity. + * Corresponds to the same VP9 syntax element in frame header. + */ + uint8_t sharpness_level; + + /** \brief Loop filter level reference delta values. + * Contains a list of 4 delta values for reference frame based block-level + * loop filter adjustment. + * If no update, set to 0. + * value range [-63..63] + */ + int8_t ref_lf_delta[4]; + + /** \brief Loop filter level mode delta values. + * Contains a list of 4 delta values for coding mode based MB-level loop + * filter adjustment. + * If no update, set to 0. + * value range [-63..63] + */ + int8_t mode_lf_delta[2]; + + /** + * Offset from starting position of output bitstream in bits where + * ref_lf_delta[] should be inserted. This offset should cover any metadata + * ahead of uncompressed header in inserted bit stream buffer (the offset + * should be same as that for final output bitstream buffer). + * + * In BRC mode, always insert ref_lf_delta[] (This implies uncompressed + * header should have mode_ref_delta_enabled=1 and mode_ref_delta_update=1). + */ + uint16_t bit_offset_ref_lf_delta; + + /** + * Offset from starting position of output bitstream in bits where + * mode_lf_delta[] should be inserted. + * + * In BRC mode, always insert mode_lf_delta[] (This implies uncompressed + * header should have mode_ref_delta_enabled=1 and mode_ref_delta_update=1). + */ + uint16_t bit_offset_mode_lf_delta; + + /** + * Offset from starting position of output bitstream in bits where (loop) + * filter_level should be inserted. + */ + uint16_t bit_offset_lf_level; + + /** + * Offset from starting position of output bitstream in bits where + * Base Qindex should be inserted. + */ + uint16_t bit_offset_qindex; + + /** + * Offset from starting position of output bitstream in bits where + * First Partition Size should be inserted. + */ + uint16_t bit_offset_first_partition_size; + + /** + * Offset from starting position of output bitstream in bits where + * segmentation_enabled is located in bitstream. When auto_segmentation + * is enabled, GPU uses this offset to locate and update the + * segmentation related information. + */ + uint16_t bit_offset_segmentation; + + /** \brief length in bit of segmentation portion from the location + * in bit stream where segmentation_enabled syntax is coded. + * When auto_segmentation is enabled, GPU uses this bit size to locate + * and update the information after segmentation. + */ + uint16_t bit_size_segmentation; + + + /** \brief log2 of number of tile rows + * Corresponds to the same VP9 syntax element in frame header. + * value range [0..2] + */ + uint8_t log2_tile_rows; + + /** \brief log2 of number of tile columns + * Corresponds to the same VP9 syntax element in frame header. + * value range [0..6] + */ + uint8_t log2_tile_columns; + + /** \brief indicate frame-skip happens + * Application may choose to drop/skip one or mulitple encoded frames or + * to-be-encoded frame due to various reasons such as insufficient + * bandwidth. + * Application uses the following three flags to inform GPU about frame-skip. + * + * value range of skip_frame_flag: [0..2] + * 0 - encode as normal, no skip; + * 1 - one or more frames were skipped by application prior to the + * current frame. Encode the current frame as normal. The driver + * will pass the number_skip_frames and skip_frames_size + * to bit rate control for adjustment. + * 2 - the current frame is to be skipped. Do not encode it but encrypt + * the packed header contents. This is for the secure encoding case + * where application generates a frame of all skipped blocks. + * The packed header will contain the skipped frame. + */ + uint8_t skip_frame_flag; + + /** \brief The number of frames skipped prior to the current frame. + * It includes only the skipped frames that were not counted before, + * and does not include the frame with skip_frame_flag == 2. + * Valid when skip_frame_flag = 1. + */ + uint8_t number_skip_frames; + + /** \brief When skip_frame_flag = 1, the size of the skipped frames in bits. + * It includes only the skipped frames that were not counted before, + * and does not include the frame size with skip_frame_flag = 2. + * When skip_frame_flag = 2, it is the size of the current skipped frame + * that is to be encrypted. + */ + uint32_t skip_frames_size; + + /** \brief Block size for each Segment ID in Segment Map. + * This specify the granularity of media driver of reading and processing the segment map. + * value should be VA_SEGID_BLOCK_XXX + */ + uint8_t seg_id_block_size; + + uint8_t va_reserved8[3]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_MEDIUM - 1]; +} VAEncPictureParameterBufferVP9; + + +/** + * \brief Per segment parameters + */ +typedef struct _VAEncSegParamVP9 { + union { + struct { + /** \brief Indicates if per segment reference frame indicator is enabled. + * Corresponding to variable feature_enabled when + * j == SEG_LVL_REF_FRAME in function setup_segmentation() VP9 code. + */ + uint8_t segment_reference_enabled : 1; + + /** \brief Specifies per segment reference indication. + * 0: reserved + * 1: Last ref + * 2: golden + * 3: altref + * Value can be derived from variable data when + * j == SEG_LVL_REF_FRAME in function setup_segmentation() VP9 code. + * value range: [0..3] + */ + uint8_t segment_reference : 2; + + /** \brief Indicates if per segment skip mode is enabled. + * Corresponding to variable feature_enabled when + * j == SEG_LVL_SKIP in function setup_segmentation() VP9 code. + */ + uint8_t segment_reference_skipped : 1; + + uint8_t reserved : 4; + + } bits; + uint8_t value; + } seg_flags; + + /** \brief Specifies per segment Loop Filter Delta. + * Must be 0 when segmentation_enabled == 0. + * value range: [-63..63] + */ + int8_t segment_lf_level_delta; + + /** \brief Specifies per segment QIndex Delta. + * Must be 0 when segmentation_enabled == 0. + * value range: [-255..255] + */ + int16_t segment_qindex_delta; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncSegParamVP9; + +/** + * Structure to convey all segment related information. + * If segmentation is disabled, this data structure is still required. + * In this case, only seg_data[0] contains valid data. + * This buffer is sent once per frame. + * + * The buffer is created with VABufferType VAQMatrixBufferType. + * + */ +typedef struct _VAEncMiscParameterTypeVP9PerSegmantParam { + /** + * Parameters for 8 segments. + */ + VAEncSegParamVP9 seg_data[8]; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAEncMiscParameterTypeVP9PerSegmantParam; + + +/** + * \brief VP9 Block Segmentation ID Buffer + * + * The application provides a buffer of VAEncMacroblockMapBufferType containing + * the initial segmentation id for each block, block size is specified by seg_id_block_size + * in VAEncPictureParameterBufferVP9 , one byte each, in raster scan order. + * Rate control may reassign it. For example, a 640x480 video, seg_id_block_size is + * VA_SEGID_BLOCK_16X16 , the buffer has 1200 entries. + * The value of each entry should be in the range [0..7], inclusive. + * If segmentation is not enabled, the application does not need to provide it. + */ + + +/** \brief Attribute value for VAConfigAttribEncVP9. */ +typedef union _VAConfigAttribValEncVP9 { + struct { + /** + * \brief segmentId block size accepted. + * This is the granularity of segmentation map. + * one bit represent one block size defined as VA_SEGID_BLOCKXXXX + * should be (1 << VA_SEGID_BLOCKXXX | 1 << VA_SEGID_BLOCKXXX ... ) + */ + uint32_t seg_id_block_size : 8; + + /** + * \brief Type of segment feature supported. + * (segment_feature_support & 0x01) == 1: SEG_LVL_ALT_Q is supported, 0: not. + * (segment_feature_support & 0x02) == 1: SEG_LVL_ALT_L is supported, 0: not. + * (segment_feature_support & 0x04) == 1: SEG_LVL_REF_FRAME is supported, 0: not. + * (segment_feature_support & 0x08) == 1: SEG_LVL_SKIP is supported, 0: not. + */ + uint32_t segment_feature_support : 4; + + /** \brief Reserved bits for future, must be zero. */ + uint32_t reserved : 20; + } bits; + uint32_t value; +} VAConfigAttribValEncVP9; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_ENC_VP9_H */ diff --git a/rs/moq-vaapi/libva/va/va_fei.h b/rs/moq-vaapi/libva/va/va_fei.h new file mode 100644 index 00000000000..d12d5bbf60b --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_fei.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2007-2017 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_fei.h + * \brief The FEI encoding common API + */ + +#ifndef VA_FEI_H +#define VA_FEI_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * \defgroup api_fei FEI encoding common API + * + * @{ + */ + +/** + * \brief FEI specific attribute definitions + */ +/** @name Attribute values for VAConfigAttribFEIFunctionType + * + * This is only for VAEntrypointFEI + * The desired type should be passed to driver when creating the configuration. + * If VA_FEI_FUNCTION_ENC_PAK is set, VA_FEI_FUNCTION_ENC and VA_FEI_FUNCTION_PAK + * will be ignored if set also. Combination of VA_FEI_FUNCTION_ENC and VA_FEI_FUNCTION_PAK + * is not valid. If VA_FEI_FUNCTION_ENC is set, there will be no bitstream output. + * If VA_FEI_FUNCTION_PAK is set, two extra input buffers for PAK are needed: + * VAEncFEIMVBufferType and VAEncFEIMBCodeBufferType. + * VA_FEI_FUNCTION_ENC_PAK is recommended for best performance. + * + **/ +/**@{*/ +/** \brief ENC only is supported */ +#define VA_FEI_FUNCTION_ENC 0x00000001 +/** \brief PAK only is supported */ +#define VA_FEI_FUNCTION_PAK 0x00000002 +/** \brief ENC_PAK is supported */ +#define VA_FEI_FUNCTION_ENC_PAK 0x00000004 + +/**@}*/ + +/** \brief Attribute value for VAConfigAttribStats */ +typedef union _VAConfigAttribValStats { + struct { + /** \brief Max number of past reference frames that are supported. */ + uint32_t max_num_past_references : 4; + /** \brief Max number of future reference frames that are supported. */ + uint32_t max_num_future_references : 4; + /** \brief Number of supported output buffers for VAStatsStatisticsParameter->outputs */ + uint32_t num_outputs : 3; + /** \brief Interlaced content is supported */ + uint32_t interlaced : 1; + uint32_t reserved : 20; + } bits; + uint32_t value; +} VAConfigAttribValStats; + +typedef struct _VAPictureStats { + VASurfaceID picture_id; + /* + * see flags below. + */ + uint32_t flags; +} VAPictureStats; +/* flags in VAPictureStats could be one of the following */ +#define VA_PICTURE_STATS_INVALID 0x00000001 +#define VA_PICTURE_STATS_PROGRESSIVE 0x00000000 +#define VA_PICTURE_STATS_TOP_FIELD 0x00000002 +#define VA_PICTURE_STATS_BOTTOM_FIELD 0x00000004 +/** \brief picutre surface content updated indicator. + * The picture surface content is updated, it means temporary buffer like downscaled pixel data in driver + * internal needs be forced freshing + **/ +#define VA_PICTURE_STATS_CONTENT_UPDATED 0x00000010 + +/** \brief Motion Vector and Statistics frame level controls. + * common part VAStatsStatisticsParameterBufferType for a MB or CTB + **/ +typedef struct _VAStatsStatisticsParameter { + /** \brief Source surface ID. */ + VAPictureStats input; + + /** \brief Past reference surface ID pointer. */ + VAPictureStats *past_references; + + /** \brief Past reference surface number */ + uint32_t num_past_references; + + /** \brief Statistics output for past reference surface. + * Only enabling statistics output for past reference picture when *past_ref_stat_buf is a valid + * VABufferID, it is needed in case app wants statistics data of both reference and current pictures + * in very special use cases for better performance. + * The output layout is defined by VAStatsStatisticsBufferType(for progressive and top field of + * interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case), only + * pixel_average_16x16/pixel_average_8x8 and variance_16x16/variance_8x8 data are valid. + **/ + VABufferID *past_ref_stat_buf; + + /** \brief Future reference surface ID pointer. */ + VAPictureStats *future_references; + + /** \brief Future reference surface number */ + uint32_t num_future_references; + + /** \brief Statistics output for future reference surface. + * Only enabling statistics output for future reference picture when *past_ref_stat_buf is a valid + * VABufferID, it is needed in case app wants statistics data of both reference and current pictures + * in very special use cases for better performance. + * The output layout is defined by VAStatsStatisticsBufferType(for progressive and top field of + * interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case), only + * pixel_average_16x16/pixel_average_8x8 and variance_16x16/variance_8x8 data are valid. + **/ + VABufferID *future_ref_stat_buf; + + /** \brief ID of the output buffer. + * The number of outputs is determined by below DisableMVOutput and DisableStatisticsOutput. + * The output layout is defined by VAStatsMVBufferType, VAStatsStatisticsBufferType(for progressive and + * top field of interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case). + **/ + VABufferID *outputs; + + /** \brief MV predictor. It is valid only when mv_predictor_ctrl is not 0. + * Each block has a pair of MVs, one for past and one for future reference + * as defined by VAMotionVector. The block is in raster scan order. + * Buffer size shall not be less than the number of blocks multiplied by sizeof(VAMotionVector). + **/ + VABufferID mv_predictor; + + /** \brief QP input buffer. It is valid only when mb_qp is set to 1. + * The data in this buffer correspond to the input source. + * One QP per MB or CTB block in raster scan order, each QP is a signed char (8-bit) value. + **/ + VABufferID qp; +} VAStatsStatisticsParameter; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_FEI_H */ diff --git a/rs/moq-vaapi/libva/va/va_fei_h264.h b/rs/moq-vaapi/libva/va/va_fei_h264.h new file mode 100644 index 00000000000..d04430dcfce --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_fei_h264.h @@ -0,0 +1,505 @@ +/* + * Copyright (c) 2007-2017 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_fei_h264.h + * \brief The FEI encoding H264 special API + */ + +#ifndef VA_FEI_H264_H +#define VA_FEI_H264_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "va_fei.h" + +/** + * \defgroup api_fei_h264 H.264 FEI encoding API + * + * @{ + */ + +/** \brief FEI frame level control buffer for H.264 */ +typedef struct _VAEncMiscParameterFEIFrameControlH264 { + uint32_t function; /* one of the VAConfigAttribFEIFunctionType values */ + /** \brief MB (16x16) control input buffer. It is valid only when (mb_input | mb_size_ctrl) + * is set to 1. The data in this buffer correspond to the input source. 16x16 MB is in raster scan order, + * each MB control data structure is defined by VAEncFEIMBControlH264. + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAEncFEIMBControlH264). + * Note: if mb_qp is set, VAEncQPBufferH264 is expected. + */ + VABufferID mb_ctrl; + /** \brief distortion output of MB ENC or ENC_PAK. + * Each 16x16 block has one distortion data with VAEncFEIDistortionH264 layout + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAEncFEIDistortionH264). + */ + VABufferID distortion; + /** \brief MVs data output of MB ENC. + * Each 16x16 block has one MVs data with layout VAMotionVector + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAMotionVector) * 16. + */ + VABufferID mv_data; + /** \brief MBCode data output of MB ENC. + * Each 16x16 block has one MB Code data with layout VAEncFEIMBCodeH264 + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAEncFEIMBCodeH264). + */ + VABufferID mb_code_data; + /** \brief QP input buffer with layout VAEncQPBufferH264. It is valid only when mb_qp is set to 1. + * The data in this buffer correspond to the input source. + * One QP per 16x16 block in raster scan order, each QP is a signed char (8-bit) value. + **/ + VABufferID qp; + /** \brief MV predictor. It is valid only when mv_predictor_enable is set to 1. + * Each 16x16 block has one or more pair of motion vectors and the corresponding + * reference indexes as defined by VAEncFEIMVPredictorH264. 16x16 block is in raster scan order. + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAEncFEIMVPredictorH264). */ + VABufferID mv_predictor; + + /** \brief number of MV predictors. It must not be greater than maximum supported MV predictor. */ + uint32_t num_mv_predictors_l0 : 16; + uint32_t num_mv_predictors_l1 : 16; + + /** \brief motion search method definition + * 0: default value, diamond search + * 1: full search + * 2: diamond search + **/ + uint32_t search_path : 8; + /** \brief maximum number of Search Units, valid range is [1, 63] + * 0 is treated as 1. reference search locations are grouped in a predefined pattern, + * and all locations within the same group must be either all are chosen or all are skipped. + * These predefined groups are called search unit (SU).*/ + uint32_t len_sp : 8; + uint32_t reserved0 : 16; + /** \brief defines the bit-mask for disabling sub-partition + * The lower 4 bits are for the major partitions (sub-macroblock) and the higher 3 bits for minor partitions (with sub-partition for 4x(8x8) sub-macroblocks. + * xxxxxx1 : 16x16 sub-macroblock disabled + * xxxxx1x : 2x(16x8) sub-macroblock within 16x16 disabled + * xxxx1xx : 2x(8x16) sub-macroblock within 16x16 disabled + * xxx1xxx : 1x(8x8) sub-partition for 4x(8x8) within 16x16 disabled + * xx1xxxx : 2x(8x4) sub-partition for 4x(8x8) within 16x16 disabled + * x1xxxxx : 2x(4x8) sub-partition for 4x(8x8) within 16x16 disabled + * 1xxxxxx : 4x(4x4) sub-partition for 4x(8x8) within 16x16 disabled + * 1111111 : Invalid + * 0000000 : default value */ + uint32_t sub_mb_part_mask : 7; + /** specifies which Luma Intra partition is enabled/disabled for intra mode decision. + * xxxx1: luma_intra_16x16 disabled + * xxx1x: luma_intra_8x8 disabled + * xx1xx: luma_intra_4x4 disabled + * xx111: intra prediction is disabled */ + uint32_t intra_part_mask : 5; + /** when set to 1, neighbor MV will be used as predictor; when set to 0, no neighbor MV will be used as predictor.*/ + uint32_t multi_pred_l0 : 1; + /** when set to 1, neighbor MV will be used as predictor; when set to 0, no neighbor MV will be used as predictor.*/ + uint32_t multi_pred_l1 : 1; + /**defines the half/quarter pel modes. The mode is inclusive, ie., higher precision mode samples lower precision locations. + * 00b: integer mode searching + * 01b: half-pel mode searching + * 10b: reserved + * 11b: quarter-pel mode searching */ + uint32_t sub_pel_mode : 2; + /** specifies distortion measure adjustments used for the inter motion search SAD comparison. + * 00b: none + * 10b: Haar transform adjusted*/ + uint32_t inter_sad : 2; + /** specifies distortion measure adjustments used for the intra motion search SAD comparison. + * 00b: none + * 10b: Haar transform adjusted*/ + uint32_t intra_sad : 2; + /** specifies if the output distortion is the raw distortion or cost adjusted distortion. + * 0: Raw Distortion without Cost + * 1: Distortion with added Cost */ + uint32_t distortion_type : 1; + /** when set to 1, enables the additional calls on Fraction & Bidirectional Refinement*/ + uint32_t repartition_check_enable : 1; + /** defines whether adaptive searching is enabled for IME(Integer Motion Estimation). + * 0: disable + * 1: enable */ + uint32_t adaptive_search : 1; + /** enables using the motion vector as an extra predictor provided by the host. If it is set, + * host needs to provide a buffer with motion vectors and the associated reference index for + * each 16x16 block as defined . The host can call processing function to get motion vectors and use as predictor. + * 0: MV predictor disabled + * 1: MV predictor enabled */ + uint32_t mv_predictor_enable : 1; + /** enables using the QP buffer to set the QP for each block*/ + uint32_t mb_qp : 1; + /** enable mb_ctrl buffer to handle MB*/ + uint32_t mb_input : 1; + /** when this flag is set, mb_ctrl must be set too and a buffer with per MB input + * needs to be provided and MaxSizeInWord and */ + uint32_t mb_size_ctrl : 1; + /** when this flag is set, extra distortion between the current MB and co-located MB is provided. + * Extra distortion output has performance impact, set it only when it is needed.*/ + uint32_t colocated_mb_distortion : 1; + uint32_t reserved1 : 4; + + /** \brief motion search window(ref_width * ref_height) */ + uint32_t ref_width : 8; + uint32_t ref_height : 8; + /** \brief predefined motion search windows. If selected, len_sp, window(ref_width * ref_eight) + * and search_path setting are ignored. + * 0: not use predefined search window + * 1: Tiny, len_sp=4, 24x24 window and diamond search + * 2: Small, len_sp=9, 28x28 window and diamond search + * 3: Diamond, len_sp=16, 48x40 window and diamond search + * 4: Large Diamond, len_sp=32, 48x40 window and diamond search + * 5: Exhaustive, len_sp=48, 48x40 window and full search + * 6: Extend Diamond, len_sp=16, 64x40 window and diamond search + * 7: Extend Large Diamond, len_sp=32, 64x40 window and diamond search + * 8: Extend Exhaustive, len_sp=48, 64x40 window and full search + **/ + uint32_t search_window : 4; + uint32_t reserved2 : 12; + + /** \brief max frame size control with multi passes QP setting */ + uint32_t max_frame_size; + /** \brief number of passes, every pass has different QP */ + uint32_t num_passes; + /** \brief delta QP list for every pass */ + uint8_t *delta_qp; + uint32_t reserved3[VA_PADDING_LOW]; +} VAEncMiscParameterFEIFrameControlH264; + +/** \brief FEI MB level control data structure */ +typedef struct _VAEncFEIMBControlH264 { + /** \brief when set, correposndent MB is coded as intra */ + uint32_t force_to_intra : 1; + /** \brief when set, correposndent MB is coded as skip */ + uint32_t force_to_skip : 1; + /** \brief specifies whether this macroblock should be coded as a non-skipped macroblock. */ + uint32_t force_to_nonskip : 1; + uint32_t enable_direct_bias_adjustment : 1; + uint32_t enable_motion_bias_adjustment : 1; + uint32_t ext_mv_cost_scaling_factor : 3; + uint32_t reserved0 : 24; + + uint32_t reserved1; + + uint32_t reserved2; + + uint32_t reserved3 : 16; + /** \brief when mb_size_ctrl is set, size here is used to budget accumulatively. Set to 0xFF if don't care. */ + uint32_t target_size_in_word : 8; + /** \brief specifies the max size of each MB */ + uint32_t max_size_in_word : 8; +} VAEncFEIMBControlH264; + + +/** \brief Application can use this definition as reference to allocate the buffer + * based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query. + **/ +typedef struct _VAEncFEIMVPredictorH264 { + /** \brief Reference index corresponding to the entry of RefPicList0 & RefPicList1 in VAEncSliceParameterBufferH264. + * Note that RefPicList0 & RefPicList1 needs to be the same for all slices. + * ref_idx_l0_x : index to RefPicList0; ref_idx_l1_x : index to RefPicList1; x : 0 - MaxNumPredictor. + **/ + struct { + uint8_t ref_idx_l0 : 4; + uint8_t ref_idx_l1 : 4; + } ref_idx[4]; /* index is predictor number */ + uint32_t reserved; + /** \brief MV. MaxNumPredictor must be the returned value from attribute VAConfigAttribFEIMVPredictors query. + * Even application doesn't use the maximum predictors, the VAFEIMVPredictorH264 structure size + * has to be defined as maximum so each MB can be at a fixed location. + * Note that 0x8000 must be used for correspondent intra block. + **/ + VAMotionVector mv[4]; /* MaxNumPredictor is 4 */ +} VAEncFEIMVPredictorH264; + +/** \brief FEI output */ +/** + * Motion vector output is per 4x4 block. For each 4x4 block there is a pair of MVs + * for RefPicList0 and RefPicList1 and each MV is 4 bytes including horizontal and vertical directions. + * Depending on Subblock partition, for the shape that is not 4x4, the MV is replicated + * so each 4x4 block has a pair of MVs. The 16x16 block has 32 MVs (128 bytes). + * 0x8000 is used for correspondent intra block. The 16x16 block is in raster scan order, + * within the 16x16 block, each 4x4 block MV is ordered as below in memory. + * The buffer size shall be greater than or equal to the number of 16x16 blocks multiplied by 128 bytes. + * Note that, when separate ENC and PAK is enabled, the exact layout of this buffer is needed for PAK input. + * App can reuse this buffer, or copy to a different buffer as PAK input. + * Layout is defined as Generic motion vector data structure VAMotionVector + * 16x16 Block + * ----------------------------------------- + * | 1 | 2 | 5 | 6 | + * ----------------------------------------- + * | 3 | 4 | 7 | 8 | + * ----------------------------------------- + * | 9 | 10 | 13 | 14 | + * ----------------------------------------- + * | 11 | 12 | 15 | 16 | + * ----------------------------------------- + **/ + +/** \brief VAEncFEIMBCodeH264 defines the data structure for VAEncFEIMBCodeBufferType per 16x16 MB block. + * it is output buffer of ENC and ENC_PAK modes, it's also input buffer of PAK mode. + * The 16x16 block is in raster scan order. Buffer size shall not be less than the number of 16x16 blocks + * multiplied by sizeof(VAEncFEIMBCodeH264). Note that, when separate ENC and PAK is enabled, + * the exact layout of this buffer is needed for PAK input. App can reuse this buffer, + * or copy to a different buffer as PAK input, reserved elements must not be modified when used as PAK input. + **/ +typedef struct _VAEncFEIMBCodeH264 { + //DWORD 0~2 + uint32_t reserved0[3]; + + //DWORD 3 + uint32_t inter_mb_mode : 2; + uint32_t mb_skip_flag : 1; + uint32_t reserved1 : 1; + uint32_t intra_mb_mode : 2; + uint32_t reserved2 : 1; + uint32_t field_mb_polarity_flag : 1; + uint32_t mb_type : 5; + uint32_t intra_mb_flag : 1; + uint32_t field_mb_flag : 1; + uint32_t transform8x8_flag : 1; + uint32_t reserved3 : 1; + uint32_t dc_block_coded_cr_flag : 1; + uint32_t dc_block_coded_cb_flag : 1; + uint32_t dc_block_coded_y_flag : 1; + uint32_t reserved4 : 12; + + //DWORD 4 + uint32_t horz_origin : 8; + uint32_t vert_origin : 8; + uint32_t cbp_y : 16; + + //DWORD 5 + uint32_t cbp_cb : 16; + uint32_t cbp_cr : 16; + + //DWORD 6 + uint32_t qp_prime_y : 8; + uint32_t reserved5 : 17; + uint32_t mb_skip_conv_disable : 1; + uint32_t is_last_mb : 1; + uint32_t enable_coefficient_clamp : 1; + uint32_t direct8x8_pattern : 4; + + //DWORD 7 8 and 9 + union { + /* Intra MBs */ + struct { + uint32_t luma_intra_pred_modes0 : 16; + uint32_t luma_intra_pred_modes1 : 16; + + uint32_t luma_intra_pred_modes2 : 16; + uint32_t luma_intra_pred_modes3 : 16; + + uint32_t chroma_intra_pred_mode : 2; + uint32_t intra_pred_avail_flag : 5; + uint32_t intra_pred_avail_flagF : 1; + uint32_t reserved6 : 24; + } intra_mb; + + /* Inter MBs */ + struct { + uint32_t sub_mb_shapes : 8; + uint32_t sub_mb_pred_modes : 8; + uint32_t reserved7 : 16; + + uint32_t ref_idx_l0_0 : 8; + uint32_t ref_idx_l0_1 : 8; + uint32_t ref_idx_l0_2 : 8; + uint32_t ref_idx_l0_3 : 8; + + uint32_t ref_idx_l1_0 : 8; + uint32_t ref_idx_l1_1 : 8; + uint32_t ref_idx_l1_2 : 8; + uint32_t ref_idx_l1_3 : 8; + } inter_mb; + } mb_mode; + + //DWORD 10 + uint32_t reserved8 : 16; + uint32_t target_size_in_word : 8; + uint32_t max_size_in_word : 8; + + //DWORD 11~14 + uint32_t reserved9[4]; + + //DWORD 15 + uint32_t reserved10; +} VAEncFEIMBCodeH264; // 64 bytes + +/** \brief VAEncFEIDistortionH264 defines the data structure for VAEncFEIDistortionBufferType per 16x16 MB block. + * It is output buffer of ENC and ENC_PAK modes, The 16x16 block is in raster scan order. + * Buffer size shall not be less than the number of 16x16 blocks multiple by sizeof(VAEncFEIDistortionH264). + **/ +typedef struct _VAEncFEIDistortionH264 { + /** \brief Inter-prediction-distortion associated with motion vector i (co-located with subblock_4x4_i). + * Its meaning is determined by sub-shape. It must be zero if the corresponding sub-shape is not chosen. + **/ + uint16_t inter_distortion[16]; + uint32_t best_inter_distortion : 16; + uint32_t best_intra_distortion : 16; + uint32_t colocated_mb_distortion : 16; + uint32_t reserved0 : 16; + uint32_t reserved1[2]; +} VAEncFEIDistortionH264; // 48 bytes + +/** \brief Motion Vector and Statistics frame level controls. + * VAStatsStatisticsParameterBufferType for H264 16x16 block + **/ +typedef struct _VAStatsStatisticsParameterH264 { + VAStatsStatisticsParameter stats_params; + + uint32_t frame_qp : 8; + /** \brief length of search path */ + uint32_t len_sp : 8; + /** \brief motion search method definition + * 0: default value, diamond search + * 1: full search + * 2: diamond search + **/ + uint32_t search_path : 8; + uint32_t reserved0 : 8; + + uint32_t sub_mb_part_mask : 7; + /** \brief sub pixel mode definition + * 00b: integer mode searching + * 01b: half-pel mode searching + * 10b: reserved + * 11b: quarter-pel mode searching + **/ + uint32_t sub_pel_mode : 2; + /** \brief distortion measure adjustment for inter search SAD comparison + * 00b: none + * 01b: reserved + * 10b: Haar transform adjusted + * 11b: reserved + **/ + uint32_t inter_sad : 2; + /** \brief distortion measure adjustment for intra search SAD comparison + * 00b: none + * 01b: reserved + * 10b: Haar transform adjusted + * 11b: reserved + **/ + uint32_t intra_sad : 2; + uint32_t adaptive_search : 1; + /** \brief indicate if future or/and past MV in mv_predictor buffer is valid. + * 0: MV predictor disabled + * 1: MV predictor enabled for past reference + * 2: MV predictor enabled for future reference + * 3: MV predictor enabled for both past and future references + **/ + uint32_t mv_predictor_ctrl : 3; + uint32_t mb_qp : 1; + /** \brief forward transform enable + * 0: disable + * 1: enable, needs frame_qp or mb_qp input for transform + **/ + uint32_t ft_enable : 1; + /** \brief luma intra mode partition mask + * xxxx1: luma_intra_16x16 disabled + * xxx1x: luma_intra_8x8 disabled + * xx1xx: luma_intra_4x4 disabled + * xx111: intra prediction is disabled + **/ + uint32_t intra_part_mask : 5; + uint32_t reserved1 : 8; + + /** \brief motion search window(ref_width * ref_height) */ + uint32_t ref_width : 8; + uint32_t ref_height : 8; + /** \brief predefined motion search windows. If selected, len_sp, window(ref_width * ref_eight) + * and search_path setting are ignored. + * 0: not use predefined search window + * 1: Tiny, len_sp=4, 24x24 window and diamond search + * 2: Small, len_sp=9, 28x28 window and diamond search + * 3: Diamond, len_sp=16, 48x40 window and diamond search + * 4: Large Diamond, len_sp=32, 48x40 window and diamond search + * 5: Exhaustive, len_sp=48, 48x40 window and full search + * 6: Extend Diamond, len_sp=16, 64x40 window and diamond search + * 7: Extend Large Diamond, len_sp=32, 64x40 window and diamond search + * 8: Extend Exhaustive, len_sp=48, 64x40 window and full search + **/ + uint32_t search_window : 4; + uint32_t reserved2 : 12; + + /** \brief MVOutput. When set to 1, MV output is NOT provided */ + uint32_t disable_mv_output : 1; + /** \brief StatisticsOutput. When set to 1, Statistics output is NOT provided. */ + uint32_t disable_statistics_output : 1; + /** \brief block 8x8 data enabling in statistics output */ + uint32_t enable_8x8_statistics : 1; + uint32_t reserved3 : 29; + uint32_t reserved4[2]; +} VAStatsStatisticsParameterH264; + +/** \brief VAStatsStatisticsH264. H264 Statistics buffer layout for VAStatsStatisticsBufferType + * and VAStatsStatisticsBottomFieldBufferType(for interlaced only). + * Statistics output is per 16x16 block. Data structure per 16x16 block is defined below. + * The 16x16 block is in raster scan order. The buffer size shall be greater than or equal to + * the number of 16x16 blocks multiplied by sizeof(VAStatsStatisticsH264). + **/ +typedef struct _VAStatsStatisticsH264 { + /** \brief past reference */ + uint32_t best_inter_distortion0 : 16; + uint32_t inter_mode0 : 16; + + /** \brief future reference */ + uint32_t best_inter_distortion1 : 16; + uint32_t inter_mode1 : 16; + + uint32_t best_intra_distortion : 16; + uint32_t intra_mode : 16; + + uint32_t num_non_zero_coef : 16; + uint32_t reserved0 : 16; + + uint32_t sum_coef; + + /** \brief DWORD 5 flat info **/ + uint32_t mb_is_flat : 1; + uint32_t reserved1 : 31; + + /** \brief DWORD 6 variance for block16x16**/ + uint32_t variance_16x16; + /** \brief DWORD 7 ~ 10, variance for block8x8 **/ + uint32_t variance_8x8[4]; + + /** \brief DWORD 11 pixel_average for block16x16 **/ + uint32_t pixel_average_16x16; + /** \brief DWORD 12 ~ 15, pixel_average for block8x8 **/ + uint32_t pixel_average_8x8[4]; +} VAStatsStatisticsH264; // 64 bytes + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_FEI_H264_H */ diff --git a/rs/moq-vaapi/libva/va/va_fei_hevc.h b/rs/moq-vaapi/libva/va/va_fei_hevc.h new file mode 100644 index 00000000000..2efb513844e --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_fei_hevc.h @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2007-2017 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_fei_hevc.h + * \brief The FEI encoding HEVC special API + */ + + +#ifndef __VA_FEI_HEVC_H__ +#define __VA_FEI_HEVC_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "va_fei.h" + +/** + * \defgroup api_fei_hevc HEVC FEI encoding API + * + * @{ + */ + +/** \brief FEI frame level control buffer for HEVC */ +typedef struct _VAEncMiscParameterFEIFrameControlHEVC { + /* one of the VAConfigAttribFEIFunctionType values */ + uint32_t function; + /** \brief CTB control input buffer. It is valid only when per_ctb_input + * is set to 1. The data in this buffer correspond to the input source. CTB is in raster scan order, + * each CTB control data structure is defined by VAEncFEICTBControlHEVC. + * Buffer size shall not be less than the number of CTBs multiplied by + * sizeof(VAEncFEICTBControlHEVC). + */ + VABufferID ctb_ctrl; + /** \brief CTB cmd per CTB data output of ENC + * it is reserved for CTB level information + * it should include CU split information and other CTB datas . + * Each CTB block has one CTB cmd data. + */ + VABufferID ctb_cmd; + /** \brief CU record data output of ENC + * it is reserved for CU level information + * it should include CU detail data. include mode,MV, reference etc. + * Each CTB block has one CU record data. + */ + VABufferID cu_record; + /** \brief distortion output of ENC or ENC_PAK. + * Each CTB has one distortion data with VAEncFEIDistortionHevc + * Buffer size shall not be less than the number of CTBs multiplied by + * sizeof(VAEncFEIDistortionHevc). + */ + VABufferID distortion; + /** \brief Qp input buffer. It is valid only when per_block_qp is set to 1. + * The data in this buffer correspond to the input source. + * One Qp per block block is in raster scan order, each Qp is a signed char (8-bit) value. + **/ + VABufferID qp; + /** \brief MV predictor. It is valid only when mv_predictor_input is set to non-zero. + * Each CTB block has one or more pair of motion vectors and the corresponding + * reference indexes as defined by VAEncFEIMVPredictorHEVC. 32x32 block is in raster scan order. + * Buffer size shall not be less than the number of 16x16 blocks multiplied by + * sizeof(VAEncFEIMVPredictorHEVC). */ + VABufferID mv_predictor; + + /** \brief number of MV predictors L0 and L1. the maximum number of motion vector predictor for a 16x16, 32x32 or + * 64x64 block is four, it must not be greater than maximum supported MV predictor, + **/ + uint32_t num_mv_predictors_l0 : 16; + uint32_t num_mv_predictors_l1 : 16; + + /** \brief control parameters */ + uint32_t search_path : 8; + uint32_t len_sp : 8; + uint32_t reserved0 : 16; + + /** \brief multi pred l0/1 + * 0000: no internal MV predictor will be used + * 0001: spatial MV predictors + * 0100/1000: Reserved + **/ + uint32_t multi_pred_l0 : 4; + uint32_t multi_pred_l1 : 4; + /** \brief defines the motion vector precision, like integer/half/quarter pel. + * 00b: integer pel + * 01b: half-pel + * 10b: reserved + * 11b: quarter-pel + */ + uint32_t sub_pel_mode : 2; + uint32_t adaptive_search : 1; + /** \brief mv_predictor_input + * 000: MV predictor disabled + * 001: MV predictor enabled per 16x16 block + * 010: MV predictor enabled per 32x32 block + * 011: MV predictor enabled per 64x64 block + * 111: MV predictor enabled, block size can vary and is determined by BlockSize in motion vector predictor buffer + * 100/101/110: Reserved + **/ + uint32_t mv_predictor_input : 3; + /** \brief enables per CTB or CU qp */ + uint32_t per_block_qp : 1; + /** \brief enables the per CTB input , if 1, need ctb_ctrl to be a real surface ID*/ + uint32_t per_ctb_input : 1; + /** when this flag is set, extra distortion between current CTB and co-located CTB is provided. + * Extra distortion output has performance impact, set it only when it is needed */ + uint32_t colocated_ctb_distortion : 1; + /** brief specifies whether this CTB should be forced to split to remove Inter big LCU: do not check Inter 32x32 + * PUs. Every 32x32 LCU is split at least once. It can be used to improved performance. + * 0: ENC determined block type + * 1: Force to split + **/ + uint32_t force_lcu_split : 1; + /** \brief enables CU64x64 check */ + uint32_t enable_cu64_check : 1; + /** \brief enables CU64x64 asymmetric motion partition check */ + uint32_t enable_cu64_amp_check : 1; + /** \brief specifies if check the 64x64 merge candidate + * 0: after skip check, + * 1: only skip check for 64x64 + Default: 0. This field is used by LCU64 bi-directional. + **/ + uint32_t cu64_skip_check_only : 1; + uint32_t reserved1 : 11; + /** specifies the search region width in pixels. + * When bidirectional search is enabled, this applies to both search regions */ + uint32_t ref_width : 8; + /** specifies the reference region height in pixels. When bidirectional search is enabled, + * this applies to both search regions. */ + uint32_t ref_height : 8; + /** \brief search window similar for AVC + * defines predefined search windows. If it is selected, RefWidth, RefHeight, LenSP and SearchPath are ignored. + * 0 : not use predefined search window + * 1 : Tiny – (4 SUs) 24x24 window diamond search + * 2 : Small – (9 SUs) 28x28 window diamond search + * 3 : Diamond – (16 SUs) 48x40 window diamond search + * 4 : Large Diamond – (32 SUs) 48x40 window diamond search + * 5 : Exhaustive – 48x40 window full search + * 6 : (64 SUs) 64x64 window full search + * Note: option 1, 2, 3 and 4 are valid only when CAP parameter SearchWindow64Support is 0. + * And option 6 is valid only when SearchWindow64Support is 1.*/ + uint32_t search_window : 8; + /** \brief number of internal MV predictors for IME searches */ + uint32_t max_num_ime_search_center : 3; + /** \brief fast intra prediction enabling bit. It is used as a trade-off between speed and quality. + * The flag will be ignored if it's unsupported in the driver*/ + uint32_t fast_intra_mode : 1; + uint32_t reserved2 : 4; + + /** \brief specifies number of splits that encoder could be run concurrently + * 1: level 1, default value + * 2: level 2 + * 4: level 3 + **/ + uint32_t num_concurrent_enc_frame_partition : 8; + uint32_t reserved3 : 24; + + /** \brief max frame size control with multi passes QP setting */ + uint32_t max_frame_size; + /** \brief number of passes, every pass has different QP */ + uint32_t num_passes; + /** \brief delta QP list for every pass */ + uint8_t *delta_qp; + + uint32_t reserved4[2]; +} VAEncMiscParameterFEIFrameControlHEVC; + +/** \brief Application can use this definition as reference to allocate the buffer + * based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query. + * this buffer allocation is always based on 16x16 block even block size is indicated as 32x32 or 64x64, and buffer + * layout is always in 32x32 block raster scan order even block size is 16x16 or 64x64. If 32x32 block size is set, + * only the data in the first 16x16 block (block 0) is used for 32x32 block. If 64x64 block size is set + * MV layout is still in 32x32 raster scan order, the same as 32x32 and the first 16x16 + * block within each 32x32 block needs to have intended MV data (four 32x32 blocks will have the same MV data in the + * correspondent first 16x16 block). Data structure for each 16x16 block is defined as below (same as AVC except + * BlockSize/Reserved bits). + **/ +typedef struct _VAEncFEIMVPredictorHEVC { + /** \brief Feference index corresponding to the entry of RefPicList0 & RefPicList1 in slice header (final reference + * list). Note that RefPicList0 & RefPicList1 needs to be the same for all slices. + * Ref0xIndex – RefPicList0; Ref1xIndex – RefPicList1; x – 0 ~ MaxNumPredictor */ + struct { + uint8_t ref_idx_l0 : 4; + uint8_t ref_idx_l1 : 4; + } ref_idx[4]; /* index is predictor number */ + /** \brief Valid only when MVPredictor is set to 011 for HEVC. Only valid in the first 16x16 block. + * 00: MV predictor disabled for this 32x32 block + * 01: MV predictor enabled per 16x16 block for this 32x32 block + * 10: MV predictor enabled per 32x32 block, the rest of 16x16 block data within this 32x32 block are ignored + * 11: Reserved */ + uint32_t block_size : 2; + uint32_t reserved : 30; + + VAMotionVector mv[4]; /* MaxNumPredictor is 4 */ +} VAEncFEIMVPredictorHEVC; //40 bytes + +/** \brief FEI CTB level control data structure */ +typedef struct _VAEncFEICTBControlHEVC { + // DWORD 0 + uint32_t force_to_intra : 1; + uint32_t force_to_inter : 1; + uint32_t force_to_skip : 1; + /** \brief force all coeff to zero */ + uint32_t force_to_zero_coeff : 1; + uint32_t reserved0 : 28; + // DWORD 1 + uint32_t reserved1; + // DWORD 2 + uint32_t reserved2; + // DWORD 3 + uint32_t reserved3; +} VAEncFEICTBControlHEVC; + +/** \brief VAEncFEIDistortionHevc defines the data structure for VAEncFEIDistortionBufferType per CTB block. + * It is output buffer of ENC and ENC_PAK modes, The CTB block is in raster scan order. + * Buffer size shall not be less than the number of CTB blocks multiple by sizeof(VAEncFEIDistortionHevc). + **/ +typedef struct _VAEncFEIDistortionHevc { + /** best CTB distortion */ + uint32_t best_distortion; + /** only when colocated_ctb_distortion in VAEncMiscParameterFEIFrameControlHEVC is set */ + uint32_t colocated_ctb_distortion; +} VAEncFEIDistortionHevc; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/rs/moq-vaapi/libva/va/va_internal.h b/rs/moq-vaapi/libva/va/va_internal.h new file mode 100644 index 00000000000..3a834f8bd3a --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_internal.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2017 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_INTERNAL_H +#define VA_INTERNAL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define CTX(dpy) (((VADisplayContextP)dpy)->pDriverContext) +#define CHECK_DISPLAY(dpy) if (!vaDisplayIsValid(dpy)) { return VA_STATUS_ERROR_INVALID_DISPLAY; } + +DLL_HIDDEN +void va_errorMessage(VADisplay dpy, const char *msg, ...); + +DLL_HIDDEN +void va_infoMessage(VADisplay dpy, const char *msg, ...); + +DLL_HIDDEN +int va_parseConfig(char *env, char *env_value); + +VADisplayContextP va_newDisplayContext(void); + +VADriverContextP va_newDriverContext(VADisplayContextP dctx); + +#ifdef __cplusplus +} +#endif + +#endif /* VA_INTERNAL_H */ diff --git a/rs/moq-vaapi/libva/va/va_prot.h b/rs/moq-vaapi/libva/va/va_prot.h new file mode 100644 index 00000000000..ab75a6d243b --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_prot.h @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2020 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_prot.h + * \brief Protected content API. + * + * This file contains the \ref api_prot "Protected content API". + */ + +#ifndef VA_PROT_H +#define VA_PROT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_prot Protected content API + * + * @{ + * \section prolouge Prolouge + * Video streaming is ubiquitous and the support for video streaming is widely + * available across client open systems such as PCs, MACs, Chromebooks etc. and + * closed systems such as settop box, smart TVs, DVDs etc. By default, + * video streaming is not considered premium due to various constraints such as + * resolution, quality, production cost etc. but recently streaming of premium + * video(1080p+) has become norm. The streaming of premium video in open systems + * such as PCs, MACs, Chromebooks etc. makes video particularly susceptible to + * piracy (due to non-video playback usages of such systems) resulting in + * millions of dollars of loss to content creators. + * + * Digital Rights Management(DRM) has been proposed to stop piracy of premium + * video streams across a wide spectrum. There are some known open/closed DRM + * standards such as [Widevine by Google](https://www.widevine.com/), + * [PlayReady by Microsoft](https://www.microsoft.com/playready/), + * [FairPlay by Apple](https://developer.apple.com/streaming/fps/), + * [Merlin by Sony](https://www.marlin-community.com/), etc... Each DRM + * standard has its properties but all DRM standards support a common + * mechanism. This common mechanism involves cryptographical method for + * authenticating the client system, delivering bitstream and required + * cryptographic assets to client system and then cryptographically processing + * bitstream in client system. The cryptographic methods used in these steps + * are asymmetric such as RSA, DH etc. and symmetric such as AES CTR, CBC etc. + * encryption mechanisms. The authentication of client system, delivery of + * bitstream and cryptographic assets to client system is performed using + * asymmetric cryptographic mechanism while bitstream is encrypted and processed + * using symmetric cryptographic. In DRM world, authentication of client system, + * delivery of bitstream and required cryptographic assets to client system is + * loosely called provisioning and license acquisition while the processing of + * cryptographically secure bitstream is divided as video decryption/decoding, + * audio decryption/playback, video display. Besides DRM standards, Video/Audio + * bitstream encryption standard such as + * [Common Encryption Standard(CENC)](https://www.iso.org/standard/76597.html) + * provides a mechanism to normalize bitstream encryption methods across vendors + * while providing flexibility. + * + * \section DRM Pipeline + * Most DRM standards execute the following deep pipeline to playback + * contents on client systems from streaming servers - provisioning uses + * provisioning servers, licence aquisition uses license servers, video + * bitstream delivery uses content servers and decryption/decoding, audio + * bitstream delivery uses content servers and decyption/playback, + * display/playback. The system level HWDRM sequence diagram is following - + * ![HWDRM sequence diagram](https://user-images.githubusercontent.com/75039699/102427278-df284e80-3fc5-11eb-9a3e-129b5f6b567a.png) + * and HWDRM pipeline view is following - + * ![HWDRM pipeline view](https://user-images.githubusercontent.com/75039699/102427357-04b55800-3fc6-11eb-8b8c-f34fc44ec061.png) + * + * \section LibVA Protected Content APIs + * The LibVA Protected APIs are designed to enable DRM capabilities or + * facilitate isolated communicaiton with TEE. + * The VAEntrypointProtectedTEEComm is to define interfaces for Application + * to TEE direct communication to perform various TEE centric operations + * such as standalone provisioning of platform at factory or provisioning + * TEE for other usages, providing TEE capabilities etc. + * The VAEntrypointProtectedContent is to define interfaces for protected + * video playback using HWDRM. This entry point co-ordinates assets across + * TEE/GPU/Display for HWDRM playback. + * + * The difference between Protected Content and Protected TEE Communication + * is that Protected Content Entrypoint does not provide isolated entry + * point for TEE and invokes TEE only from HWDRM perspective. + * + * Protected Content Entrypoint + * The most of DRM standards execute following deep pipeline to playback + * contents on client systems from streaming servers - provisioning uses + * provisioning servers, licence aquisition uses license servers, video + * bitstream delivery uses content servers and decryption/decoding, audio + * bitstream delivery uses content servers and decyption/playback, + * display/playback. + * + * The Provisioning and License aquisition implementations are Independent + * Hardware Vendor (IHV) specific but most IHVs use some form of Trusted + * Execution Environment (TEE) to prepare client platform or system for DRM + * content playback. The provisioning operations use provisioning servers (as + * instructed in DRM standard) and client system TEE. The communication between + * provisioning servers and client system TEE uses asymmetic cryptographic + * mechanism. This step provides a way to establish root-of-trust between + * client system and streaming servers. Once root-of-trust is established then + * client system requests for license aquisition for a particular streaming + * title. The license aquisition involves communication between licensing + * servers and TEE using asymmetic cryptographic mechanism. At end of this step, + * client system TEE has required assets to decrypt/decode. Although these + * communication does not direcly involve video aspect of GPU but **facilitate + * GPU required assets to playback premium contents**. + * + * To support DRM standard requirements in playback pipeline, OSes and HWs + * incorporate various methods to protect full playback pipeline. These + * methods of protection could be SW based or HW based. The SW based protection + * mechanism of DRMs is called SWDRM while HW based protection mechanism is + * called HWDRM. There is no previous support in LibVA to support either DRM + * mechanism. + * + * For DRM capabilities, APIs inolve creation of protected session to + * communicate with TEE and then using these protected sessions to process + * video/audio data. The philophashy behind these API is to leverage existing + * LibVA infrastructure as much as possible. + * + * Note: TEE could be any secure HW device such as ME-FW or FPGA Secure + * Enclave or NPU Secure Enclave. There are 2 concepts here – TEE Type such + * as ME-FW or FPGA or NPU; TEE Type Client such as for AMT or HDCP or + * something else etc. + * + * \section description Detailed Description + * The Protected content API provides a general mechanism for opening + * protected session with TEE and if required then \ref priming GPU/Display. + * The behavior of protected session API depends on parameterization/ + * configuration of protected session. Just for TEE tasks, protected + * session is parameterized/configured as TEE Communication while for + * HWDRM, protected session is parameterized/confgured as Protected + * Content. + * + * TEE Communication Entrypoint + * With TEE Communication parameterization/configuration, client + * executes TEE workloads in TEE with TEE Communication protected + * session. + * + * Protected Content Entrypoint + * With Protected Content parameterization/configuration, client + * executes HWDRM playback workloads HW accelerating protected video + * content decryption/decoding with protected content session. + * + * Before calling vaCreateProtectedSession, VAConfigID is obtained using + * existing libva mechanism to determine configuration parameters of + * protected session. The VAConfigID is determined in this way so that + * Protected Session implementation aligns with existing libva implementation. + * After obtaining VAConfigID, Protected Session needs to be created but + * note this is a session and not a context. Refer VAProtectedSessionID + * for more details. + * + * Note:- Protected session represents session object that has all security + * information needed for Secure Enclave to operate certain operations. + * + * \subsection priming Priming + * Priming is used to refer various types of initializations. For example, + * if license acquisition is being performed then priming means that TEE is + * already provisioned aka TEE has some sort of "cryptographic" whitelist of + * servers that TEE will use to do license acquisition for video playback. If + * HWDRM video playback is being performed then priming means that HWDRM + * eco-system TEE/GPU/Display has proper keys to do proper video playback etc. + * + * Protected content API uses the following paradigm for protected content + * session: + * - \ref api_pc_caps + * - \ref api_pc_setup + * - \ref api_pc_exec + * - \ref api_pc_attach + * + * \subsection api_pc_caps Query for supported cipher mode, block size, mode + * + * Checking whether protected content is supported can be performed with + * vaQueryConfigEntrypoints() and the profile argument set to + * #VAProfileProtected. If protected content is supported, then the list of + * returned entry-points will include #VAEntrypointProtectedContent + * + * \code + * VAEntrypoint *entrypoints; + * int i, num_entrypoints, supportsProtectedContent = 0; + * + * num_entrypoints = vaMaxNumEntrypoints(); + * entrypoints = malloc(num_entrypoints * sizeof(entrypoints[0]); + * vaQueryConfigEntrypoints(va_dpy, VAProfileProtected, entrypoints, + * &num_entrypoints); + * + * for (i = 0; !supportsProtectedContent && i < num_entrypoints; i++) { + * if (entrypoints[i] == VAEntrypointProtectedContent) + * supportsProtectedContent = 1; + * } + * \endcode + * + * Then, the vaGetConfigAttributes() function is used to query the protected + * session capabilities. + * + * \code + * VAConfigAttrib attribs; + * attribs[0].type = VAConfigAttribProtectedContentCipherAlgorithm; + * attribs[1].type = VAConfigAttribProtectedContentCipherBlockSize; + * attribs[2].type = VAConfigAttribProtectedContentCipherMode; + * attribs[3].type = VAConfigAttribProtectedContentCipherSampleType; + * attribs[4].type = VAConfigAttribProtectedContentUsage; + * vaGetConfigAttributes(va_dpy, VAProfileProtected, + * VAEntrypointProtectedContent, attribs, 5); + * if ((attribs[1].value & VA_PC_CIPHER_AES) == 0) { + * // not find desired cipher algorithm + * assert(0); + * } + * if ((attribs[2].value & VA_PC_BLOCK_SIZE_128) == 0) { + * // not find desired block size + * assert(0); + * } + * if ((attribs[3].value & VA_PC_CIPHER_MODE_CBC) == 0) { + * // not find desired counter mode + * assert(0); + * } + * if ((attribs[4].value & VA_PC_SAMPLE_TYPE_SUBSAMPLE) == 0) { + * // not find desired sample type + * assert(0); + * } + * if ((attribs[5].value & VA_PC_USAGE_WIDEVINE) == 0) { + * // not find desired usage + * assert(0); + * } + * \endcode + * + * \subsection api_pc_setup Set up a protected content session + * + * TEE Communication Entrypoint + * The protected content session provides a TEE session that is used to extract + * TEE information. This information could be used to peform TEE operations. + * + * Protected Content Entrypoint + * The protected content session can be attached to VA decode/encode/vp context + * to do decryption/protection in the pipeline. + * Before creating a protected content session, it needs to create a config + * first via vaCreateConfig(). Then using this config id to create a protected + * content session via vaCreateProtectedSession(). + * + * The general control flow is demonstrated by the following pseudo-code: + * \code + * // Create config + * VAConfigID config_id; + * + * attribs[0].value = VA_PC_CIPHER_AES; + * attribs[1].value = VA_PC_BLOCK_SIZE_128; + * attribs[2].value = VA_PC_CIPHER_MODE_CBC; + * attribs[3].value = VA_PC_SAMPLE_TYPE_SUBSAMPLE; + * attribs[4].value = VA_PC_USAGE_WIDEVINE; + * va_status = vaCreateConfig(va_dpy, VAProfileProtected, + * VAEntrypointProtectedContent, attribs, 5, &config_id); + * CHECK_VASTATUS(va_status, "vaCreateConfig"); + * \endcode + * + * Once the config is set up, we can create protected content session via + vaCreateProtectedSession(). + * \code + * // Create a protected session + * VAProtectedSessionID crypto_session; + * + * va_status = vaCreateProtectedSession(va_dpy, config_id, &crypto_session); + * CHECK_VASTATUS(va_status, "vaCreateProtectedSession"); + * \endcode + * + * \subsection api_pc_exec TEE communication via vaProtectedSessionExecute() + * + * TEE Communication Entrypoint + * App needs to communicate with TEE to get TEE information or \ref priming + * "prime" TEE with information that will be utilized for future TEE + * operations/tasks. + * + * Protected Content Entrypoint + * Before starting decryption/encryption operation in GPU, app may need to + * communicate with TEE to get encrypted assets for \ref priming HWDRM pipeline + * for decryption. App need to call vaProtectedSessionExecute() to get this + * asset. The following pseudo-code demonstrates getting session assets via + * vaProtectedSessionExecute() as an example. + * + * In this example, the vaCreateBuffer is called with exec_buffer mainly becasue TEE + * Communication Entrypoint buffers are CPU bound and buffer size is small enough to + * have extra copy operation without impacting performance. + * + * \code + * uint32_t app_id = 0xFF; + * VABufferID buffer; + * VAProtectedSessionExecuteBuffer exec_buff = {0}; + * + * exec_buff.function_id = GET_SESSION_ID; + * exec_buff.input.data = nullptr; + * exec_buff.input.data_size = 0; + * exec_buff.output.data = &app_id; + * exec_buff.output.max_data_size = sizeof(app_id); + * va_status = vaCreateBuffer( + * va_dpy, + * crypto_session, + * (VABufferType) VAProtectedSessionExecuteBufferType, + * sizeof(exec_buff), + * 1, + * &exec_buff, + * &buffer); + * + * va_status = vaProtectedSessionExecute(va_dpy, crypto_session, buffer); + * + * vaDestroyBuffer(va_dpy, buffer); + * \endcode + * + * \subsection api_pc_attach Attach/Detach protected content session to the VA + * context which want to enable/disable decryption/protection + * + * Protected content session is attached to VA decode/encode/vp context to + * enable protected decoding/encoding/video processing per frame or entire + * stream. If protected session attached per frame then application has 2 + * options for decoding/encoding skip processing i.e. accomodating clear + * frames - 1. Application could do detach after each frame is processed + * to process clear frame 2. Application could remains attached to decode/ + * encode session but specify enryption byte length to 0. + * The video processing does not has option #2 mainly because API does + * not provide skip processing. + * + * \code + * vaAttachProtectedSession(va_dpy, decode_ctx, crypto_session); + * foreach (iteration) { + * vaBeginPicture(va_dpy, decode_ctx, surface); + * ... + * vaRenderPicture(va_dpy, decode_ctx, &buf_id1, 1); + * vaRenderPicture(va_dpy, decode_ctx, &buf_id2, 1); + * // Buffer holding encryption parameters, i.e. VAEncryptionParameterBufferType buffer + * vaRenderPicture(va_dpy, decode_ctx, &buf_id_enc_param, 1); + * ... + * vaEndPicture(va_dpy, decode_ctx); + * } + * vaDetachProtectedSession(va_dpy, decode_ctx); + * \endcode + * + * or it could be frame-by-frame attaching/detaching as following: + * + * \code + * foreach (iteration) { + * if (encrypted) + * vaAttachProtectedSession(va_dpy, decode_ctx, crypto_session); + + * vaBeginPicture(va_dpy, decode_ctx, surface); + * ... + * vaRenderPicture(va_dpy, decode_ctx, &buf_id1, 1); + * vaRenderPicture(va_dpy, decode_ctx, &buf_id2, 1); + * // Buffer holding encryption parameters, i.e. VAEncryptionParameterBufferType buffer + * vaRenderPicture(va_dpy, decode_ctx, &buf_id_enc_param, 1); + * ... + * vaEndPicture(va_dpy, decode_ctx); + * + * if (encrypted) + * vaDetachProtectedSession(va_dpy, decode_ctx); + + * // check encrypted variable for next frame + * } + * \endcode + */ + +/** + * ProtectedSessions and Contexts + * + * According to #VAContextID, Context represents a "virtual" video decode, + * encode or video processing pipeline. Surfaces are render targets for a given + * context. The data in the surfaces are not accessible to the client except if + * derived image is supported and the internal data format of the surface is + * implementation specific. Application can create a video decode, encode or + * processing context which represents a "virtualized" hardware device. + * + * Since Protected Session does not virtualize any HW device or build any + * pipeline but rather accessorize existing virtualized HW device or pipeline + * to operate in protected mode so we decided to create separate function. + * Beside this, a virtualized HW device or pipeline could own several protected + * sessions and operate in those protected modes without ever re-creating + * virtualization of HW device or re-building HW pipeline (an unique protected + * environment multiplexing capability in Intel HW). + * + * The returned protected_session represents a notion of Host and TEE clients + * while representing protection status in GPU and Display. + * + * Both contexts and protected sessions are identified by unique IDs and its + * implementation specific internals are kept opaque to the clients + */ +typedef VAGenericID VAProtectedSessionID; + +/** \brief TEE Execucte Function ID. */ +typedef enum _VA_TEE_EXEC_FUNCTION_ID { + VA_TEE_EXECUTE_FUNCTION_ID_PASS_THROUGH = 0x00000001, + VA_TEE_EXECUTE_FUNCTION_ID_GET_FIRMWARE_VERSION = 0x00000002, + +} VA_TEE_EXECUTE_FUNCTION_ID; + +/** \brief Input/Output buffer of VAProtectedSessionExecuteBuffer */ +typedef struct _VAProtectedSessionBuffer { + /* + * This is used when this buffer refer to output buffer. The maximum size of + * data that the driver can return in the output buffer. It is not used for + * input buffer. + */ + uint32_t max_data_size; + /* + * If it is used for input buffer, it is the size of the input data. If it is + * used for output buffer, it is the returns size of the output data written + * by the driver. + */ + uint32_t data_size; + /* + * data pointer of this buffer + */ + void *data; + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProtectedSessionBuffer; + +/** \brief Buffer for vaProtectedSessionExecute() */ +typedef struct _VAProtectedSessionExecuteBuffer { + /** \brief Specify the function to execute. It is IHV's implementation + * specific */ + uint32_t function_id; + /** \brief Input buffer */ + VAProtectedSessionBuffer input; + /** \brief Output buffer */ + VAProtectedSessionBuffer output; + /** \brief Return the result of this function. The status result is IHV's + * implementation specific */ + uint32_t status; + /** \brief - vtag represents TEE sandbox identification for multiple playback scenario + * + * If TEE interface is created using VAEntrypointProtectedTEEComm then + * vtag is non-zero for multiple playback and vtag is zero for single playback + * + * If TEE interface is not created using VAEntrypointProtectedTEEComm then + * vtag - reserved + */ + uint64_t vtag; + /** \brief reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW - 2]; +} VAProtectedSessionExecuteBuffer; + +/** + * \brief Create a protected session + * + * Create a protected session + * + * @param[in] dpy the VA display + * @param[in] config_id configuration for the protected session + * @param[out] protected_session created protected session id upon return + */ +VAStatus vaCreateProtectedSession(VADisplay dpy, VAConfigID config_id, + VAProtectedSessionID *protected_session); + +/** + * \brief Destroy a protected session + * + * Destroy a protected session + * + * @param[in] dpy the VA display + * @param[in] protected_session protected session to be destroyed + */ +VAStatus vaDestroyProtectedSession(VADisplay dpy, + VAProtectedSessionID protected_session); + +/** + * \brief Attach a protected content session to VA context + * + * Attach a protected content session to the context to enable + * decryption/protection + * + * @param[in] dpy the VA display + * @param[in] id the VA decode/encode/vp context + * @param[in] protected_session the protected session to attach + */ +VAStatus vaAttachProtectedSession(VADisplay dpy, VAGenericID id, + VAProtectedSessionID protected_session); + +/** + * \brief Detach the protected content session from the VA context + * + * Detach protected content session of the context to disable + * decryption/protection + * + * @param[in] dpy the VA display + * @param[in] id TEE client id to be detached + */ +VAStatus vaDetachProtectedSession(VADisplay dpy, VAGenericID id); + +/** + * \brief Execute provides a general mechanism for TEE client tasks execution. + * + * vaProtectedSessionExecute provides a mechanism for TEE clients to execute + * specific tasks. The implementation may differ between IHVs. + * This is a synchronous API. + * + * @param[in] dpy the VA display + * @param[in] protected_session the protected session + * @param[in,out] buf_id the VA buffer + */ +VAStatus vaProtectedSessionExecute(VADisplay dpy, + VAProtectedSessionID protected_session, + VABufferID buf_id); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_PROT_H */ diff --git a/rs/moq-vaapi/libva/va/va_str.h b/rs/moq-vaapi/libva/va/va_str.h new file mode 100644 index 00000000000..1bfe5834ba7 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_str.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef _VA_STR_H_ +#define _VA_STR_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +const char *vaProfileStr(VAProfile profile); + +const char *vaEntrypointStr(VAEntrypoint entrypoint); + +const char *vaConfigAttribTypeStr(VAConfigAttribType configAttribType); + +const char *vaBufferTypeStr(VABufferType bufferType); + +const char *vaStatusStr(VAStatus status); + +#ifdef __cplusplus +} +#endif + +#endif /* _VA_STR_H_ */ diff --git a/rs/moq-vaapi/libva/va/va_tpi.h b/rs/moq-vaapi/libva/va/va_tpi.h new file mode 100644 index 00000000000..fb165adee63 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_tpi.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2007-2009 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef _VA_TPI_H_ +#define _VA_TPI_H_ + +#warning The APIs / data structures included in this file are deprecated + +#endif diff --git a/rs/moq-vaapi/libva/va/va_trace.h b/rs/moq-vaapi/libva/va/va_trace.h new file mode 100644 index 00000000000..8fa46b59699 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_trace.h @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2009 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_TRACE_H +#define VA_TRACE_H + +#ifdef __cplusplus +extern "C" { +#endif + +extern int va_trace_flag; + +#define VA_TRACE_FLAG_LOG 0x1 +#define VA_TRACE_FLAG_BUFDATA 0x2 +#define VA_TRACE_FLAG_CODEDBUF 0x4 +#define VA_TRACE_FLAG_SURFACE_DECODE 0x8 +#define VA_TRACE_FLAG_SURFACE_ENCODE 0x10 +#define VA_TRACE_FLAG_SURFACE_JPEG 0x20 +#define VA_TRACE_FLAG_SURFACE_VPPOUT 0x80 + +#define VA_TRACE_FLAG_SURFACE (VA_TRACE_FLAG_SURFACE_DECODE | \ + VA_TRACE_FLAG_SURFACE_ENCODE | \ + VA_TRACE_FLAG_SURFACE_JPEG) +#define VA_TRACE_FLAG_FTRACE 0x40 +#define VA_TRACE_FLAG_FTRACE_BUFDATA (VA_TRACE_FLAG_FTRACE | \ + VA_TRACE_FLAG_BUFDATA) + + +#define VA_TRACE_LOG(trace_func,...) \ + if (va_trace_flag & VA_TRACE_FLAG_LOG) { \ + trace_func(__VA_ARGS__); \ + } +#define VA_TRACE_ALL(trace_func,...) \ + if (va_trace_flag) { \ + trace_func(__VA_ARGS__); \ + } +#define VA_TRACE_RET(dpy,ret) \ + if (va_trace_flag){ \ + va_TraceStatus(dpy, __func__, ret); \ + } + +/** \brief event id definition + * identifier of trace event, coresponding the task value in the manifest, located in libva-util/tracetool + * the trace tool will translate this id to event name, also the trace data carried along. + * Note: make sure event id definition backward compatible */ +enum { + INVALIDE_ID = 0, + CREATE_CONFIG = 1, + DESTROY_CONFIG, + CREATE_CONTEXT, + DESTROY_CONTEXT, + CREATE_BUFFER, + DESTROY_BUFFER, + CREATE_SURFACE, + DESTROY_SURFACE, + BEGIN_PICTURE, + RENDER_PICTURE, + END_PICTURE, + BUFFER_DATA, + SYNC_SURFACE, + SYNC_SURFACE2, + QUERY_SURFACE_ATTR, +}; + +/** \brief event opcode definition + * identifier of trace event operation, coresponding the opcode value in the manifest. + * 4 predefined opcode */ +#define TRACE_INFO 0 +#define TRACE_BEGIN 1 +#define TRACE_END 2 +#define TRACE_DATA 3 + +/** \brief event data structure + * structure list to pass event data without copy, each entry contain the event data address and size. + * va_TraceEvent will write these raw data into ftrace entry */ +typedef struct va_event_data { + void *buf; + unsigned int size; +} VAEventData; + + +/** \brief VA_TRACE + * trace interface to send out trace event with empty event data. */ +#define VA_TRACE(dpy,id,op) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + va_TraceEvent(dpy, id, op, 0, NULL); \ + } \ + } while (0) +/** \brief VA_TRACE_V + * trace interface to send out trace event with 1 data element from variable. the variable data type could be 8/16/32/64 bitsize */ +#define VA_TRACE_V(dpy,id,op,v) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + VAEventData desc[1] = {{&v, sizeof(v)}}; \ + va_TraceEvent(dpy, id, op, 1, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_PV + * trace interface to send out trace event with 2 data element, from pointer and variable. their data size could be 8/16/32/64 bitsize */ +#define VA_TRACE_PV(dpy,id,op,p,v) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + VAEventData desc[2] = {{p, sizeof(*p)}, \ + {&v, sizeof(v)}}; \ + va_TraceEvent(dpy, id, op, 2, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VV + * trace interface to send out trace event with 2 data element, both from variable. their data size could be 8/16/32/64 bitsize */ +#define VA_TRACE_VV(dpy,id,op,v1,v2) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + VAEventData desc[2] = {{&v1, sizeof(v1)}, \ + {&v2, sizeof(v2)}}; \ + va_TraceEvent(dpy, id, op, 2, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VVVV + * trace interface to send out trace event with 4 data element, all from variable. their data size could be 8/16/32/64 bitsize */ +#define VA_TRACE_VVVV(dpy,id,op,v1,v2,v3,v4) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + VAEventData desc[4] = { {&v1, sizeof(v1)}, \ + {&v2, sizeof(v2)}, \ + {&v3, sizeof(v3)}, \ + {&v4, sizeof(v4)}}; \ + va_TraceEvent(dpy, id, op, 4, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VA + * trace interface to send out trace event with a dynamic length array data element, array length from variable. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_VA(dpy,id,op,n,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = n | sizeof(*a) << 16; \ + VAEventData desc[2] = {{&num, sizeof(num)}, \ + {a, n * sizeof(*a)}}; \ + va_TraceEvent(dpy, id, op, 2, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_PA + * trace interface to send out trace event with a dynamic length array data element, array length from pointer. need check null before set. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_PA(dpy,id,op,pn,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = sizeof(*a) << 16; \ + VAEventData desc[2] = {{&num, sizeof(num)}, \ + {a, 0}}; \ + if (pn) { \ + num |= *pn; \ + desc[1].size = (*pn) * sizeof(*a); \ + } \ + va_TraceEvent(dpy, id, op, 2, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VVA + * trace interface to send out trace event with 1 data element and a dynamic length array data element, array length from variable. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_VVA(dpy,id,op,v,n,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = n | (sizeof(*a) << 16); \ + VAEventData desc[3] = {{&v, sizeof(v)}, \ + {&num, sizeof(num)}, \ + {a, n*sizeof(*a)}}; \ + va_TraceEvent(dpy, id, op, 3, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VVVA + * trace interface to send out trace event with 2 data element and a dynamic length array data element, array length from variable. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_VVVA(dpy,id,op,v1,v2,n,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = n | (sizeof(*a) << 16); \ + VAEventData desc[4] = {{&v1, sizeof(v1)}, \ + {&v2, sizeof(v2)}, \ + {&num, sizeof(num)}, \ + {a, n*sizeof(*a)}}; \ + va_TraceEvent(dpy, id, op, 4, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VVVVA + * trace interface to send out trace event with 3 data element and a dynamic length array data element, array length from variable. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_VVVVA(dpy,id,op,v1,v2,v3,n,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = n | (sizeof(*a) << 16); \ + VAEventData desc[5] = {{&v1, sizeof(v1)}, \ + {&v2, sizeof(v2)}, \ + {&v3, sizeof(v3)}, \ + {&num, sizeof(num)}, \ + {a, n*sizeof(*a)}}; \ + va_TraceEvent(dpy, id, op, 5, desc); \ + } \ + } while (0) +/** \brief VA_TRACE_VVVVVA + * trace interface to send out trace event with 4 data elsement and a dynamic length array data element, array length from variable. + * high 16bits of array length is used to set bitssize of array element. */ +#define VA_TRACE_VVVVVA(dpy,id,op,v1,v2,v3,v4,n,a) do { \ + if (va_trace_flag & VA_TRACE_FLAG_FTRACE) { \ + int num = n | (sizeof(*a) << 16); \ + VAEventData desc[6] = {{&v1, sizeof(v1)}, \ + {&v2, sizeof(v2)}, \ + {&v3, sizeof(v3)}, \ + {&v4, sizeof(v4)}, \ + {&num, sizeof(num)}, \ + {a, n*sizeof(*a)}}; \ + va_TraceEvent(dpy, id, op, 6, desc); \ + } \ + } while (0) + +/* add macro interface to support new data type combination */ + + +/** \brief VA_TRACE_BUFFERS + * trace interface to dump all data in va buffer ids into trace. + * libva-utils will parse buffer into fields according to buffer type */ +#define VA_TRACE_BUFFERS(dpy,ctx,num,buffers) do { \ + if ((va_trace_flag & VA_TRACE_FLAG_FTRACE_BUFDATA) == VA_TRACE_FLAG_FTRACE_BUFDATA) { \ + va_TraceEventBuffers(dpy, ctx, num, buffers); \ + } \ + } while (0) + +DLL_HIDDEN +void va_TraceInit(VADisplay dpy); +DLL_HIDDEN +void va_TraceEnd(VADisplay dpy); + +DLL_HIDDEN +void va_TraceInitialize( + VADisplay dpy, + int *major_version, /* out */ + int *minor_version /* out */ +); + +DLL_HIDDEN +void va_TraceTerminate( + VADisplay dpy +); + +DLL_HIDDEN +void va_TraceCreateConfig( + VADisplay dpy, + VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, + int num_attribs, + VAConfigID *config_id /* out */ +); + +DLL_HIDDEN +void va_TraceDestroyConfig( + VADisplay dpy, + VAConfigID config_id +); + +DLL_HIDDEN +void va_TraceCreateSurfaces( + VADisplay dpy, + int width, + int height, + int format, + int num_surfaces, + VASurfaceID *surfaces, /* out */ + VASurfaceAttrib *attrib_list, + unsigned int num_attribs +); + +DLL_HIDDEN +void va_TraceDestroySurfaces( + VADisplay dpy, + VASurfaceID *surface_list, + int num_surfaces +); + +DLL_HIDDEN +void va_TraceCreateContext( + VADisplay dpy, + VAConfigID config_id, + int picture_width, + int picture_height, + int flag, + VASurfaceID *render_targets, + int num_render_targets, + VAContextID *context /* out */ +); + +DLL_HIDDEN +void va_TraceDestroyContext( + VADisplay dpy, + VAContextID context +); + +DLL_HIDDEN +void va_TraceCreateMFContext( + VADisplay dpy, + VAContextID *mf_context /* out */ +); + +DLL_HIDDEN +void va_TraceMFAddContext( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID context +); + +DLL_HIDDEN +void va_TraceMFReleaseContext( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID context +); + +DLL_HIDDEN +void va_TraceMFSubmit( + VADisplay dpy, + VAMFContextID mf_context, + VAContextID *contexts, + int num_contexts +); + +DLL_HIDDEN +void va_TraceCreateBuffer( + VADisplay dpy, + VAContextID context, /* in */ + VABufferType type, /* in */ + unsigned int size, /* in */ + unsigned int num_elements, /* in */ + void *data, /* in */ + VABufferID *buf_id /* out */ +); + +DLL_HIDDEN +void va_TraceDestroyBuffer( + VADisplay dpy, + VABufferID buf_id /* in */ +); + +DLL_HIDDEN +void va_TraceMapBuffer( + VADisplay dpy, + VABufferID buf_id, /* in */ + void **pbuf, /* out */ + uint32_t flags /* in */ +); + + +DLL_HIDDEN +void va_TraceBeginPicture( + VADisplay dpy, + VAContextID context, + VASurfaceID render_target +); + +DLL_HIDDEN +void va_TraceRenderPicture( + VADisplay dpy, + VAContextID context, + VABufferID *buffers, + int num_buffers +); + +DLL_HIDDEN +void va_TraceEndPicture( + VADisplay dpy, + VAContextID context, + int endpic_done +); + +DLL_HIDDEN +void va_TraceEndPictureExt( + VADisplay dpy, + VAContextID context, + int endpic_done +); + +DLL_HIDDEN +void va_TraceSyncSurface( + VADisplay dpy, + VASurfaceID render_target +); + +DLL_HIDDEN +void va_TraceSyncSurface2( + VADisplay dpy, + VASurfaceID surface, + uint64_t timeout_ns +); + +DLL_HIDDEN +void va_TraceQuerySurfaceAttributes( + VADisplay dpy, + VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int *num_attribs +); + +DLL_HIDDEN +void va_TraceQuerySurfaceStatus( + VADisplay dpy, + VASurfaceID render_target, + VASurfaceStatus *status /* out */ +); + +DLL_HIDDEN +void va_TraceQuerySurfaceError( + VADisplay dpy, + VASurfaceID surface, + VAStatus error_status, + void **error_info /*out*/ +); + +DLL_HIDDEN +void va_TraceSyncBuffer( + VADisplay dpy, + VABufferID buf_id, + uint64_t timeout_ns +); + +DLL_HIDDEN +void va_TraceMaxNumDisplayAttributes( + VADisplay dpy, + int number +); + +DLL_HIDDEN +void va_TraceQueryDisplayAttributes( + VADisplay dpy, + VADisplayAttribute *attr_list, /* out */ + int *num_attributes /* out */ +); + +DLL_HIDDEN +void va_TraceGetDisplayAttributes( + VADisplay dpy, + VADisplayAttribute *attr_list, + int num_attributes +); + +DLL_HIDDEN +void va_TraceSetDisplayAttributes( + VADisplay dpy, + VADisplayAttribute *attr_list, + int num_attributes +); + +/* extern function called by display side */ +void va_TracePutSurface( + VADisplay dpy, + VASurfaceID surface, + void *draw, /* the target Drawable */ + short srcx, + short srcy, + unsigned short srcw, + unsigned short srch, + short destx, + short desty, + unsigned short destw, + unsigned short desth, + VARectangle *cliprects, /* client supplied clip list */ + unsigned int number_cliprects, /* number of clip rects in the clip list */ + unsigned int flags /* de-interlacing flags */ +); + +void va_TraceStatus(VADisplay dpy, const char * funcName, VAStatus status); + +/** \brief va_TraceEvent + * common trace interface to send out trace event with scatterd event data. */ +DLL_HIDDEN +void va_TraceEvent( + VADisplay dpy, + unsigned short id, + unsigned short opcode, + unsigned int num, + VAEventData *desc); + +/** \brief va_TraceEventBuffers + * trace buffer interface to send out data in buffers. */ +DLL_HIDDEN +void va_TraceEventBuffers( + VADisplay dpy, + VAContextID context, + int num_buffers, + VABufferID *buffers); + +/** \brief va_TraceExportSurfaceHandle + * trace exported surface handle. */ +DLL_HIDDEN +void va_TraceExportSurfaceHandle( + VADisplay dpy, + VASurfaceID surfaceId, + uint32_t memType, + uint32_t flags, + void *descriptor); + +/** \brief va_TraceDeriveImage + * trace derive image */ +DLL_HIDDEN +void va_TraceDeriveImage( + VADisplay dpy, + VASurfaceID surface, + VAImage *image); + +#ifdef __cplusplus +} +#endif + + +#endif /* VA_TRACE_H */ diff --git a/rs/moq-vaapi/libva/va/va_version.h.in b/rs/moq-vaapi/libva/va/va_version.h.in new file mode 100644 index 00000000000..0cc5ea7c1b1 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_version.h.in @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2009 Splitted-Desktop Systems. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef VA_VERSION_H +#define VA_VERSION_H + +/** + * VA_MAJOR_VERSION: + * + * The major version of VA-API (1, if %VA_VERSION is 1.2.3) + */ +#define VA_MAJOR_VERSION @VA_API_MAJOR_VERSION@ + +/** + * VA_MINOR_VERSION: + * + * The minor version of VA-API (2, if %VA_VERSION is 1.2.3) + */ +#define VA_MINOR_VERSION @VA_API_MINOR_VERSION@ + +/** + * VA_MICRO_VERSION: + * + * The micro version of VA-API (3, if %VA_VERSION is 1.2.3) + */ +#define VA_MICRO_VERSION @VA_API_MICRO_VERSION@ + +/** + * VA_VERSION: + * + * The full version of VA-API, like 1.2.3 + */ +#define VA_VERSION @VA_API_VERSION@ + +/** + * VA_VERSION_S: + * + * The full version of VA-API, in string form (suited for string + * concatenation) + */ +#define VA_VERSION_S "@VA_API_VERSION@" + +/** + * VA_VERSION_HEX: + * + * Numerically encoded version of VA-API, like 0x010203 + */ +#define VA_VERSION_HEX ((VA_MAJOR_VERSION << 24) | \ + (VA_MINOR_VERSION << 16) | \ + (VA_MICRO_VERSION << 8)) + +/** + * VA_CHECK_VERSION: + * @major: major version, like 1 in 1.2.3 + * @minor: minor version, like 2 in 1.2.3 + * @micro: micro version, like 3 in 1.2.3 + * + * Evaluates to %TRUE if the version of VA-API is greater than + * @major, @minor and @micro + */ +#define VA_CHECK_VERSION(major,minor,micro) \ + (VA_MAJOR_VERSION > (major) || \ + (VA_MAJOR_VERSION == (major) && VA_MINOR_VERSION > (minor)) || \ + (VA_MAJOR_VERSION == (major) && VA_MINOR_VERSION == (minor) && VA_MICRO_VERSION >= (micro))) + +#endif /* VA_VERSION_H */ diff --git a/rs/moq-vaapi/libva/va/va_vpp.h b/rs/moq-vaapi/libva/va/va_vpp.h new file mode 100644 index 00000000000..586497e3f92 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_vpp.h @@ -0,0 +1,1590 @@ +/* + * Copyright (c) 2007-2011 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file va_vpp.h + * \brief The video processing API + * + * This file contains the \ref api_vpp "Video processing API". + */ + +#ifndef VA_VPP_H +#define VA_VPP_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \defgroup api_vpp Video processing API + * + * @{ + * + * The video processing API uses the same paradigm as for decoding: + * - Query for supported filters; + * - Set up a video processing pipeline; + * - Send video processing parameters through VA buffers. + * + * \section api_vpp_caps Query for supported filters + * + * Checking whether video processing is supported can be performed + * with vaQueryConfigEntrypoints() and the profile argument set to + * #VAProfileNone. If video processing is supported, then the list of + * returned entry-points will include #VAEntrypointVideoProc. + * + * \code + * VAEntrypoint *entrypoints; + * int i, num_entrypoints, supportsVideoProcessing = 0; + * + * num_entrypoints = vaMaxNumEntrypoints(); + * entrypoints = malloc(num_entrypoints * sizeof(entrypoints[0]); + * vaQueryConfigEntrypoints(va_dpy, VAProfileNone, + * entrypoints, &num_entrypoints); + * + * for (i = 0; !supportsVideoProcessing && i < num_entrypoints; i++) { + * if (entrypoints[i] == VAEntrypointVideoProc) + * supportsVideoProcessing = 1; + * } + * \endcode + * + * Then, the vaQueryVideoProcFilters() function is used to query the + * list of video processing filters. + * + * \code + * VAProcFilterType filters[VAProcFilterCount]; + * unsigned int num_filters = VAProcFilterCount; + * + * // num_filters shall be initialized to the length of the array + * vaQueryVideoProcFilters(va_dpy, vpp_ctx, &filters, &num_filters); + * \endcode + * + * Finally, individual filter capabilities can be checked with + * vaQueryVideoProcFilterCaps(). + * + * \code + * VAProcFilterCap denoise_caps; + * unsigned int num_denoise_caps = 1; + * vaQueryVideoProcFilterCaps(va_dpy, vpp_ctx, + * VAProcFilterNoiseReduction, + * &denoise_caps, &num_denoise_caps + * ); + * + * VAProcFilterCapDeinterlacing deinterlacing_caps[VAProcDeinterlacingCount]; + * unsigned int num_deinterlacing_caps = VAProcDeinterlacingCount; + * vaQueryVideoProcFilterCaps(va_dpy, vpp_ctx, + * VAProcFilterDeinterlacing, + * &deinterlacing_caps, &num_deinterlacing_caps + * ); + * \endcode + * + * \section api_vpp_setup Set up a video processing pipeline + * + * A video processing pipeline buffer is created for each source + * surface we want to process. However, buffers holding filter + * parameters can be created once and for all. Rationale is to avoid + * multiple creation/destruction chains of filter buffers and also + * because filter parameters generally won't change frame after + * frame. e.g. this makes it possible to implement a checkerboard of + * videos where the same filters are applied to each video source. + * + * The general control flow is demonstrated by the following pseudo-code: + * \code + * // Create filters + * VABufferID denoise_filter, deint_filter; + * VABufferID filter_bufs[VAProcFilterCount]; + * unsigned int num_filter_bufs; + * + * for (i = 0; i < num_filters; i++) { + * switch (filters[i]) { + * case VAProcFilterNoiseReduction: { // Noise reduction filter + * VAProcFilterParameterBuffer denoise; + * denoise.type = VAProcFilterNoiseReduction; + * denoise.value = 0.5; + * vaCreateBuffer(va_dpy, vpp_ctx, + * VAProcFilterParameterBufferType, sizeof(denoise), 1, + * &denoise, &denoise_filter + * ); + * filter_bufs[num_filter_bufs++] = denoise_filter; + * break; + * } + * + * case VAProcFilterDeinterlacing: // Motion-adaptive deinterlacing + * for (j = 0; j < num_deinterlacing_caps; j++) { + * VAProcFilterCapDeinterlacing * const cap = &deinterlacing_caps[j]; + * if (cap->type != VAProcDeinterlacingMotionAdaptive) + * continue; + * + * VAProcFilterParameterBufferDeinterlacing deint; + * deint.type = VAProcFilterDeinterlacing; + * deint.algorithm = VAProcDeinterlacingMotionAdaptive; + * vaCreateBuffer(va_dpy, vpp_ctx, + * VAProcFilterParameterBufferType, sizeof(deint), 1, + * &deint, &deint_filter + * ); + * filter_bufs[num_filter_bufs++] = deint_filter; + * } + * } + * } + * \endcode + * + * Once the video processing pipeline is set up, the caller shall check the + * implied capabilities and requirements with vaQueryVideoProcPipelineCaps(). + * This function can be used to validate the number of reference frames are + * needed by the specified deinterlacing algorithm, the supported color + * primaries, etc. + * \code + * // Create filters + * VAProcPipelineCaps pipeline_caps; + * VASurfaceID *forward_references; + * unsigned int num_forward_references; + * VASurfaceID *backward_references; + * unsigned int num_backward_references; + * VAProcColorStandardType in_color_standards[VAProcColorStandardCount]; + * VAProcColorStandardType out_color_standards[VAProcColorStandardCount]; + * + * pipeline_caps.input_color_standards = NULL; + * pipeline_caps.num_input_color_standards = ARRAY_ELEMS(in_color_standards); + * pipeline_caps.output_color_standards = NULL; + * pipeline_caps.num_output_color_standards = ARRAY_ELEMS(out_color_standards); + * vaQueryVideoProcPipelineCaps(va_dpy, vpp_ctx, + * filter_bufs, num_filter_bufs, + * &pipeline_caps + * ); + * + * num_forward_references = pipeline_caps.num_forward_references; + * forward_references = + * malloc(num__forward_references * sizeof(VASurfaceID)); + * num_backward_references = pipeline_caps.num_backward_references; + * backward_references = + * malloc(num_backward_references * sizeof(VASurfaceID)); + * \endcode + * + * \section api_vpp_submit Send video processing parameters through VA buffers + * + * Video processing pipeline parameters are submitted for each source + * surface to process. Video filter parameters can also change, per-surface. + * e.g. the list of reference frames used for deinterlacing. + * + * \code + * foreach (iteration) { + * vaBeginPicture(va_dpy, vpp_ctx, vpp_surface); + * foreach (surface) { + * VARectangle output_region; + * VABufferID pipeline_buf; + * VAProcPipelineParameterBuffer *pipeline_param; + * + * vaCreateBuffer(va_dpy, vpp_ctx, + * VAProcPipelineParameterBuffer, sizeof(*pipeline_param), 1, + * NULL, &pipeline_buf + * ); + * + * // Setup output region for this surface + * // e.g. upper left corner for the first surface + * output_region.x = BORDER; + * output_region.y = BORDER; + * output_region.width = + * (vpp_surface_width - (Nx_surfaces + 1) * BORDER) / Nx_surfaces; + * output_region.height = + * (vpp_surface_height - (Ny_surfaces + 1) * BORDER) / Ny_surfaces; + * + * vaMapBuffer(va_dpy, pipeline_buf, &pipeline_param); + * pipeline_param->surface = surface; + * pipeline_param->surface_region = NULL; + * pipeline_param->output_region = &output_region; + * pipeline_param->output_background_color = 0; + * if (first surface to render) + * pipeline_param->output_background_color = 0xff000000; // black + * pipeline_param->filter_flags = VA_FILTER_SCALING_HQ; + * pipeline_param->filters = filter_bufs; + * pipeline_param->num_filters = num_filter_bufs; + * vaUnmapBuffer(va_dpy, pipeline_buf); + * + * // Update reference frames for deinterlacing, if necessary + * pipeline_param->forward_references = forward_references; + * pipeline_param->num_forward_references = num_forward_references_used; + * pipeline_param->backward_references = backward_references; + * pipeline_param->num_backward_references = num_bacward_references_used; + * + * // Apply filters + * vaRenderPicture(va_dpy, vpp_ctx, &pipeline_buf, 1); + * } + * vaEndPicture(va_dpy, vpp_ctx); + * } + * \endcode + */ + +/** \brief Video filter types. */ +typedef enum _VAProcFilterType { + VAProcFilterNone = 0, + /** \brief Noise reduction filter. */ + VAProcFilterNoiseReduction, + /** \brief Deinterlacing filter. */ + VAProcFilterDeinterlacing, + /** \brief Sharpening filter. */ + VAProcFilterSharpening, + /** \brief Color balance parameters. */ + VAProcFilterColorBalance, + /** \brief Skin Tone Enhancement. */ + VAProcFilterSkinToneEnhancement, + /** \brief Total Color Correction. */ + VAProcFilterTotalColorCorrection, + /** \brief Human Vision System(HVS) Noise reduction filter. */ + VAProcFilterHVSNoiseReduction, + /** \brief High Dynamic Range Tone Mapping. */ + VAProcFilterHighDynamicRangeToneMapping, + /** \brief Three-Dimensional Look Up Table (3DLUT). */ + VAProcFilter3DLUT, + /** \brief Number of video filters. */ + VAProcFilterCount +} VAProcFilterType; + +/** \brief Deinterlacing types. */ +typedef enum _VAProcDeinterlacingType { + VAProcDeinterlacingNone = 0, + /** \brief Bob deinterlacing algorithm. */ + VAProcDeinterlacingBob, + /** \brief Weave deinterlacing algorithm. */ + VAProcDeinterlacingWeave, + /** \brief Motion adaptive deinterlacing algorithm. */ + VAProcDeinterlacingMotionAdaptive, + /** \brief Motion compensated deinterlacing algorithm. */ + VAProcDeinterlacingMotionCompensated, + /** \brief Number of deinterlacing algorithms. */ + VAProcDeinterlacingCount +} VAProcDeinterlacingType; + +/** \brief Color balance types. */ +typedef enum _VAProcColorBalanceType { + VAProcColorBalanceNone = 0, + /** \brief Hue. */ + VAProcColorBalanceHue, + /** \brief Saturation. */ + VAProcColorBalanceSaturation, + /** \brief Brightness. */ + VAProcColorBalanceBrightness, + /** \brief Contrast. */ + VAProcColorBalanceContrast, + /** \brief Automatically adjusted saturation. */ + VAProcColorBalanceAutoSaturation, + /** \brief Automatically adjusted brightness. */ + VAProcColorBalanceAutoBrightness, + /** \brief Automatically adjusted contrast. */ + VAProcColorBalanceAutoContrast, + /** \brief Number of color balance attributes. */ + VAProcColorBalanceCount +} VAProcColorBalanceType; + +/** \brief Color standard types. + * + * These define a set of color properties corresponding to particular + * video standards. + * + * Where matrix_coefficients is specified, it applies only to YUV data - + * RGB data always use the identity matrix (matrix_coefficients = 0). + */ +typedef enum _VAProcColorStandardType { + VAProcColorStandardNone = 0, + /** \brief ITU-R BT.601. + * + * It is unspecified whether this will use 525-line or 625-line values; + * specify the colour primaries and matrix coefficients explicitly if + * it is known which one is required. + * + * Equivalent to: + * colour_primaries = 5 or 6 + * transfer_characteristics = 6 + * matrix_coefficients = 5 or 6 + */ + VAProcColorStandardBT601, + /** \brief ITU-R BT.709. + * + * Equivalent to: + * colour_primaries = 1 + * transfer_characteristics = 1 + * matrix_coefficients = 1 + */ + VAProcColorStandardBT709, + /** \brief ITU-R BT.470-2 System M. + * + * Equivalent to: + * colour_primaries = 4 + * transfer_characteristics = 4 + * matrix_coefficients = 4 + */ + VAProcColorStandardBT470M, + /** \brief ITU-R BT.470-2 System B, G. + * + * Equivalent to: + * colour_primaries = 5 + * transfer_characteristics = 5 + * matrix_coefficients = 5 + */ + VAProcColorStandardBT470BG, + /** \brief SMPTE-170M. + * + * Equivalent to: + * colour_primaries = 6 + * transfer_characteristics = 6 + * matrix_coefficients = 6 + */ + VAProcColorStandardSMPTE170M, + /** \brief SMPTE-240M. + * + * Equivalent to: + * colour_primaries = 7 + * transfer_characteristics = 7 + * matrix_coefficients = 7 + */ + VAProcColorStandardSMPTE240M, + /** \brief Generic film. + * + * Equivalent to: + * colour_primaries = 8 + * transfer_characteristics = 1 + * matrix_coefficients = 1 + */ + VAProcColorStandardGenericFilm, + /** \brief sRGB. + * + * Equivalent to: + * colour_primaries = 1 + * transfer_characteristics = 13 + * matrix_coefficients = 0 + */ + VAProcColorStandardSRGB, + /** \brief stRGB. + * + * ??? + */ + VAProcColorStandardSTRGB, + /** \brief xvYCC601. + * + * Equivalent to: + * colour_primaries = 1 + * transfer_characteristics = 11 + * matrix_coefficients = 5 + */ + VAProcColorStandardXVYCC601, + /** \brief xvYCC709. + * + * Equivalent to: + * colour_primaries = 1 + * transfer_characteristics = 11 + * matrix_coefficients = 1 + */ + VAProcColorStandardXVYCC709, + /** \brief ITU-R BT.2020. + * + * Equivalent to: + * colour_primaries = 9 + * transfer_characteristics = 14 + * matrix_coefficients = 9 + */ + VAProcColorStandardBT2020, + /** \brief Explicitly specified color properties. + * + * Use corresponding color properties section. + * For example, HDR10 content: + * colour_primaries = 9 (BT2020) + * transfer_characteristics = 16 (SMPTE ST2084) + * matrix_coefficients = 9 + */ + VAProcColorStandardExplicit, + /** \brief Number of color standards. */ + VAProcColorStandardCount +} VAProcColorStandardType; + +/** \brief Total color correction types. */ +typedef enum _VAProcTotalColorCorrectionType { + VAProcTotalColorCorrectionNone = 0, + /** \brief Red Saturation. */ + VAProcTotalColorCorrectionRed, + /** \brief Green Saturation. */ + VAProcTotalColorCorrectionGreen, + /** \brief Blue Saturation. */ + VAProcTotalColorCorrectionBlue, + /** \brief Cyan Saturation. */ + VAProcTotalColorCorrectionCyan, + /** \brief Magenta Saturation. */ + VAProcTotalColorCorrectionMagenta, + /** \brief Yellow Saturation. */ + VAProcTotalColorCorrectionYellow, + /** \brief Number of color correction attributes. */ + VAProcTotalColorCorrectionCount +} VAProcTotalColorCorrectionType; + +/** \brief High Dynamic Range Metadata types. */ +typedef enum _VAProcHighDynamicRangeMetadataType { + VAProcHighDynamicRangeMetadataNone = 0, + /** \brief Metadata type for HDR10. */ + VAProcHighDynamicRangeMetadataHDR10, + /** \brief Number of Metadata type. */ + VAProcHighDynamicRangeMetadataTypeCount +} VAProcHighDynamicRangeMetadataType; + +/** \brief Video Processing Mode. */ +typedef enum _VAProcMode { + /** + * \brief Default Mode. + * In this mode, pipeline is decided in driver to the appropriate mode. + * e.g. a mode that's a balance between power and performance. + */ + VAProcDefaultMode = 0, + /** + * \brief Power Saving Mode. + * In this mode, pipeline is optimized for power saving. + */ + VAProcPowerSavingMode, + /** + * \brief Performance Mode. + * In this mode, pipeline is optimized for performance. + */ + VAProcPerformanceMode +} VAProcMode; + +/** @name Video blending flags */ +/**@{*/ +/** \brief Global alpha blending. */ +#define VA_BLEND_GLOBAL_ALPHA 0x0001 +/** \brief Premultiplied alpha blending (RGBA surfaces only). */ +#define VA_BLEND_PREMULTIPLIED_ALPHA 0x0002 +/** \brief Luma color key (YUV surfaces only). */ +#define VA_BLEND_LUMA_KEY 0x0010 +/**@}*/ + +/** \brief Video blending state definition. */ +typedef struct _VABlendState { + /** \brief Video blending flags. */ + unsigned int flags; + /** + * \brief Global alpha value. + * + * Valid if \ref flags has VA_BLEND_GLOBAL_ALPHA. + * Valid range is 0.0 to 1.0 inclusive. + */ + float global_alpha; + /** + * \brief Minimum luma value. + * + * Valid if \ref flags has VA_BLEND_LUMA_KEY. + * Valid range is 0.0 to 1.0 inclusive. + * \ref min_luma shall be set to a sensible value lower than \ref max_luma. + */ + float min_luma; + /** + * \brief Maximum luma value. + * + * Valid if \ref flags has VA_BLEND_LUMA_KEY. + * Valid range is 0.0 to 1.0 inclusive. + * \ref max_luma shall be set to a sensible value larger than \ref min_luma. + */ + float max_luma; +} VABlendState; + +/** @name Video pipeline flags */ +/**@{*/ +/** \brief Specifies whether to apply subpictures when processing a surface. */ +#define VA_PROC_PIPELINE_SUBPICTURES 0x00000001 +/** + * \brief Specifies whether to apply power or performance + * optimizations to a pipeline. + * + * When processing several surfaces, it may be necessary to prioritize + * more certain pipelines than others. This flag is only a hint to the + * video processor so that it can omit certain filters to save power + * for example. Typically, this flag could be used with video surfaces + * decoded from a secondary bitstream. + */ +#define VA_PROC_PIPELINE_FAST 0x00000002 +/**@}*/ + +/** @name Video filter flags */ +/**@{*/ +/** \brief Specifies whether the filter shall be present in the pipeline. */ +#define VA_PROC_FILTER_MANDATORY 0x00000001 +/**@}*/ + +/** @name Pipeline end flags */ +/**@{*/ +/** \brief Specifies the pipeline is the last. */ +#define VA_PIPELINE_FLAG_END 0x00000004 +/**@}*/ + +/** @name Chroma Siting flag */ +/**@{*/ +/** vertical chroma sitting take bit 0-1, horizontal chroma sitting take bit 2-3 + * vertical chromma siting | horizontal chroma sitting to be chroma sitting */ +#define VA_CHROMA_SITING_UNKNOWN 0x00 +/** \brief Chroma samples are co-sited vertically on the top with the luma samples. */ +#define VA_CHROMA_SITING_VERTICAL_TOP 0x01 +/** \brief Chroma samples are not co-sited vertically with the luma samples. */ +#define VA_CHROMA_SITING_VERTICAL_CENTER 0x02 +/** \brief Chroma samples are co-sited vertically on the bottom with the luma samples. */ +#define VA_CHROMA_SITING_VERTICAL_BOTTOM 0x03 +/** \brief Chroma samples are co-sited horizontally on the left with the luma samples. */ +#define VA_CHROMA_SITING_HORIZONTAL_LEFT 0x04 +/** \brief Chroma samples are not co-sited horizontally with the luma samples. */ +#define VA_CHROMA_SITING_HORIZONTAL_CENTER 0x08 +/**@}*/ + +/** + * This is to indicate that the color-space conversion uses full range or reduced range. + * VA_SOURCE_RANGE_FULL(Full range): Y/Cb/Cr is in [0, 255]. It is mainly used + * for JPEG/JFIF formats. The combination with the BT601 flag means that + * JPEG/JFIF color-space conversion matrix is used. + * VA_SOURCE_RANGE_REDUCED(Reduced range): Y is in [16, 235] and Cb/Cr is in [16, 240]. + * It is mainly used for the YUV->RGB color-space conversion in SDTV/HDTV/UHDTV. + */ +#define VA_SOURCE_RANGE_UNKNOWN 0 +#define VA_SOURCE_RANGE_REDUCED 1 +#define VA_SOURCE_RANGE_FULL 2 + +/** @name Tone Mapping flags multiple HDR mode*/ +/**@{*/ +/** \brief Tone Mapping from HDR content to HDR display. */ +#define VA_TONE_MAPPING_HDR_TO_HDR 0x0001 +/** \brief Tone Mapping from HDR content to SDR display. */ +#define VA_TONE_MAPPING_HDR_TO_SDR 0x0002 +/** \brief Tone Mapping from HDR content to EDR display. */ +#define VA_TONE_MAPPING_HDR_TO_EDR 0x0004 +/** \brief Tone Mapping from SDR content to HDR display. */ +#define VA_TONE_MAPPING_SDR_TO_HDR 0x0008 +/**@}*/ + +/** \brief Video processing pipeline capabilities. */ +typedef struct _VAProcPipelineCaps { + /** \brief Pipeline flags. See VAProcPipelineParameterBuffer::pipeline_flags. */ + uint32_t pipeline_flags; + /** \brief Extra filter flags. See VAProcPipelineParameterBuffer::filter_flags. */ + uint32_t filter_flags; + /** \brief Number of forward reference frames that are needed. */ + uint32_t num_forward_references; + /** \brief Number of backward reference frames that are needed. */ + uint32_t num_backward_references; + /** \brief List of color standards supported on input. */ + VAProcColorStandardType *input_color_standards; + /** \brief Number of elements in \ref input_color_standards array. */ + uint32_t num_input_color_standards; + /** \brief List of color standards supported on output. */ + VAProcColorStandardType *output_color_standards; + /** \brief Number of elements in \ref output_color_standards array. */ + uint32_t num_output_color_standards; + + /** + * \brief Rotation flags. + * + * For each rotation angle supported by the underlying hardware, + * the corresponding bit is set in \ref rotation_flags. See + * "Rotation angles" for a description of rotation angles. + * + * A value of 0 means the underlying hardware does not support any + * rotation. Otherwise, a check for a specific rotation angle can be + * performed as follows: + * + * \code + * VAProcPipelineCaps pipeline_caps; + * ... + * vaQueryVideoProcPipelineCaps(va_dpy, vpp_ctx, + * filter_bufs, num_filter_bufs, + * &pipeline_caps + * ); + * ... + * if (pipeline_caps.rotation_flags & (1 << VA_ROTATION_xxx)) { + * // Clockwise rotation by xxx degrees is supported + * ... + * } + * \endcode + */ + uint32_t rotation_flags; + /** \brief Blend flags. See "Video blending flags". */ + uint32_t blend_flags; + /** + * \brief Mirroring flags. + * + * For each mirroring direction supported by the underlying hardware, + * the corresponding bit is set in \ref mirror_flags. See + * "Mirroring directions" for a description of mirroring directions. + * + */ + uint32_t mirror_flags; + /** \brief Number of additional output surfaces supported by the pipeline */ + uint32_t num_additional_outputs; + + /** \brief Number of elements in \ref input_pixel_format array. */ + uint32_t num_input_pixel_formats; + /** \brief List of input pixel formats in fourcc. */ + uint32_t *input_pixel_format; + /** \brief Number of elements in \ref output_pixel_format array. */ + uint32_t num_output_pixel_formats; + /** \brief List of output pixel formats in fourcc. */ + uint32_t *output_pixel_format; + + /** \brief Max supported input width in pixels. */ + uint32_t max_input_width; + /** \brief Max supported input height in pixels. */ + uint32_t max_input_height; + /** \brief Min supported input width in pixels. */ + uint32_t min_input_width; + /** \brief Min supported input height in pixels. */ + uint32_t min_input_height; + + /** \brief Max supported output width in pixels. */ + uint32_t max_output_width; + /** \brief Max supported output height in pixels. */ + uint32_t max_output_height; + /** \brief Min supported output width in pixels. */ + uint32_t min_output_width; + /** \brief Min supported output height in pixels. */ + uint32_t min_output_height; + /** \brief Reserved bytes for future use, must be zero */ +#if defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__) || defined(__LP64__) + uint32_t va_reserved[VA_PADDING_HIGH - 2]; +#else + uint32_t va_reserved[VA_PADDING_HIGH]; +#endif +} VAProcPipelineCaps; + +/** \brief Specification of values supported by the filter. */ +typedef struct _VAProcFilterValueRange { + /** \brief Minimum value supported, inclusive. */ + float min_value; + /** \brief Maximum value supported, inclusive. */ + float max_value; + /** \brief Default value. */ + float default_value; + /** \brief Step value that alters the filter behaviour in a sensible way. */ + float step; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterValueRange; + +typedef struct _VAProcColorProperties { + /** Chroma sample location.\c VA_CHROMA_SITING_VERTICAL_XXX | VA_CHROMA_SITING_HORIZONTAL_XXX */ + uint8_t chroma_sample_location; + /** Color range. \c VA_SOURCE_RANGE_XXX*/ + uint8_t color_range; + /** Colour primaries. + * + * See ISO/IEC 23001-8 or ITU H.273, section 8.1 and table 2. + * Only used if the color standard in use is \c VAColorStandardExplicit. + * Below list the typical colour primaries for the reference. + * --------------------------------------------------------------------------------- + * | Value | Primaries | Informative Remark | + * -------------------------------------------------------------------------------- + * | 1 |primary x y |Rec.ITU-R BT.709-5 | + * | |green 0.300 0.600 |IEC 61966-2-1(sRGB or sYCC) | + * | |blue 0.150 0.060 | | + * | |red 0.640 0.330 | | + * | |whiteD65 0.3127 0.3290 | | + * --------------------------------------------------------------------------------- + * | 6 |primary x y |Rec.ITU-R BT.601-6 525 | + * | |green 0.310 0.595 | | + * | |blue 0.155 0.070 | | + * | |red 0.630 0.340 | | + * | |whiteD65 0.3127 0.3290 | | + * --------------------------------------------------------------------------------- + * | 9 |primary x y |Rec.ITU-R BT.2020 | + * | |green 0.170 0.797 | | + * | |blue 0.131 0.046 | | + * | |red 0.708 0.292 | | + * | |whiteD65 0.3127 0.3290 | | + * --------------------------------------------------------------------------------- + */ + uint8_t colour_primaries; + /** Transfer characteristics. + * + * See ISO/IEC 23001-8 or ITU H.273, section 8.2 and table 3. + * Only used if the color standard in use is \c VAColorStandardExplicit. + * Below list the typical transfer characteristics for the reference. + * ----------------------------------------------------------- + * | Value | Informative Remark | + * ----------------------------------------------------------- + * | 1 |Rec.ITU-R BT.709-5 | + * | |colour gamut system | + * ----------------------------------------------------------- + * | 4 |Assumed display gamma 2.2 | + * ----------------------------------------------------------- + * | 6 |Rec.ITU-R BT.601-6 525 or 625 | + * ----------------------------------------------------------- + * | 8 |Linear transfer characteristics | + * ----------------------------------------------------------- + * | 13 |IEC 61966-2-1(sRGB or sYCC) | + * ----------------------------------------------------------- + * | 14,15 |Rec.ITU-R BT.2020 | + * ----------------------------------------------------------- + * | 16 |SMPTE ST 2084 for 10,12,14 and 16bit system | + * ----------------------------------------------------------- + */ + uint8_t transfer_characteristics; + /** Matrix coefficients. + * + * See ISO/IEC 23001-8 or ITU H.273, section 8.3 and table 4. + * Only used if the color standard in use is \c VAColorStandardExplicit. + */ + uint8_t matrix_coefficients; + /** Reserved bytes for future use, must be zero. */ + uint8_t reserved[3]; +} VAProcColorProperties; + +/** \brief Describes High Dynamic Range Meta Data for HDR10. + * + * Specifies the colour volume(the colour primaries, white point and luminance range) of + * a display considered to be the mastering display for the associated video content -e.g., + * the colour volume of a display that was used for viewing while authoring the video content. + * See ITU-T H.265 D.3.27 Mastering display colour volume SEI message semantics. + * + * Specifies upper bounds for the nominal light level of the content. See ITU-T H.265 D.3.35 + * Content light level information SEI message semantics. + * + * This structure can be used to indicate the HDR10 metadata for 1) the content which was authored; + * 2) the display on which the content will be presented. If it is for display, max_content_light_level + * and max_pic_average_light_level are ignored. + */ +typedef struct _VAHdrMetaDataHDR10 { + /** + * \brief X chromaticity coordinate of the mastering display. + * + * Index value c equal to 0 should correspond to the green primary. + * Index value c equal to 1 should correspond to the blue primary. + * Index value c equal to 2 should correspond to the red primary. + * The value for display_primaries_x shall be in the range of 0 to 50000 inclusive. + */ + uint16_t display_primaries_x[3]; + /** + * \brief Y chromaticity coordinate of the mastering display. + * + * Index value c equal to 0 should correspond to the green primary. + * Index value c equal to 1 should correspond to the blue primary. + * Index value c equal to 2 should correspond to the red primary. + * The value for display_primaries_y shall be in the range of 0 to 50000 inclusive. + */ + uint16_t display_primaries_y[3]; + /** + * \brief X chromaticity coordinate of the white point of the mastering display. + * + * The value for white_point_x shall be in the range of 0 to 50000 inclusive. + */ + uint16_t white_point_x; + /** + * \brief Y chromaticity coordinate of the white point of the mastering display. + * + * The value for white_point_y shall be in the range of 0 to 50000 inclusive. + */ + uint16_t white_point_y; + /** + * \brief The maximum display luminance of the mastering display. + * + * The value is in units of 0.0001 candelas per square metre. + */ + uint32_t max_display_mastering_luminance; + /** + * \brief The minumum display luminance of the mastering display. + * + * The value is in units of 0.0001 candelas per square metre. + */ + uint32_t min_display_mastering_luminance; + /** + * \brief The maximum content light level (MaxCLL). + * + * The value is in units of 1 candelas per square metre. + */ + uint16_t max_content_light_level; + /** + * \brief The maximum picture average light level (MaxFALL). + * + * The value is in units of 1 candelas per square metre. + */ + uint16_t max_pic_average_light_level; + /** Resevered */ + uint16_t reserved[VA_PADDING_HIGH]; +} VAHdrMetaDataHDR10; + +/** \brief Capabilities specification for the High Dynamic Range filter. */ +typedef struct _VAProcFilterCapHighDynamicRange { + /** \brief high dynamic range type. */ + VAProcHighDynamicRangeMetadataType metadata_type; + /** + * \brief flag for high dynamic range tone mapping + * + * The flag is the combination of VA_TONE_MAPPING_XXX_TO_XXX. + * It could be VA_TONE_MAPPING_HDR_TO_HDR | VA_TONE_MAPPING_HDR_TO_SDR. + * SDR content to SDR display is always supported by default since it is legacy path. + */ + uint16_t caps_flag; + /** \brief Reserved bytes for future use, must be zero */ + uint16_t va_reserved[VA_PADDING_HIGH]; +} VAProcFilterCapHighDynamicRange; + +/** \brief High Dynamic Range Meta Data. */ +typedef struct _VAHdrMetaData { + /** \brief high dynamic range metadata type, HDR10 etc. */ + VAProcHighDynamicRangeMetadataType metadata_type; + /** + * \brief Pointer to high dynamic range metadata. + * + * The pointer could point to VAHdrMetaDataHDR10 or other HDR meta data. + */ + void* metadata; + /** + * \brief Size of high dynamic range metadata. + */ + uint32_t metadata_size; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t reserved[VA_PADDING_LOW]; +} VAHdrMetaData; + +/** + * \brief Video processing pipeline configuration. + * + * This buffer defines a video processing pipeline. The actual filters to + * be applied are provided in the \c filters field, they can be re-used + * in other processing pipelines. + * + * The target surface is specified by the \c render_target argument of + * \c vaBeginPicture(). The general usage model is described as follows: + * - \c vaBeginPicture(): specify the target surface that receives the + * processed output; + * - \c vaRenderPicture(): specify a surface to be processed and composed + * into the \c render_target. Use as many \c vaRenderPicture() calls as + * necessary surfaces to compose ; + * - \c vaEndPicture(): tell the driver to start processing the surfaces + * with the requested filters. + * + * If a filter (e.g. noise reduction) needs to be applied with different + * values for multiple surfaces, the application needs to create as many + * filter parameter buffers as necessary. i.e. the filter parameters shall + * not change between two calls to \c vaRenderPicture(). + * + * For composition usage models, the first surface to process will generally + * use an opaque background color, i.e. \c output_background_color set with + * the most significant byte set to \c 0xff. For instance, \c 0xff000000 for + * a black background. Then, subsequent surfaces would use a transparent + * background color. + */ +typedef struct _VAProcPipelineParameterBuffer { + /** + * \brief Source surface ID. + * + * ID of the source surface to process. If subpictures are associated + * with the video surfaces then they shall be rendered to the target + * surface, if the #VA_PROC_PIPELINE_SUBPICTURES pipeline flag is set. + */ + VASurfaceID surface; + /** + * \brief Region within the source surface to be processed. + * + * Pointer to a #VARectangle defining the region within the source + * surface to be processed. If NULL, \c surface_region implies the + * whole surface. + */ + const VARectangle *surface_region; + /** + * \brief Requested input color standard. + * + * Color properties are implicitly converted throughout the processing + * pipeline. The video processor chooses the best moment to apply + * this conversion. The set of supported color standards for input shall + * be queried with vaQueryVideoProcPipelineCaps(). + * + * If this is set to VAProcColorStandardExplicit, the color properties + * are specified explicitly in input_color_properties instead. + */ + VAProcColorStandardType surface_color_standard; + /** + * \brief Region within the output surface. + * + * Pointer to a #VARectangle defining the region within the output + * surface that receives the processed pixels. If NULL, \c output_region + * implies the whole surface. + * + * Note that any pixels residing outside the specified region will + * be filled in with the \ref output_background_color. + */ + const VARectangle *output_region; + /** + * \brief Background color. + * + * Background color used to fill in pixels that reside outside of the + * specified \ref output_region. The color is specified in ARGB format: + * [31:24] alpha, [23:16] red, [15:8] green, [7:0] blue. + * + * Unless the alpha value is zero or the \ref output_region represents + * the whole target surface size, implementations shall not render the + * source surface to the target surface directly. Rather, in order to + * maintain the exact semantics of \ref output_background_color, the + * driver shall use a temporary surface and fill it in with the + * appropriate background color. Next, the driver will blend this + * temporary surface into the target surface. + */ + uint32_t output_background_color; + /** + * \brief Requested output color standard. + * + * If this is set to VAProcColorStandardExplicit, the color properties + * are specified explicitly in output_color_properties instead. + */ + VAProcColorStandardType output_color_standard; + /** + * \brief Pipeline filters. See video pipeline flags. + * + * Flags to control the pipeline, like whether to apply subpictures + * or not, notify the driver that it can opt for power optimizations, + * should this be needed. + */ + uint32_t pipeline_flags; + /** + * \brief Extra filter flags. See vaPutSurface() flags. + * + * Filter flags are used as a fast path, wherever possible, to use + * vaPutSurface() flags instead of explicit filter parameter buffers. + * + * Allowed filter flags API-wise. Use vaQueryVideoProcPipelineCaps() + * to check for implementation details: + * - Bob-deinterlacing: \c VA_FRAME_PICTURE, \c VA_TOP_FIELD, + * \c VA_BOTTOM_FIELD. Note that any deinterlacing filter + * (#VAProcFilterDeinterlacing) will override those flags. + * - Color space conversion: \c VA_SRC_BT601, \c VA_SRC_BT709, + * \c VA_SRC_SMPTE_240. + * - Scaling: \c VA_FILTER_SCALING_DEFAULT, \c VA_FILTER_SCALING_FAST, + * \c VA_FILTER_SCALING_HQ, \c VA_FILTER_SCALING_NL_ANAMORPHIC. + * - Interpolation Method: \c VA_FILTER_INTERPOLATION_DEFAULT, + * \c VA_FILTER_INTERPOLATION_NEAREST_NEIGHBOR, + * \c VA_FILTER_INTERPOLATION_BILINEAR, \c VA_FILTER_INTERPOLATION_ADVANCED. + */ + uint32_t filter_flags; + /** + * \brief Array of filters to apply to the surface. + * + * The list of filters shall be ordered in the same way the driver expects + * them. i.e. as was returned from vaQueryVideoProcFilters(). + * Otherwise, a #VA_STATUS_ERROR_INVALID_FILTER_CHAIN is returned + * from vaRenderPicture() with this buffer. + * + * #VA_STATUS_ERROR_UNSUPPORTED_FILTER is returned if the list + * contains an unsupported filter. + * + */ + VABufferID *filters; + /** \brief Actual number of filters. */ + uint32_t num_filters; + /** \brief Array of forward reference frames (past frames). */ + VASurfaceID *forward_references; + /** \brief Number of forward reference frames that were supplied. */ + uint32_t num_forward_references; + /** \brief Array of backward reference frames (future frames). */ + VASurfaceID *backward_references; + /** \brief Number of backward reference frames that were supplied. */ + uint32_t num_backward_references; + /** + * \brief Rotation state. See rotation angles. + * + * The rotation angle is clockwise. There is no specific rotation + * center for this operation. Rather, The source \ref surface is + * first rotated by the specified angle and then scaled to fit the + * \ref output_region. + * + * This means that the top-left hand corner (0,0) of the output + * (rotated) surface is expressed as follows: + * - \ref VA_ROTATION_NONE: (0,0) is the top left corner of the + * source surface -- no rotation is performed ; + * - \ref VA_ROTATION_90: (0,0) is the bottom-left corner of the + * source surface ; + * - \ref VA_ROTATION_180: (0,0) is the bottom-right corner of the + * source surface -- the surface is flipped around the X axis ; + * - \ref VA_ROTATION_270: (0,0) is the top-right corner of the + * source surface. + * + * Check VAProcPipelineCaps::rotation_flags first prior to + * defining a specific rotation angle. Otherwise, the hardware can + * perfectly ignore this variable if it does not support any + * rotation. + */ + uint32_t rotation_state; + /** + * \brief blending state. See "Video blending state definition". + * + * If \ref blend_state is NULL, then default operation mode depends + * on the source \ref surface format: + * - RGB: per-pixel alpha blending ; + * - YUV: no blending, i.e override the underlying pixels. + * + * Otherwise, \ref blend_state is a pointer to a #VABlendState + * structure that shall be live until vaEndPicture(). + * + * Implementation note: the driver is responsible for checking the + * blend state flags against the actual source \ref surface format. + * e.g. premultiplied alpha blending is only applicable to RGB + * surfaces, and luma keying is only applicable to YUV surfaces. + * If a mismatch occurs, then #VA_STATUS_ERROR_INVALID_BLEND_STATE + * is returned. + */ + const VABlendState *blend_state; + /** + * \brief mirroring state. See "Mirroring directions". + * + * Mirroring of an image can be performed either along the + * horizontal or vertical axis. It is assumed that the rotation + * operation is always performed before the mirroring operation. + */ + uint32_t mirror_state; + /** \brief Array of additional output surfaces. */ + VASurfaceID *additional_outputs; + /** \brief Number of additional output surfaces. */ + uint32_t num_additional_outputs; + /** + * \brief Flag to indicate the input surface flag + * + * bit0~3: Surface sample type + * - 0000: Progressive --> VA_FRAME_PICTURE + * - 0001: Single Top Field --> VA_TOP_FIELD + * - 0010: Single Bottom Field --> VA_BOTTOM_FIELD + * - 0100: Interleaved Top Field First --> VA_TOP_FIELD_FIRST + * - 1000: Interleaved Bottom Field First --> VA_BOTTOM_FIELD_FIRST + * + * For interlaced scaling, examples as follow: + * - 1. Interleaved to Interleaved (Suppose input is top field first) + * -- set input_surface_flag as VA_TOP_FIELD_FIRST + * -- set output_surface_flag as VA_TOP_FIELD_FIRST + * - 2. Interleaved to Field (Suppose input is top field first) + * An interleaved frame need to be passed twice. + * First cycle to get the first field: + * -- set input_surface_flag as VA_TOP_FIELD_FIRST + * -- set output_surface_flag as VA_TOP_FIELD + * Second cycle to get the second field: + * -- set input_surface_flag as VA_TOP_FIELD_FIRST + * -- set output_surface_flag as VA_BOTTOM_FIELD + * - 3. Field to Interleaved (Suppose first field is top field) + * -- create two surfaces, one for top field, the other for bottom field + * -- set surface with the first field surface id + * -- set backward_reference with the second field surface id + * -- set input_surface_flag as VA_TOP_FIELD + * -- set output_surface_flag as VA_TOP_FIELD_FIRST + * - 4. Field to Field: + * -- set flag according to each frame. + * + * bit31: Surface encryption + * - 0: non-protected + * - 1: protected + * + * bit4~30 for future + */ + uint32_t input_surface_flag; + /** + * \brief Flag to indicate the output surface flag + * + * bit0~3: Surface sample type + * - 0000: Progressive --> VA_FRAME_PICTURE + * - 0001: Top Field --> VA_TOP_FIELD + * - 0010: Bottom Field --> VA_BOTTOM_FIELD + * - 0100: Top Field First --> VA_TOP_FIELD_FIRST + * - 1000: Bottom Field First --> VA_BOTTOM_FIELD_FIRST + * + * bit31: Surface encryption + * - 0: non-protected + * - 1: protected + * + * bit4~30 for future + */ + uint32_t output_surface_flag; + /** + * \brief Input Color Properties. See "VAProcColorProperties". + */ + VAProcColorProperties input_color_properties; + /** + * \brief Output Color Properties. See "VAProcColorProperties". + */ + VAProcColorProperties output_color_properties; + /** + * \brief Processing mode. See "VAProcMode". + */ + VAProcMode processing_mode; + /** + * \brief Output High Dynamic Metadata. + * + * If output_metadata is NULL, then output default to SDR. + */ + VAHdrMetaData *output_hdr_metadata; + + /** \brief Reserved bytes for future use, must be zero */ +#if defined(__AMD64__) || defined(__x86_64__) || defined(__amd64__)|| defined(__LP64__) + uint32_t va_reserved[VA_PADDING_LARGE - 16]; +#else + uint32_t va_reserved[VA_PADDING_LARGE - 13]; +#endif +} VAProcPipelineParameterBuffer; + +/** + * \brief Filter parameter buffer base. + * + * This is a helper structure used by driver implementations only. + * Users are not supposed to allocate filter parameter buffers of this + * type. + */ +typedef struct _VAProcFilterParameterBufferBase { + /** \brief Filter type. */ + VAProcFilterType type; +} VAProcFilterParameterBufferBase; + +/** + * \brief Default filter parametrization. + * + * Unless there is a filter-specific parameter buffer, + * #VAProcFilterParameterBuffer is the default type to use. + */ +typedef struct _VAProcFilterParameterBuffer { + /** \brief Filter type. */ + VAProcFilterType type; + /** \brief Value. */ + float value; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterParameterBuffer; + +/** @name De-interlacing flags */ +/**@{*/ +/** + * \brief Bottom field first in the input frame. + * if this is not set then assumes top field first. + */ +#define VA_DEINTERLACING_BOTTOM_FIELD_FIRST 0x0001 +/** + * \brief Bottom field used in deinterlacing. + * if this is not set then assumes top field is used. + */ +#define VA_DEINTERLACING_BOTTOM_FIELD 0x0002 +/** + * \brief A single field is stored in the input frame. + * if this is not set then assumes the frame contains two interleaved fields. + */ +#define VA_DEINTERLACING_ONE_FIELD 0x0004 +/** + * \brief Film Mode Detection is enabled. If enabled, driver performs inverse + * of various pulldowns, such as 3:2 pulldown. + * if this is not set then assumes FMD is disabled. + */ +#define VA_DEINTERLACING_FMD_ENABLE 0x0008 + +//Scene change parameter for ADI on Linux, if enabled, driver use spatial DI(Bob), instead of ADI. if not, use old behavior for ADI +//Input stream is TFF(set flags = 0), SRC0,1,2,3 are interlaced frame (top +bottom fields), DSTs are progressive frames +//30i->30p +//SRC0 -> BOBDI, no reference, set flag = 0, output DST0 +//SRC1 -> ADI, reference frame=SRC0, set flags = 0, call VP, output DST1 +//SRC2 -> ADI, reference frame=SRC1, set flags = 0x0010(decimal 16), call VP, output DST2(T4) +//SRC3 -> ADI, reference frame=SRC2, set flags = 0, call VP, output DST3 +//30i->60p +//SRC0 -> BOBDI, no reference, set flag = 0, output DST0 +//SRC0 -> BOBDI, no reference, set flag =0x0002, output DST1 + +//SRC1 -> ADI, reference frame =SRC0, set flags = 0, call VP, output DST2 +//SRC1 -> ADI, reference frame =SRC0, set flags = 0x0012(decimal18), call VP, output DST3(B3) + +//SRC2 -> ADI, reference frame =SRC1, set flags = 0x0010(decimal 16), call VP, output DST4(T4) +//SRC2 -> ADI, reference frame =SRC1, set flags = 0x0002, call VP, output DST5 + +//SRC3 -> ADI, reference frame =SRC2, set flags = 0, call VP, output DST6 +//SRC3 -> ADI, reference frame =SRC1, set flags = 0x0002, call VP, output DST7 + +#define VA_DEINTERLACING_SCD_ENABLE 0x0010 + +/**@}*/ + +/** \brief Deinterlacing filter parametrization. */ +typedef struct _VAProcFilterParameterBufferDeinterlacing { + /** \brief Filter type. Shall be set to #VAProcFilterDeinterlacing. */ + VAProcFilterType type; + /** \brief Deinterlacing algorithm. */ + VAProcDeinterlacingType algorithm; + /** \brief Deinterlacing flags. */ + uint32_t flags; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterParameterBufferDeinterlacing; + +/** + * \brief Color balance filter parametrization. + * + * This buffer defines color balance attributes. A VA buffer can hold + * several color balance attributes by creating a VA buffer of desired + * number of elements. This can be achieved by the following pseudo-code: + * + * \code + * enum { kHue, kSaturation, kBrightness, kContrast }; + * + * // Initial color balance parameters + * static const VAProcFilterParameterBufferColorBalance colorBalanceParams[4] = + * { + * [kHue] = + * { VAProcFilterColorBalance, VAProcColorBalanceHue, 0.5 }, + * [kSaturation] = + * { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 }, + * [kBrightness] = + * { VAProcFilterColorBalance, VAProcColorBalanceBrightness, 0.5 }, + * [kSaturation] = + * { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 } + * }; + * + * // Create buffer + * VABufferID colorBalanceBuffer; + * vaCreateBuffer(va_dpy, vpp_ctx, + * VAProcFilterParameterBufferType, sizeof(*pColorBalanceParam), 4, + * colorBalanceParams, + * &colorBalanceBuffer + * ); + * + * VAProcFilterParameterBufferColorBalance *pColorBalanceParam; + * vaMapBuffer(va_dpy, colorBalanceBuffer, &pColorBalanceParam); + * { + * // Change brightness only + * pColorBalanceBuffer[kBrightness].value = 0.75; + * } + * vaUnmapBuffer(va_dpy, colorBalanceBuffer); + * \endcode + */ +typedef struct _VAProcFilterParameterBufferColorBalance { + /** \brief Filter type. Shall be set to #VAProcFilterColorBalance. */ + VAProcFilterType type; + /** \brief Color balance attribute. */ + VAProcColorBalanceType attrib; + /** + * \brief Color balance value. + * + * Special case for automatically adjusted attributes. e.g. + * #VAProcColorBalanceAutoSaturation, + * #VAProcColorBalanceAutoBrightness, + * #VAProcColorBalanceAutoContrast. + * - If \ref value is \c 1.0 +/- \c FLT_EPSILON, the attribute is + * automatically adjusted and overrides any other attribute of + * the same type that would have been set explicitly; + * - If \ref value is \c 0.0 +/- \c FLT_EPSILON, the attribute is + * disabled and other attribute of the same type is used instead. + */ + float value; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterParameterBufferColorBalance; + +/** \brief Total color correction filter parametrization. */ +typedef struct _VAProcFilterParameterBufferTotalColorCorrection { + /** \brief Filter type. Shall be set to #VAProcFilterTotalColorCorrection. */ + VAProcFilterType type; + /** \brief Color to correct. */ + VAProcTotalColorCorrectionType attrib; + /** \brief Color correction value. */ + float value; +} VAProcFilterParameterBufferTotalColorCorrection; + +/** @name Video Processing Human Vision System (HVS) Denoise Mode.*/ +/**@{*/ +/** + * \brief Default Mode. + * This mode is decided in driver to the appropriate mode. + */ +#define VA_PROC_HVS_DENOISE_DEFAULT 0x0000 +/** + * \brief Auto BDRate Mode. + * Indicates auto BD rate improvement in pre-processing (such as before video encoding), ignore Strength. + */ +#define VA_PROC_HVS_DENOISE_AUTO_BDRATE 0x0001 +/** + * \brief Auto Subjective Mode. + * Indicates auto subjective quality improvement in pre-processing (such as before video encoding), ignore Strength. + */ +#define VA_PROC_HVS_DENOISE_AUTO_SUBJECTIVE 0x0002 +/** + * \brief Manual Mode. + * Indicates manual mode, allow to adjust the denoise strength manually (need to set Strength explicitly). + */ +#define VA_PROC_HVS_DENOISE_MANUAL 0x0003 +/**@}*/ + +/** \brief Human Vision System(HVS) Noise reduction filter parametrization. */ +typedef struct _VAProcFilterParameterBufferHVSNoiseReduction { + /** \brief Filter type. Shall be set to #VAProcFilterHVSNoiseReduction. */ + VAProcFilterType type; + /** \brief QP for encoding, used for HVS Denoise */ + uint16_t qp; + /** + * \brief QP to Noise Reduction Strength Mode, used for Human Vision System Based Noise Reduction. + * Controls Noise Reduction strength of conservative and aggressive mode. + * It is an integer from [0-16]. + * Value 0 means completely turn off Noise Reduction; + * Value 16 means the most aggressive mode of Noise Reduction; + * Value 10 is the default value. + */ + uint16_t strength; + /** + * \brief HVS Denoise Mode which controls denoise method. + * It is a value of VA_PROC_HVS_DENOISE_xxx. + * Please see the definition of VA_PROC_HVS_DENOISE_xxx. + */ + uint16_t mode; + /** \brief Reserved bytes for future use, must be zero */ + uint16_t va_reserved[VA_PADDING_HIGH - 1]; +} VAProcFilterParameterBufferHVSNoiseReduction; + +/** \brief High Dynamic Range(HDR) Tone Mapping filter parametrization. */ +typedef struct _VAProcFilterParameterBufferHDRToneMapping { + /** \brief Filter type. Shall be set to #VAProcFilterHighDynamicRangeToneMapping.*/ + VAProcFilterType type; + /** + * \brief High Dynamic Range metadata, could be HDR10 etc. + * + * This metadata is mainly for the input surface. Given that dynamic metadata is changing + * on frame-by-frame or scene-by-scene basis for HDR10 plus, differentiate the metadata + * for the input and output. + */ + VAHdrMetaData data; + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_HIGH]; +} VAProcFilterParameterBufferHDRToneMapping; + +/** @name 3DLUT Channel Layout and Mapping */ +/**@{*/ +/** \brief 3DLUT Channel Layout is unknown. */ +#define VA_3DLUT_CHANNEL_UNKNOWN 0x00000000 +/** \brief 3DLUT Channel Layout is R, G, B, the default layout. Map RGB to RGB. */ +#define VA_3DLUT_CHANNEL_RGB_RGB 0x00000001 +/** \brief 3DLUT Channel Layout is Y, U, V. Map YUV to RGB. */ +#define VA_3DLUT_CHANNEL_YUV_RGB 0x00000002 +/** \brief 3DLUT Channel Layout is V, U, Y. Map VUY to RGB. */ +#define VA_3DLUT_CHANNEL_VUY_RGB 0x00000004 +/**@}*/ + +/** + * \brief 3DLUT filter parametrization. + * + * 3DLUT (Three Dimensional Look Up Table) is often used when converting an image or a video frame + * from one color representation to another, for example, when converting log and gamma encodings, + * changing the color space, applying a color correction, changing the dynamic range, gamut mapping etc. + * + * This buffer defines 3DLUT attributes and memory layout. The typical 3DLUT has fixed number(lut_size) + * per dimension and memory layout is 3 dimensional array as 3dlut[stride_0][stride_1][stride_2] (lut_size + * shall be smaller than stride_0/1/2). + * + * API user should query hardware capability by using the VAProcFilterCap3DLUT to get the 3DLUT attributes + * which hardware supports, and use these attributes. For example, if the user queries hardware, the API user + * could get caps with 3dlut[33][33][64] (lut_size = 33, lut_stride[0/1/2] = 33/33/64). API user shall not + * use the attributes which hardware can not support. + * + * 3DLUT is usually used to transform input RGB/YUV values in one color space to output RGB values in another + * color space. Based on 1) the format and color space of VPP input and output and 2) 3DLUT memory layout and + * channel mapping, driver will enable some color space conversion implicitly if needed. For example, the input of + * VPP is P010 format in BT2020 color space, the output of VPP is NV12 in BT709 color space and the 3DLUT channel + * mapping is VA_3DLUT_CHANNEL_RGB_RGB, driver could build the data pipeline as P010(BT2020)->RGB(BT2020) + * ->3DULT(BT709)->NV12(BT709). Please note, the limitation of 3DLUT filter color space is that the color space of + * 3DLUT filter input data needs to be same as the input data of VPP; the color space of 3DLUT filter output data + * needs to be same as the output data of VPP; format does not have such limitation. + */ +typedef struct _VAProcFilterParameterBuffer3DLUT { + /** \brief Filter type. Shall be set to #VAProcFilter3DLUT.*/ + VAProcFilterType type; + + /** \brief lut_surface contains 3DLUT data in the 3DLUT memory layout, must be linear */ + VASurfaceID lut_surface; + /** + * \brief lut_size is the number of valid points on every dimension of the three dimensional look up table. + * The size of LUT (lut_size) shall be same among every dimension of the three dimensional look up table. + * The size of LUT (lut_size) shall be smaller than lut_stride[0/1/2]. + */ + uint16_t lut_size; + /** + * \brief lut_stride are the number of points on every dimension of the three dimensional look up table. + * Three dimension can has 3 different stride, lut3d[lut_stride[0]][lut_stride[1]][lut_stride[2]]. + * But the valid point shall start from 0, the range of valid point is [0, lut_size-1] for every dimension. + */ + uint16_t lut_stride[3]; + /** \brief bit_depth is the number of bits for every channel R, G or B (or Y, U, V) */ + uint16_t bit_depth; + /** \brief num_channel is the number of channels */ + uint16_t num_channel; + + /** \brief channel_mapping defines the mapping of input and output channels, could be one of VA_3DLUT_CHANNEL_XXX*/ + uint32_t channel_mapping; + + /** \brief reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_HIGH]; +} VAProcFilterParameterBuffer3DLUT; + +/** \brief Capabilities specification for the 3DLUT filter. */ +typedef struct _VAProcFilterCap3DLUT { + /** \brief lut_size is the number of valid points on every dimension of the three dimensional look up table. */ + uint16_t lut_size; + /** \brief lut_stride are the number of points on every dimension of the three dimensional look up table. lut3d[lut_stride[0]][lut_stride[1]][lut_stride[2]]*/ + uint16_t lut_stride[3]; + /** \brief bit_depth is the number of bits for every channel R, G or B (or Y, U, V) */ + uint16_t bit_depth; + /** \brief num_channel is the number of channels */ + uint16_t num_channel; + /** \brief channel_mapping defines the mapping of channels, could be some combination of VA_3DLUT_CHANNEL_XXX*/ + uint32_t channel_mapping; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_HIGH]; +} VAProcFilterCap3DLUT; + +/** + * \brief Default filter cap specification (single range value). + * + * Unless there is a filter-specific cap structure, #VAProcFilterCap is the + * default type to use for output caps from vaQueryVideoProcFilterCaps(). + */ +typedef struct _VAProcFilterCap { + /** \brief Range of supported values for the filter. */ + VAProcFilterValueRange range; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterCap; + +/** \brief Capabilities specification for the deinterlacing filter. */ +typedef struct _VAProcFilterCapDeinterlacing { + /** \brief Deinterlacing algorithm. */ + VAProcDeinterlacingType type; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterCapDeinterlacing; + +/** \brief Capabilities specification for the color balance filter. */ +typedef struct _VAProcFilterCapColorBalance { + /** \brief Color balance operation. */ + VAProcColorBalanceType type; + /** \brief Range of supported values for the specified operation. */ + VAProcFilterValueRange range; + + /** \brief Reserved bytes for future use, must be zero */ + uint32_t va_reserved[VA_PADDING_LOW]; +} VAProcFilterCapColorBalance; + +/** \brief Capabilities specification for the Total Color Correction filter. */ +typedef struct _VAProcFilterCapTotalColorCorrection { + /** \brief Color to correct. */ + VAProcTotalColorCorrectionType type; + /** \brief Range of supported values for the specified color. */ + VAProcFilterValueRange range; +} VAProcFilterCapTotalColorCorrection; + +/** + * \brief Queries video processing filters. + * + * This function returns the list of video processing filters supported + * by the driver. The \c filters array is allocated by the user and + * \c num_filters shall be initialized to the number of allocated + * elements in that array. Upon successful return, the actual number + * of filters will be overwritten into \c num_filters. Otherwise, + * \c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and \c num_filters + * is adjusted to the number of elements that would be returned if enough + * space was available. + * + * The list of video processing filters supported by the driver shall + * be ordered in the way they can be iteratively applied. This is needed + * for both correctness, i.e. some filters would not mean anything if + * applied at the beginning of the pipeline; but also for performance + * since some filters can be applied in a single pass (e.g. noise + * reduction + deinterlacing). + * + * @param[in] dpy the VA display + * @param[in] context the video processing context + * @param[out] filters the output array of #VAProcFilterType elements + * @param[in,out] num_filters the number of elements allocated on input, + * the number of elements actually filled in on output + */ +VAStatus +vaQueryVideoProcFilters( + VADisplay dpy, + VAContextID context, + VAProcFilterType *filters, + unsigned int *num_filters +); + +/** + * \brief Queries video filter capabilities. + * + * This function returns the list of capabilities supported by the driver + * for a specific video filter. The \c filter_caps array is allocated by + * the user and \c num_filter_caps shall be initialized to the number + * of allocated elements in that array. Upon successful return, the + * actual number of filters will be overwritten into \c num_filter_caps. + * Otherwise, \c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and + * \c num_filter_caps is adjusted to the number of elements that would be + * returned if enough space was available. + * + * @param[in] dpy the VA display + * @param[in] context the video processing context + * @param[in] type the video filter type + * @param[out] filter_caps the output array of #VAProcFilterCap elements + * @param[in,out] num_filter_caps the number of elements allocated on input, + * the number of elements actually filled in output + */ +VAStatus +vaQueryVideoProcFilterCaps( + VADisplay dpy, + VAContextID context, + VAProcFilterType type, + void *filter_caps, + unsigned int *num_filter_caps +); + +/** + * \brief Queries video processing pipeline capabilities. + * + * This function returns the video processing pipeline capabilities. The + * \c filters array defines the video processing pipeline and is an array + * of buffers holding filter parameters. + * + * Note: the #VAProcPipelineCaps structure contains user-provided arrays. + * If non-NULL, the corresponding \c num_* fields shall be filled in on + * input with the number of elements allocated. Upon successful return, + * the actual number of elements will be overwritten into the \c num_* + * fields. Otherwise, \c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned + * and \c num_* fields are adjusted to the number of elements that would + * be returned if enough space was available. + * + * @param[in] dpy the VA display + * @param[in] context the video processing context + * @param[in] filters the array of VA buffers defining the video + * processing pipeline + * @param[in] num_filters the number of elements in filters + * @param[in,out] pipeline_caps the video processing pipeline capabilities + */ +VAStatus +vaQueryVideoProcPipelineCaps( + VADisplay dpy, + VAContextID context, + VABufferID *filters, + unsigned int num_filters, + VAProcPipelineCaps *pipeline_caps +); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* VA_VPP_H */ diff --git a/rs/moq-vaapi/libva/va/va_x11.h b/rs/moq-vaapi/libva/va/va_x11.h new file mode 100644 index 00000000000..c7e15d7ffe5 --- /dev/null +++ b/rs/moq-vaapi/libva/va/va_x11.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2012 Intel Corporation. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef _VA_X11_H_ +#define _VA_X11_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Returns a suitable VADisplay for VA API + */ +VADisplay vaGetDisplay( + Display *dpy +); + +/* + * Output rendering + * Following is the rendering interface for X windows, + * to get the decode output surface to a X drawable + * It basically performs a de-interlacing (if needed), + * color space conversion and scaling to the destination + * rectangle + */ +VAStatus vaPutSurface( + VADisplay dpy, + VASurfaceID surface, + Drawable draw, /* X Drawable */ + short srcx, + short srcy, + unsigned short srcw, + unsigned short srch, + short destx, + short desty, + unsigned short destw, + unsigned short desth, + VARectangle *cliprects, /* client supplied destination clip list */ + unsigned int number_cliprects, /* number of clip rects in the clip list */ + unsigned int flags /* PutSurface flags */ +); + +#ifdef __cplusplus +} +#endif + +#endif /* _VA_X11_H_ */ diff --git a/rs/moq-vaapi/src/bindings.rs b/rs/moq-vaapi/src/bindings.rs new file mode 100644 index 00000000000..743fc42f690 --- /dev/null +++ b/rs/moq-vaapi/src/bindings.rs @@ -0,0 +1,48 @@ +// 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, + clippy::useless_transmute, + clippy::too_many_arguments, + non_upper_case_globals, + non_snake_case, + non_camel_case_types, + dead_code, + rustdoc::all, + reason = "generated by bindgen from the vendored libva headers" +)] + +// Generated from the vendored headers by `bindgen.sh` and checked in, so a +// build needs neither bindgen nor libclang. +include!("bindings/libva.rs"); + +use std::sync::OnceLock; + +/// The dlopen'd libva symbol table, resolved once on first use. The result is +/// cached (success or failure) so a missing libva is probed at most once. +static VA: OnceLock> = OnceLock::new(); + +/// Loads libva (via `libva-drm.so.2`) on first call and returns the symbol table. +/// +/// `libva-drm.so.2` is linked against `libva.so.2`, so a single dlopen exposes +/// both `vaGetDisplayDRM` and the core `va*` symbols (dlsym on the handle searches +/// its dependencies). Returns `Err` if the library is absent, so a caller on a +/// libva-less host can fall back to another encoder instead of aborting. +pub(crate) fn load() -> Result<&'static Va, &'static str> { + VA.get_or_init(|| unsafe { Va::new("libva-drm.so.2") }.map_err(|e| e.to_string())) + .as_ref() + .map_err(String::as_str) +} + +/// Accessor for the loaded libva symbols. +/// +/// Panics if libva has not loaded. Every entry point that reaches libva goes +/// through a [`crate::Display`], whose constructor calls [`load`] and bails out on +/// failure, so by the time any other `va*` call runs the library is present. +pub(crate) fn va() -> &'static Va { + load().expect("libva not loaded; open a Display first") +} diff --git a/rs/moq-vaapi/src/bindings/libva.rs b/rs/moq-vaapi/src/bindings/libva.rs new file mode 100644 index 00000000000..ae9d561a81c --- /dev/null +++ b/rs/moq-vaapi/src/bindings/libva.rs @@ -0,0 +1,22389 @@ +/* automatically generated by rust-bindgen 0.72.1 */ + +#[repr(C)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct __BindgenBitfieldUnit { + storage: Storage, +} +impl __BindgenBitfieldUnit { + #[inline] + pub const fn new(storage: Storage) -> Self { + Self { storage } + } +} +impl __BindgenBitfieldUnit +where + Storage: AsRef<[u8]> + AsMut<[u8]>, +{ + #[inline] + fn extract_bit(byte: u8, index: usize) -> bool { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + let mask = 1 << bit_index; + byte & mask == mask + } + #[inline] + pub fn get_bit(&self, index: usize) -> bool { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = self.storage.as_ref()[byte_index]; + Self::extract_bit(byte, index) + } + #[inline] + pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { *(core::ptr::addr_of!((*this).storage) as *const u8).offset(byte_index as isize) }; + Self::extract_bit(byte, index) + } + #[inline] + fn change_bit(byte: u8, index: usize, val: bool) -> u8 { + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; + let mask = 1 << bit_index; + if val { + byte | mask + } else { + byte & !mask + } + } + #[inline] + pub fn set_bit(&mut self, index: usize, val: bool) { + debug_assert!(index / 8 < self.storage.as_ref().len()); + let byte_index = index / 8; + let byte = &mut self.storage.as_mut()[byte_index]; + *byte = Self::change_bit(*byte, index, val); + } + #[inline] + pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) { + debug_assert!(index / 8 < core::mem::size_of::()); + let byte_index = index / 8; + let byte = unsafe { (core::ptr::addr_of_mut!((*this).storage) as *mut u8).offset(byte_index as isize) }; + unsafe { *byte = Self::change_bit(*byte, index, val) }; + } + #[inline] + pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); + let mut val = 0; + for i in 0..(bit_width as usize) { + if self.get_bit(i + bit_offset) { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] + pub unsafe fn raw_get(this: *const Self, bit_offset: usize, bit_width: u8) -> u64 { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!((bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::()); + let mut val = 0; + for i in 0..(bit_width as usize) { + if unsafe { Self::raw_get_bit(this, i + bit_offset) } { + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + val |= 1 << index; + } + } + val + } + #[inline] + pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); + debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + self.set_bit(index + bit_offset, val_bit_is_set); + } + } + #[inline] + pub unsafe fn raw_set(this: *mut Self, bit_offset: usize, bit_width: u8, val: u64) { + debug_assert!(bit_width <= 64); + debug_assert!(bit_offset / 8 < core::mem::size_of::()); + debug_assert!((bit_offset + (bit_width as usize)) / 8 <= core::mem::size_of::()); + for i in 0..(bit_width as usize) { + let mask = 1 << i; + let val_bit_is_set = val & mask == mask; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; + unsafe { Self::raw_set_bit(this, index + bit_offset, val_bit_is_set) }; + } + } +} +#[repr(C)] +#[derive(Default)] +pub struct __IncompleteArrayField(::std::marker::PhantomData, [T; 0]); +impl __IncompleteArrayField { + #[inline] + pub const fn new() -> Self { + __IncompleteArrayField(::std::marker::PhantomData, []) + } + #[inline] + pub fn as_ptr(&self) -> *const T { + self as *const _ as *const T + } + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self as *mut _ as *mut T + } + #[inline] + pub unsafe fn as_slice(&self, len: usize) -> &[T] { + ::std::slice::from_raw_parts(self.as_ptr(), len) + } + #[inline] + pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { + ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) + } +} +impl ::std::fmt::Debug for __IncompleteArrayField { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + fmt.write_str("__IncompleteArrayField") + } +} +pub const VA_MAJOR_VERSION: u32 = 1; +pub const VA_MINOR_VERSION: u32 = 23; +pub const VA_MICRO_VERSION: u32 = 0; +pub const VA_VERSION_S: &[u8; 7] = b"1.23.0\0"; +pub const VA_VERSION_HEX: u32 = 18284544; +pub const VA_STATUS_SUCCESS: u32 = 0; +pub const VA_STATUS_ERROR_OPERATION_FAILED: u32 = 1; +pub const VA_STATUS_ERROR_ALLOCATION_FAILED: u32 = 2; +pub const VA_STATUS_ERROR_INVALID_DISPLAY: u32 = 3; +pub const VA_STATUS_ERROR_INVALID_CONFIG: u32 = 4; +pub const VA_STATUS_ERROR_INVALID_CONTEXT: u32 = 5; +pub const VA_STATUS_ERROR_INVALID_SURFACE: u32 = 6; +pub const VA_STATUS_ERROR_INVALID_BUFFER: u32 = 7; +pub const VA_STATUS_ERROR_INVALID_IMAGE: u32 = 8; +pub const VA_STATUS_ERROR_INVALID_SUBPICTURE: u32 = 9; +pub const VA_STATUS_ERROR_ATTR_NOT_SUPPORTED: u32 = 10; +pub const VA_STATUS_ERROR_MAX_NUM_EXCEEDED: u32 = 11; +pub const VA_STATUS_ERROR_UNSUPPORTED_PROFILE: u32 = 12; +pub const VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT: u32 = 13; +pub const VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT: u32 = 14; +pub const VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE: u32 = 15; +pub const VA_STATUS_ERROR_SURFACE_BUSY: u32 = 16; +pub const VA_STATUS_ERROR_FLAG_NOT_SUPPORTED: u32 = 17; +pub const VA_STATUS_ERROR_INVALID_PARAMETER: u32 = 18; +pub const VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED: u32 = 19; +pub const VA_STATUS_ERROR_UNIMPLEMENTED: u32 = 20; +pub const VA_STATUS_ERROR_SURFACE_IN_DISPLAYING: u32 = 21; +pub const VA_STATUS_ERROR_INVALID_IMAGE_FORMAT: u32 = 22; +pub const VA_STATUS_ERROR_DECODING_ERROR: u32 = 23; +pub const VA_STATUS_ERROR_ENCODING_ERROR: u32 = 24; +pub const VA_STATUS_ERROR_INVALID_VALUE: u32 = 25; +pub const VA_STATUS_ERROR_UNSUPPORTED_FILTER: u32 = 32; +pub const VA_STATUS_ERROR_INVALID_FILTER_CHAIN: u32 = 33; +pub const VA_STATUS_ERROR_HW_BUSY: u32 = 34; +pub const VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE: u32 = 36; +pub const VA_STATUS_ERROR_NOT_ENOUGH_BUFFER: u32 = 37; +pub const VA_STATUS_ERROR_TIMEDOUT: u32 = 38; +pub const VA_STATUS_ERROR_UNKNOWN: u32 = 4294967295; +pub const VA_FRAME_PICTURE: u32 = 0; +pub const VA_TOP_FIELD: u32 = 1; +pub const VA_BOTTOM_FIELD: u32 = 2; +pub const VA_TOP_FIELD_FIRST: u32 = 4; +pub const VA_BOTTOM_FIELD_FIRST: u32 = 8; +pub const VA_ENABLE_BLEND: u32 = 4; +pub const VA_CLEAR_DRAWABLE: u32 = 8; +pub const VA_SRC_COLOR_MASK: u32 = 240; +pub const VA_SRC_BT601: u32 = 16; +pub const VA_SRC_BT709: u32 = 32; +pub const VA_SRC_SMPTE_240: u32 = 64; +pub const VA_FILTER_SCALING_DEFAULT: u32 = 0; +pub const VA_FILTER_SCALING_FAST: u32 = 256; +pub const VA_FILTER_SCALING_HQ: u32 = 512; +pub const VA_FILTER_SCALING_NL_ANAMORPHIC: u32 = 768; +pub const VA_FILTER_SCALING_MASK: u32 = 3840; +pub const VA_FILTER_INTERPOLATION_DEFAULT: u32 = 0; +pub const VA_FILTER_INTERPOLATION_NEAREST_NEIGHBOR: u32 = 4096; +pub const VA_FILTER_INTERPOLATION_BILINEAR: u32 = 8192; +pub const VA_FILTER_INTERPOLATION_ADVANCED: u32 = 12288; +pub const VA_FILTER_INTERPOLATION_MASK: u32 = 61440; +pub const VA_PADDING_LOW: u32 = 4; +pub const VA_PADDING_MEDIUM: u32 = 8; +pub const VA_PADDING_HIGH: u32 = 16; +pub const VA_PADDING_LARGE: u32 = 32; +pub const VA_EXEC_SYNC: u32 = 0; +pub const VA_EXEC_ASYNC: u32 = 1; +pub const VA_EXEC_MODE_DEFAULT: u32 = 0; +pub const VA_EXEC_MODE_POWER_SAVING: u32 = 1; +pub const VA_EXEC_MODE_PERFORMANCE: u32 = 2; +pub const VA_FEATURE_NOT_SUPPORTED: u32 = 0; +pub const VA_FEATURE_SUPPORTED: u32 = 1; +pub const VA_FEATURE_REQUIRED: u32 = 2; +pub const VA_RT_FORMAT_YUV420: u32 = 1; +pub const VA_RT_FORMAT_YUV422: u32 = 2; +pub const VA_RT_FORMAT_YUV444: u32 = 4; +pub const VA_RT_FORMAT_YUV411: u32 = 8; +pub const VA_RT_FORMAT_YUV400: u32 = 16; +pub const VA_RT_FORMAT_YUV420_10: u32 = 256; +pub const VA_RT_FORMAT_YUV422_10: u32 = 512; +pub const VA_RT_FORMAT_YUV444_10: u32 = 1024; +pub const VA_RT_FORMAT_YUV420_12: u32 = 4096; +pub const VA_RT_FORMAT_YUV422_12: u32 = 8192; +pub const VA_RT_FORMAT_YUV444_12: u32 = 16384; +pub const VA_RT_FORMAT_RGB16: u32 = 65536; +pub const VA_RT_FORMAT_RGB32: u32 = 131072; +pub const VA_RT_FORMAT_RGBP: u32 = 1048576; +pub const VA_RT_FORMAT_RGB32_10: u32 = 2097152; +pub const VA_RT_FORMAT_PROTECTED: u32 = 2147483648; +pub const VA_RT_FORMAT_RGB32_10BPP: u32 = 2097152; +pub const VA_RT_FORMAT_YUV420_10BPP: u32 = 256; +pub const VA_RC_NONE: u32 = 1; +pub const VA_RC_CBR: u32 = 2; +pub const VA_RC_VBR: u32 = 4; +pub const VA_RC_VCM: u32 = 8; +pub const VA_RC_CQP: u32 = 16; +pub const VA_RC_VBR_CONSTRAINED: u32 = 32; +pub const VA_RC_ICQ: u32 = 64; +pub const VA_RC_MB: u32 = 128; +pub const VA_RC_CFS: u32 = 256; +pub const VA_RC_PARALLEL: u32 = 512; +pub const VA_RC_QVBR: u32 = 1024; +pub const VA_RC_AVBR: u32 = 2048; +pub const VA_RC_TCBRC: u32 = 4096; +pub const VA_DEC_SLICE_MODE_NORMAL: u32 = 1; +pub const VA_DEC_SLICE_MODE_BASE: u32 = 2; +pub const VA_DEC_PROCESSING_NONE: u32 = 0; +pub const VA_DEC_PROCESSING: u32 = 1; +pub const VA_ENC_PACKED_HEADER_NONE: u32 = 0; +pub const VA_ENC_PACKED_HEADER_SEQUENCE: u32 = 1; +pub const VA_ENC_PACKED_HEADER_PICTURE: u32 = 2; +pub const VA_ENC_PACKED_HEADER_SLICE: u32 = 4; +pub const VA_ENC_PACKED_HEADER_MISC: u32 = 8; +pub const VA_ENC_PACKED_HEADER_RAW_DATA: u32 = 16; +pub const VA_ENC_INTERLACED_NONE: u32 = 0; +pub const VA_ENC_INTERLACED_FRAME: u32 = 1; +pub const VA_ENC_INTERLACED_FIELD: u32 = 2; +pub const VA_ENC_INTERLACED_MBAFF: u32 = 4; +pub const VA_ENC_INTERLACED_PAFF: u32 = 8; +pub const VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS: u32 = 1; +pub const VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS: u32 = 2; +pub const VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS: u32 = 4; +pub const VA_ENC_SLICE_STRUCTURE_MAX_SLICE_SIZE: u32 = 8; +pub const VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS: u32 = 16; +pub const VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS: u32 = 32; +pub const VA_ENC_QUANTIZATION_NONE: u32 = 0; +pub const VA_ENC_QUANTIZATION_TRELLIS_SUPPORTED: u32 = 1; +pub const VA_PREDICTION_DIRECTION_PREVIOUS: u32 = 1; +pub const VA_PREDICTION_DIRECTION_FUTURE: u32 = 2; +pub const VA_PREDICTION_DIRECTION_BI_NOT_EMPTY: u32 = 4; +pub const VA_ENC_INTRA_REFRESH_NONE: u32 = 0; +pub const VA_ENC_INTRA_REFRESH_ROLLING_COLUMN: u32 = 1; +pub const VA_ENC_INTRA_REFRESH_ROLLING_ROW: u32 = 2; +pub const VA_ENC_INTRA_REFRESH_ADAPTIVE: u32 = 16; +pub const VA_ENC_INTRA_REFRESH_CYCLIC: u32 = 32; +pub const VA_ENC_INTRA_REFRESH_P_FRAME: u32 = 65536; +pub const VA_ENC_INTRA_REFRESH_B_FRAME: u32 = 131072; +pub const VA_ENC_INTRA_REFRESH_MULTI_REF: u32 = 262144; +pub const VA_PC_CIPHER_AES: u32 = 1; +pub const VA_PC_BLOCK_SIZE_128: u32 = 1; +pub const VA_PC_BLOCK_SIZE_192: u32 = 2; +pub const VA_PC_BLOCK_SIZE_256: u32 = 4; +pub const VA_PC_CIPHER_MODE_ECB: u32 = 1; +pub const VA_PC_CIPHER_MODE_CBC: u32 = 2; +pub const VA_PC_CIPHER_MODE_CTR: u32 = 4; +pub const VA_PC_SAMPLE_TYPE_FULLSAMPLE: u32 = 1; +pub const VA_PC_SAMPLE_TYPE_SUBSAMPLE: u32 = 2; +pub const VA_PC_USAGE_DEFAULT: u32 = 0; +pub const VA_PC_USAGE_WIDEVINE: u32 = 1; +pub const VA_PROCESSING_RATE_NONE: u32 = 0; +pub const VA_PROCESSING_RATE_ENCODE: u32 = 1; +pub const VA_PROCESSING_RATE_DECODE: u32 = 2; +pub const VA_SEGID_BLOCK_16X16: u32 = 0; +pub const VA_SEGID_BLOCK_32X32: u32 = 1; +pub const VA_SEGID_BLOCK_64X64: u32 = 2; +pub const VA_SEGID_BLOCK_8X8: u32 = 3; +pub const VA_ATTRIB_NOT_SUPPORTED: u32 = 2147483648; +pub const VA_INVALID_ID: u32 = 4294967295; +pub const VA_INVALID_SURFACE: u32 = 4294967295; +pub const VA_SURFACE_ATTRIB_NOT_SUPPORTED: u32 = 0; +pub const VA_SURFACE_ATTRIB_GETTABLE: u32 = 1; +pub const VA_SURFACE_ATTRIB_SETTABLE: u32 = 2; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_VA: u32 = 1; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_V4L2: u32 = 2; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_USER_PTR: u32 = 4; +pub const VA_SURFACE_EXTBUF_DESC_ENABLE_TILING: u32 = 1; +pub const VA_SURFACE_EXTBUF_DESC_CACHED: u32 = 2; +pub const VA_SURFACE_EXTBUF_DESC_UNCACHED: u32 = 4; +pub const VA_SURFACE_EXTBUF_DESC_WC: u32 = 8; +pub const VA_SURFACE_EXTBUF_DESC_PROTECTED: u32 = 2147483648; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC: u32 = 0; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_DECODER: u32 = 1; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER: u32 = 2; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_VPP_READ: u32 = 4; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_VPP_WRITE: u32 = 8; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_DISPLAY: u32 = 16; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_EXPORT: u32 = 32; +pub const VA_PROGRESSIVE: u32 = 1; +pub const VA_ENCRYPTION_TYPE_FULLSAMPLE_CTR: u32 = 1; +pub const VA_ENCRYPTION_TYPE_FULLSAMPLE_CBC: u32 = 2; +pub const VA_ENCRYPTION_TYPE_SUBSAMPLE_CTR: u32 = 4; +pub const VA_ENCRYPTION_TYPE_SUBSAMPLE_CBC: u32 = 8; +pub const VA_SLICE_DATA_FLAG_ALL: u32 = 0; +pub const VA_SLICE_DATA_FLAG_BEGIN: u32 = 1; +pub const VA_SLICE_DATA_FLAG_MIDDLE: u32 = 2; +pub const VA_SLICE_DATA_FLAG_END: u32 = 4; +pub const VA_MB_TYPE_MOTION_FORWARD: u32 = 2; +pub const VA_MB_TYPE_MOTION_BACKWARD: u32 = 4; +pub const VA_MB_TYPE_MOTION_PATTERN: u32 = 8; +pub const VA_MB_TYPE_MOTION_INTRA: u32 = 16; +pub const VA_PICTURE_H264_INVALID: u32 = 1; +pub const VA_PICTURE_H264_TOP_FIELD: u32 = 2; +pub const VA_PICTURE_H264_BOTTOM_FIELD: u32 = 4; +pub const VA_PICTURE_H264_SHORT_TERM_REFERENCE: u32 = 8; +pub const VA_PICTURE_H264_LONG_TERM_REFERENCE: u32 = 16; +pub const VA_CODED_BUF_STATUS_PICTURE_AVE_QP_MASK: u32 = 255; +pub const VA_CODED_BUF_STATUS_LARGE_SLICE_MASK: u32 = 256; +pub const VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK: u32 = 512; +pub const VA_CODED_BUF_STATUS_BITRATE_OVERFLOW: u32 = 1024; +pub const VA_CODED_BUF_STATUS_BITRATE_HIGH: u32 = 2048; +pub const VA_CODED_BUF_STATUS_FRAME_SIZE_OVERFLOW: u32 = 4096; +pub const VA_CODED_BUF_STATUS_BAD_BITSTREAM: u32 = 32768; +pub const VA_CODED_BUF_STATUS_AIR_MB_OVER_THRESHOLD: u32 = 16711680; +pub const VA_CODED_BUF_STATUS_NUMBER_PASSES_MASK: u32 = 251658240; +pub const VA_CODED_BUF_STATUS_SINGLE_NALU: u32 = 268435456; +pub const VA_MAPBUFFER_FLAG_DEFAULT: u32 = 0; +pub const VA_MAPBUFFER_FLAG_READ: u32 = 1; +pub const VA_MAPBUFFER_FLAG_WRITE: u32 = 2; +pub const VA_EXPORT_SURFACE_READ_ONLY: u32 = 1; +pub const VA_EXPORT_SURFACE_WRITE_ONLY: u32 = 2; +pub const VA_EXPORT_SURFACE_READ_WRITE: u32 = 3; +pub const VA_EXPORT_SURFACE_SEPARATE_LAYERS: u32 = 4; +pub const VA_EXPORT_SURFACE_COMPOSED_LAYERS: u32 = 8; +pub const VA_TIMEOUT_INFINITE: i32 = -1; +pub const VA_FOURCC_NV12: u32 = 842094158; +pub const VA_FOURCC_NV21: u32 = 825382478; +pub const VA_FOURCC_AI44: u32 = 875839817; +pub const VA_FOURCC_RGBA: u32 = 1094862674; +pub const VA_FOURCC_RGBX: u32 = 1480738642; +pub const VA_FOURCC_BGRA: u32 = 1095911234; +pub const VA_FOURCC_BGRX: u32 = 1481787202; +pub const VA_FOURCC_ARGB: u32 = 1111970369; +pub const VA_FOURCC_XRGB: u32 = 1111970392; +pub const VA_FOURCC_ABGR: u32 = 1380401729; +pub const VA_FOURCC_XBGR: u32 = 1380401752; +pub const VA_FOURCC_UYVY: u32 = 1498831189; +pub const VA_FOURCC_YUY2: u32 = 844715353; +pub const VA_FOURCC_AYUV: u32 = 1448433985; +pub const VA_FOURCC_NV11: u32 = 825316942; +pub const VA_FOURCC_YV12: u32 = 842094169; +pub const VA_FOURCC_P208: u32 = 942682704; +pub const VA_FOURCC_I420: u32 = 808596553; +pub const VA_FOURCC_YV24: u32 = 875714137; +pub const VA_FOURCC_YV32: u32 = 842225241; +pub const VA_FOURCC_Y800: u32 = 808466521; +pub const VA_FOURCC_IMC3: u32 = 860048713; +pub const VA_FOURCC_411P: u32 = 1345401140; +pub const VA_FOURCC_411R: u32 = 1378955572; +pub const VA_FOURCC_422H: u32 = 1211249204; +pub const VA_FOURCC_422V: u32 = 1446130228; +pub const VA_FOURCC_444P: u32 = 1345598516; +pub const VA_FOURCC_RGBP: u32 = 1346520914; +pub const VA_FOURCC_BGRP: u32 = 1347569474; +pub const VA_FOURCC_RGB565: u32 = 909199186; +pub const VA_FOURCC_BGR565: u32 = 909199170; +pub const VA_FOURCC_Y210: u32 = 808530521; +pub const VA_FOURCC_Y212: u32 = 842084953; +pub const VA_FOURCC_Y216: u32 = 909193817; +pub const VA_FOURCC_Y410: u32 = 808531033; +pub const VA_FOURCC_Y412: u32 = 842085465; +pub const VA_FOURCC_Y416: u32 = 909194329; +pub const VA_FOURCC_YV16: u32 = 909203033; +pub const VA_FOURCC_P010: u32 = 808530000; +pub const VA_FOURCC_P012: u32 = 842084432; +pub const VA_FOURCC_P016: u32 = 909193296; +pub const VA_FOURCC_I010: u32 = 808529993; +pub const VA_FOURCC_IYUV: u32 = 1448433993; +pub const VA_FOURCC_A2R10G10B10: u32 = 808669761; +pub const VA_FOURCC_A2B10G10R10: u32 = 808665665; +pub const VA_FOURCC_X2R10G10B10: u32 = 808669784; +pub const VA_FOURCC_X2B10G10R10: u32 = 808665688; +pub const VA_FOURCC_Y8: u32 = 538982489; +pub const VA_FOURCC_Y16: u32 = 540422489; +pub const VA_FOURCC_VYUY: u32 = 1498765654; +pub const VA_FOURCC_YVYU: u32 = 1431918169; +pub const VA_FOURCC_ARGB64: u32 = 877089345; +pub const VA_FOURCC_ABGR64: u32 = 877085249; +pub const VA_FOURCC_XYUV: u32 = 1448434008; +pub const VA_FOURCC_Q416: u32 = 909194321; +pub const VA_LSB_FIRST: u32 = 1; +pub const VA_MSB_FIRST: u32 = 2; +pub const VA_SUBPICTURE_CHROMA_KEYING: u32 = 1; +pub const VA_SUBPICTURE_GLOBAL_ALPHA: u32 = 2; +pub const VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD: u32 = 4; +pub const VA_ROTATION_NONE: u32 = 0; +pub const VA_ROTATION_90: u32 = 1; +pub const VA_ROTATION_180: u32 = 2; +pub const VA_ROTATION_270: u32 = 3; +pub const VA_MIRROR_NONE: u32 = 0; +pub const VA_MIRROR_HORIZONTAL: u32 = 1; +pub const VA_MIRROR_VERTICAL: u32 = 2; +pub const VA_OOL_DEBLOCKING_FALSE: u32 = 0; +pub const VA_OOL_DEBLOCKING_TRUE: u32 = 1; +pub const VA_RENDER_MODE_UNDEFINED: u32 = 0; +pub const VA_RENDER_MODE_LOCAL_OVERLAY: u32 = 1; +pub const VA_RENDER_MODE_LOCAL_GPU: u32 = 2; +pub const VA_RENDER_MODE_EXTERNAL_OVERLAY: u32 = 4; +pub const VA_RENDER_MODE_EXTERNAL_GPU: u32 = 8; +pub const VA_RENDER_DEVICE_UNDEFINED: u32 = 0; +pub const VA_RENDER_DEVICE_LOCAL: u32 = 1; +pub const VA_RENDER_DEVICE_EXTERNAL: u32 = 2; +pub const VA_DISPLAY_ATTRIB_NOT_SUPPORTED: u32 = 0; +pub const VA_DISPLAY_ATTRIB_GETTABLE: u32 = 1; +pub const VA_DISPLAY_ATTRIB_SETTABLE: u32 = 2; +pub const VA_PICTURE_HEVC_INVALID: u32 = 1; +pub const VA_PICTURE_HEVC_FIELD_PIC: u32 = 2; +pub const VA_PICTURE_HEVC_BOTTOM_FIELD: u32 = 4; +pub const VA_PICTURE_HEVC_LONG_TERM_REFERENCE: u32 = 8; +pub const VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE: u32 = 16; +pub const VA_PICTURE_HEVC_RPS_ST_CURR_AFTER: u32 = 32; +pub const VA_PICTURE_HEVC_RPS_LT_CURR: u32 = 64; +pub const VA_PICTURE_VVC_INVALID: u32 = 1; +pub const VA_PICTURE_VVC_LONG_TERM_REFERENCE: u32 = 2; +pub const VA_PICTURE_VVC_UNAVAILABLE_REFERENCE: u32 = 4; +pub const VA_FEI_FUNCTION_ENC: u32 = 1; +pub const VA_FEI_FUNCTION_PAK: u32 = 2; +pub const VA_FEI_FUNCTION_ENC_PAK: u32 = 4; +pub const VA_PICTURE_STATS_INVALID: u32 = 1; +pub const VA_PICTURE_STATS_PROGRESSIVE: u32 = 0; +pub const VA_PICTURE_STATS_TOP_FIELD: u32 = 2; +pub const VA_PICTURE_STATS_BOTTOM_FIELD: u32 = 4; +pub const VA_PICTURE_STATS_CONTENT_UPDATED: u32 = 16; +pub const VA_MB_PRED_AVAIL_TOP_LEFT: u32 = 4; +pub const VA_MB_PRED_AVAIL_TOP: u32 = 16; +pub const VA_MB_PRED_AVAIL_TOP_RIGHT: u32 = 8; +pub const VA_MB_PRED_AVAIL_LEFT: u32 = 64; +pub const VA_AV1_MAX_SEGMENTS: u32 = 8; +pub const VA_AV1_SEG_LVL_MAX: u32 = 8; +pub const VA_BLEND_GLOBAL_ALPHA: u32 = 1; +pub const VA_BLEND_PREMULTIPLIED_ALPHA: u32 = 2; +pub const VA_BLEND_LUMA_KEY: u32 = 16; +pub const VA_PROC_PIPELINE_SUBPICTURES: u32 = 1; +pub const VA_PROC_PIPELINE_FAST: u32 = 2; +pub const VA_PROC_FILTER_MANDATORY: u32 = 1; +pub const VA_PIPELINE_FLAG_END: u32 = 4; +pub const VA_CHROMA_SITING_UNKNOWN: u32 = 0; +pub const VA_CHROMA_SITING_VERTICAL_TOP: u32 = 1; +pub const VA_CHROMA_SITING_VERTICAL_CENTER: u32 = 2; +pub const VA_CHROMA_SITING_VERTICAL_BOTTOM: u32 = 3; +pub const VA_CHROMA_SITING_HORIZONTAL_LEFT: u32 = 4; +pub const VA_CHROMA_SITING_HORIZONTAL_CENTER: u32 = 8; +pub const VA_SOURCE_RANGE_UNKNOWN: u32 = 0; +pub const VA_SOURCE_RANGE_REDUCED: u32 = 1; +pub const VA_SOURCE_RANGE_FULL: u32 = 2; +pub const VA_TONE_MAPPING_HDR_TO_HDR: u32 = 1; +pub const VA_TONE_MAPPING_HDR_TO_SDR: u32 = 2; +pub const VA_TONE_MAPPING_HDR_TO_EDR: u32 = 4; +pub const VA_TONE_MAPPING_SDR_TO_HDR: u32 = 8; +pub const VA_DEINTERLACING_BOTTOM_FIELD_FIRST: u32 = 1; +pub const VA_DEINTERLACING_BOTTOM_FIELD: u32 = 2; +pub const VA_DEINTERLACING_ONE_FIELD: u32 = 4; +pub const VA_DEINTERLACING_FMD_ENABLE: u32 = 8; +pub const VA_DEINTERLACING_SCD_ENABLE: u32 = 16; +pub const VA_PROC_HVS_DENOISE_DEFAULT: u32 = 0; +pub const VA_PROC_HVS_DENOISE_AUTO_BDRATE: u32 = 1; +pub const VA_PROC_HVS_DENOISE_AUTO_SUBJECTIVE: u32 = 2; +pub const VA_PROC_HVS_DENOISE_MANUAL: u32 = 3; +pub const VA_3DLUT_CHANNEL_UNKNOWN: u32 = 0; +pub const VA_3DLUT_CHANNEL_RGB_RGB: u32 = 1; +pub const VA_3DLUT_CHANNEL_YUV_RGB: u32 = 2; +pub const VA_3DLUT_CHANNEL_VUY_RGB: u32 = 4; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM: u32 = 268435456; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME: u32 = 536870912; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2: u32 = 1073741824; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_3: u32 = 134217728; +#[doc = "Overview\n\nThe VA API is intended to provide an interface between a video decode/encode/processing\napplication (client) and a hardware accelerator (server), to off-load\nvideo decode/encode/processing operations from the host to the hardware accelerator at various\nentry-points.\n\nThe basic operation steps are:\n\n- Negotiate a mutually acceptable configuration with the server to lock\ndown profile, entrypoints, and other attributes that will not change on\na frame-by-frame basis.\n- Create a video decode, encode or processing context which represents a\n\"virtualized\" hardware device\n- Get and fill the render buffers with the corresponding data (depending on\nprofiles and entrypoints)\n- Pass the render buffers to the server to handle the current frame\n\nInitialization & Configuration Management\n\n- Find out supported profiles\n- Find out entrypoints for a given profile\n- Find out configuration attributes for a given profile/entrypoint pair\n- Create a configuration for use by the application"] +pub type VADisplay = *mut ::std::os::raw::c_void; +pub type VAStatus = ::std::os::raw::c_int; +#[doc = " \\brief Structure to describe rectangle."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VARectangle { + pub x: i16, + pub y: i16, + pub width: u16, + pub height: u16, +} +#[doc = " \\brief Structure to describe rectangle."] +pub type VARectangle = _VARectangle; +#[doc = " \\brief Generic motion vector data structure."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAMotionVector { + #[doc = " \\brief Past reference\n\n - \\c [0]: horizontal motion vector for past reference\n - \\c [1]: vertical motion vector for past reference"] + pub mv0: [i16; 2usize], + #[doc = " \\brief Future reference\n\n - \\c [0]: horizontal motion vector for future reference\n - \\c [1]: vertical motion vector for future reference"] + pub mv1: [i16; 2usize], +} +#[doc = " \\brief Generic motion vector data structure."] +pub type VAMotionVector = _VAMotionVector; +#[doc = " Type of a message callback, used for both error and info log."] +pub type VAMessageCallback = ::std::option::Option< + unsafe extern "C" fn(user_context: *mut ::std::os::raw::c_void, message: *const ::std::os::raw::c_char), +>; +pub type VAPrivFunc = ::std::option::Option ::std::os::raw::c_int>; +pub mod VAProfile { + #[doc = " Currently defined profiles"] + pub type Type = ::std::os::raw::c_int; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileNone: Type = -1; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileMPEG2Simple: Type = 0; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileMPEG2Main: Type = 1; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileMPEG4Simple: Type = 2; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileMPEG4AdvancedSimple: Type = 3; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileMPEG4Main: Type = 4; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264Baseline: Type = 5; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264Main: Type = 6; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264High: Type = 7; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVC1Simple: Type = 8; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVC1Main: Type = 9; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVC1Advanced: Type = 10; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH263Baseline: Type = 11; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileJPEGBaseline: Type = 12; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264ConstrainedBaseline: Type = 13; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVP8Version0_3: Type = 14; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264MultiviewHigh: Type = 15; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileH264StereoHigh: Type = 16; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain: Type = 17; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain10: Type = 18; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVP9Profile0: Type = 19; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVP9Profile1: Type = 20; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVP9Profile2: Type = 21; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileVP9Profile3: Type = 22; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain12: Type = 23; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain422_10: Type = 24; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain422_12: Type = 25; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain444: Type = 26; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain444_10: Type = 27; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCMain444_12: Type = 28; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCSccMain: Type = 29; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCSccMain10: Type = 30; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCSccMain444: Type = 31; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileAV1Profile0: Type = 32; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileAV1Profile1: Type = 33; + #[doc = " \\brief Profile ID used for video processing."] + pub const VAProfileHEVCSccMain444_10: Type = 34; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileProtected: Type = 35; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileH264High10: Type = 36; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileVVCMain10: Type = 37; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileVVCMultilayerMain10: Type = 38; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileAV1Profile2: Type = 39; + #[doc = " \\brief Profile ID used for protected video playback."] + pub const VAProfileH264High422: Type = 40; +} +pub mod VAEntrypoint { + #[doc = " Currently defined entrypoints"] + pub type Type = ::std::os::raw::c_uint; + pub const VAEntrypointVLD: Type = 1; + pub const VAEntrypointIZZ: Type = 2; + pub const VAEntrypointIDCT: Type = 3; + pub const VAEntrypointMoComp: Type = 4; + pub const VAEntrypointDeblocking: Type = 5; + pub const VAEntrypointEncSlice: Type = 6; + pub const VAEntrypointEncPicture: Type = 7; + pub const VAEntrypointEncSliceLP: Type = 8; + #[doc = "< Video pre/post-processing."] + pub const VAEntrypointVideoProc: Type = 10; + #[doc = " \\brief VAEntrypointFEI\n\n The purpose of FEI (Flexible Encoding Infrastructure) is to allow applications to\n have more controls and trade off quality for speed with their own IPs.\n The application can optionally provide input to ENC for extra encode control\n and get the output from ENC. Application can chose to modify the ENC\n output/PAK input during encoding, but the performance impact is significant.\n\n On top of the existing buffers for normal encode, there will be\n one extra input buffer (VAEncMiscParameterFEIFrameControl) and\n three extra output buffers (VAEncFEIMVBufferType, VAEncFEIMBModeBufferType\n and VAEncFEIDistortionBufferType) for VAEntrypointFEI entry function.\n If separate PAK is set, two extra input buffers\n (VAEncFEIMVBufferType, VAEncFEIMBModeBufferType) are needed for PAK input."] + pub const VAEntrypointFEI: Type = 11; + #[doc = " \\brief VAEntrypointStats\n\n A pre-processing function for getting some statistics and motion vectors is added,\n and some extra controls for Encode pipeline are provided. The application can\n optionally call the statistics function to get motion vectors and statistics like\n variances, distortions before calling Encode function via this entry point.\n\n Checking whether Statistics is supported can be performed with vaQueryConfigEntrypoints().\n If Statistics entry point is supported, then the list of returned entry-points will\n include #VAEntrypointStats. Supported pixel format, maximum resolution and statistics\n specific attributes can be obtained via normal attribute query. One input buffer\n (VAStatsStatisticsParameterBufferType) and one or two output buffers\n (VAStatsStatisticsBufferType, VAStatsStatisticsBottomFieldBufferType (for interlace only)\n and VAStatsMVBufferType) are needed for this entry point."] + pub const VAEntrypointStats: Type = 12; + #[doc = " \\brief VAEntrypointProtectedTEEComm\n\n A function for communicating with TEE (Trusted Execution Environment)."] + pub const VAEntrypointProtectedTEEComm: Type = 13; + #[doc = " \\brief VAEntrypointProtectedContent\n\n A function for protected content to decrypt encrypted content."] + pub const VAEntrypointProtectedContent: Type = 14; +} +pub mod VAConfigAttribType { + #[doc = " Currently defined configuration attribute types"] + pub type Type = ::std::os::raw::c_uint; + pub const VAConfigAttribRTFormat: Type = 0; + pub const VAConfigAttribSpatialResidual: Type = 1; + pub const VAConfigAttribSpatialClipping: Type = 2; + pub const VAConfigAttribIntraResidual: Type = 3; + pub const VAConfigAttribEncryption: Type = 4; + pub const VAConfigAttribRateControl: Type = 5; + #[doc = " @name Attributes for decoding */\n/**@{*/\n/**\n \\brief Slice Decoding mode. Read/write.\n\n This attribute determines what mode the driver supports for slice\n decoding, through vaGetConfigAttributes(); and what mode the user\n will be providing to the driver, through vaCreateConfig(), if the\n driver supports those. If this attribute is not set by the user then\n it is assumed that VA_DEC_SLICE_MODE_NORMAL mode is used.\n\n See \\c VA_DEC_SLICE_MODE_xxx for the list of slice decoding modes."] + pub const VAConfigAttribDecSliceMode: Type = 6; + #[doc = " \\brief JPEG decoding attribute. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n JPEG implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValDecJPEG union."] + pub const VAConfigAttribDecJPEG: Type = 7; + #[doc = " \\brief Decode processing support. Read/write.\n\n This attribute determines if the driver supports video processing\n with decoding using the decoding context in a single call, through\n vaGetConfigAttributes(); and if the user may use this feature,\n through vaCreateConfig(), if the driver supports the user scenario.\n The user will essentially create a regular decode VAContext. Therefore,\n the parameters of vaCreateContext() such as picture_width, picture_height\n and render_targets are in relation to the decode output parameters\n (not processing output parameters) as normal.\n If this attribute is not set by the user then it is assumed that no\n extra processing is done after decoding for this decode context.\n\n Since essentially the application is creating a decoder config and context,\n all function calls that take in the config (e.g. vaQuerySurfaceAttributes())\n or context are in relation to the decoder, except those video processing\n function specified in the next paragraph.\n\n Once the decode config and context are created, the user must further\n query the supported processing filters using vaQueryVideoProcFilters(),\n vaQueryVideoProcFilterCaps(), vaQueryVideoProcPipelineCaps() by specifying\n the created decode context. The user must provide processing information\n and extra processing output surfaces as \"additional_outputs\" to the driver\n through VAProcPipelineParameterBufferType. The render_target specified\n at vaBeginPicture() time refers to the decode output surface. The\n target surface for the output of processing needs to be a different\n surface since the decode process requires the original reconstructed buffer.\n The \"surface\" member of VAProcPipelineParameterBuffer should be set to the\n same as \"render_target\" set in vaBeginPicture(), but the driver may choose\n to ignore this parameter."] + pub const VAConfigAttribDecProcessing: Type = 8; + #[doc = " @name Attributes for encoding */\n/**@{*/\n/**\n \\brief Packed headers mode. Read/write.\n\n This attribute determines what packed headers the driver supports,\n through vaGetConfigAttributes(); and what packed headers the user\n will be providing to the driver, through vaCreateConfig(), if the\n driver supports those.\n\n See \\c VA_ENC_PACKED_HEADER_xxx for the list of packed headers."] + pub const VAConfigAttribEncPackedHeaders: Type = 10; + #[doc = " \\brief Interlaced mode. Read/write.\n\n This attribute determines what kind of interlaced encoding mode\n the driver supports.\n\n See \\c VA_ENC_INTERLACED_xxx for the list of interlaced modes."] + pub const VAConfigAttribEncInterlaced: Type = 11; + #[doc = " \\brief Maximum number of reference frames. Read-only.\n\n This attribute determines the maximum number of reference\n frames supported for encoding.\n\n Note: for H.264 encoding, the value represents the maximum number\n of reference frames for both the reference picture list 0 (bottom\n 16 bits) and the reference picture list 1 (top 16 bits)."] + pub const VAConfigAttribEncMaxRefFrames: Type = 13; + #[doc = " \\brief Maximum number of slices per frame. Read-only.\n\n This attribute determines the maximum number of slices the\n driver can support to encode a single frame."] + pub const VAConfigAttribEncMaxSlices: Type = 14; + #[doc = " \\brief Slice structure. Read-only.\n\n This attribute determines slice structures supported by the\n driver for encoding. This attribute is a hint to the user so\n that he can choose a suitable surface size and how to arrange\n the encoding process of multiple slices per frame.\n\n More specifically, for H.264 encoding, this attribute\n determines the range of accepted values to\n VAEncSliceParameterBufferH264::macroblock_address and\n VAEncSliceParameterBufferH264::num_macroblocks.\n\n See \\c VA_ENC_SLICE_STRUCTURE_xxx for the supported slice\n structure types."] + pub const VAConfigAttribEncSliceStructure: Type = 15; + #[doc = " \\brief Macroblock information. Read-only.\n\n This attribute determines whether the driver supports extra\n encoding information per-macroblock. e.g. QP.\n\n More specifically, for H.264 encoding, if the driver returns a non-zero\n value for this attribute, this means the application can create\n additional #VAEncMacroblockParameterBufferH264 buffers referenced\n through VAEncSliceParameterBufferH264::macroblock_info."] + pub const VAConfigAttribEncMacroblockInfo: Type = 16; + #[doc = " \\brief Maximum picture width. Read-only.\n\n This attribute determines the maximum picture width the driver supports\n for a given configuration."] + pub const VAConfigAttribMaxPictureWidth: Type = 18; + #[doc = " \\brief Maximum picture height. Read-only.\n\n This attribute determines the maximum picture height the driver supports\n for a given configuration."] + pub const VAConfigAttribMaxPictureHeight: Type = 19; + #[doc = " \\brief JPEG encoding attribute. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n JPEG implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncJPEG union."] + pub const VAConfigAttribEncJPEG: Type = 20; + #[doc = " \\brief Encoding quality range attribute. Read-only.\n\n This attribute conveys whether the driver supports different quality level settings\n for encoding. A value less than or equal to 1 means that the encoder only has a single\n quality setting, and a value greater than 1 represents the number of quality levels\n that can be configured. e.g. a value of 2 means there are two distinct quality levels."] + pub const VAConfigAttribEncQualityRange: Type = 21; + #[doc = " \\brief Encoding quantization attribute. Read-only.\n\n This attribute conveys whether the driver supports certain types of quantization methods\n for encoding (e.g. trellis). See \\c VA_ENC_QUANTIZATION_xxx for the list of quantization methods"] + pub const VAConfigAttribEncQuantization: Type = 22; + #[doc = " \\brief Encoding intra refresh attribute. Read-only.\n\n This attribute conveys whether the driver supports certain types of intra refresh methods\n for encoding (e.g. adaptive intra refresh or rolling intra refresh).\n See \\c VA_ENC_INTRA_REFRESH_xxx for intra refresh methods"] + pub const VAConfigAttribEncIntraRefresh: Type = 23; + #[doc = " \\brief Encoding skip frame attribute. Read-only.\n\n This attribute conveys whether the driver supports sending skip frame parameters\n (VAEncMiscParameterTypeSkipFrame) to the encoder's rate control, when the user has\n externally skipped frames."] + pub const VAConfigAttribEncSkipFrame: Type = 24; + #[doc = " \\brief Encoding region-of-interest (ROI) attribute. Read-only.\n\n This attribute conveys whether the driver supports region-of-interest (ROI) encoding,\n based on user provided ROI rectangles. The attribute value is partitioned into fields\n as defined in the VAConfigAttribValEncROI union.\n\n If ROI encoding is supported, the ROI information is passed to the driver using\n VAEncMiscParameterTypeROI."] + pub const VAConfigAttribEncROI: Type = 25; + #[doc = " \\brief Encoding extended rate control attribute. Read-only.\n\n This attribute conveys whether the driver supports any extended rate control features\n The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncRateControlExt union."] + pub const VAConfigAttribEncRateControlExt: Type = 26; + #[doc = " \\brief Processing rate reporting attribute. Read-only.\n\n This attribute conveys whether the driver supports reporting of\n encode/decode processing rate based on certain set of parameters\n (i.e. levels, I frame internvals) for a given configuration.\n If this is supported, vaQueryProcessingRate() can be used to get\n encode or decode processing rate.\n See \\c VA_PROCESSING_RATE_xxx for encode/decode processing rate"] + pub const VAConfigAttribProcessingRate: Type = 27; + #[doc = " \\brief Encoding dirty rectangle. Read-only.\n\n This attribute conveys whether the driver supports dirty rectangle.\n encoding, based on user provided ROI rectangles which indicate the rectangular areas\n where the content has changed as compared to the previous picture. The regions of the\n picture that are not covered by dirty rect rectangles are assumed to have not changed\n compared to the previous picture. The encoder may do some optimizations based on\n this information. The attribute value returned indicates the number of regions that\n are supported. e.g. A value of 0 means dirty rect encoding is not supported. If dirty\n rect encoding is supported, the ROI information is passed to the driver using\n VAEncMiscParameterTypeDirtyRect."] + pub const VAConfigAttribEncDirtyRect: Type = 28; + #[doc = " \\brief Parallel Rate Control (hierachical B) attribute. Read-only.\n\n This attribute conveys whether the encoder supports parallel rate control.\n It is a integer value 0 - unsupported, > 0 - maximum layer supported.\n This is the way when hireachical B frames are encoded, multiple independent B frames\n on the same layer may be processed at same time. If supported, app may enable it by\n setting enable_parallel_brc in VAEncMiscParameterRateControl,and the number of B frames\n per layer per GOP will be passed to driver through VAEncMiscParameterParallelRateControl\n structure.Currently three layers are defined."] + pub const VAConfigAttribEncParallelRateControl: Type = 29; + #[doc = " \\brief Dynamic Scaling Attribute. Read-only.\n\n This attribute conveys whether encoder is capable to determine dynamic frame\n resolutions adaptive to bandwidth utilization and processing power, etc.\n It is a boolean value 0 - unsupported, 1 - supported.\n If it is supported,for VP9, suggested frame resolution can be retrieved from VACodedBufferVP9Status."] + pub const VAConfigAttribEncDynamicScaling: Type = 30; + #[doc = " \\brief frame size tolerance support\n it indicates the tolerance of frame size"] + pub const VAConfigAttribFrameSizeToleranceSupport: Type = 31; + #[doc = " \\brief Encode function type for FEI.\n\n This attribute conveys whether the driver supports different function types for encode.\n It can be VA_FEI_FUNCTION_ENC, VA_FEI_FUNCTION_PAK, or VA_FEI_FUNCTION_ENC_PAK. Currently\n it is for FEI entry point only.\n Default is VA_FEI_FUNCTION_ENC_PAK."] + pub const VAConfigAttribFEIFunctionType: Type = 32; + #[doc = " \\brief Maximum number of FEI MV predictors. Read-only.\n\n This attribute determines the maximum number of MV predictors the driver\n can support to encode a single frame. 0 means no MV predictor is supported.\n Currently it is for FEI entry point only."] + pub const VAConfigAttribFEIMVPredictors: Type = 33; + #[doc = " \\brief Statistics attribute. Read-only.\n\n This attribute exposes a number of capabilities of the VAEntrypointStats entry\n point. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValStats union. Currently it is for VAEntrypointStats only."] + pub const VAConfigAttribStats: Type = 34; + #[doc = " \\brief Tile Support Attribute. Read-only.\n\n This attribute conveys whether encoder is capable to support tiles.\n If not supported, the tile related parameters sent to encoder, such as\n tiling structure, should be ignored. 0 - unsupported, 1 - supported."] + pub const VAConfigAttribEncTileSupport: Type = 35; + #[doc = " \\brief whether accept rouding setting from application. Read-only.\n This attribute is for encode quality, if it is report,\n application can change the rounding setting by VAEncMiscParameterTypeCustomRoundingControl"] + pub const VAConfigAttribCustomRoundingControl: Type = 36; + #[doc = " \\brief Encoding QP info block size attribute. Read-only.\n This attribute conveys the block sizes that underlying driver\n support for QP info for buffer #VAEncQpBuffer."] + pub const VAConfigAttribQPBlockSize: Type = 37; + #[doc = " \\brief encode max frame size attribute. Read-only\n attribute value \\c VAConfigAttribValMaxFrameSize represent max frame size support"] + pub const VAConfigAttribMaxFrameSize: Type = 38; + #[doc = " \\brief inter frame prediction directrion attribute. Read-only.\n this attribute conveys the prediction direction (backward or forword) for specific config\n the value could be VA_PREDICTION_DIRECTION_XXXX. it can be combined with VAConfigAttribEncMaxRefFrames\n to describe reference list , and the prediction direction. if this attrib is not present,both direction\n should be supported, no restriction.\n for example: normal HEVC encoding , maximum reference frame number in reflist 0 and reflist 1 is deduced\n by VAConfigAttribEncMaxRefFrames. so there are typical P frame, B frame,\n if VAConfigAttribPredictionDirection is also present. it will stipulate prediction direction in both\n reference list. if only one prediction direction present(such as PREVIOUS),all reference frame should be\n previous frame (PoC < current)."] + pub const VAConfigAttribPredictionDirection: Type = 39; + #[doc = " \\brief combined submission of multiple frames from different streams, it is optimization for different HW\n implementation, multiple frames encode/decode can improve HW concurrency"] + pub const VAConfigAttribMultipleFrame: Type = 40; + #[doc = " \\brief priority setting for the context. Read-Write\n attribute value is \\c VAConfigAttribValContextPriority\n this setting also could be update by \\c VAContextParameterUpdateBuffer"] + pub const VAConfigAttribContextPriority: Type = 41; + #[doc = " \\brief AV1 decoding features. Read-only.\n\n This attribute describes the supported features of an\n AV1 decoder configuration. The value returned uses the\n VAConfigAttribValDecAV1Features type."] + pub const VAConfigAttribDecAV1Features: Type = 42; + #[doc = " \\brief TEE could be any HW secure device. Read-only"] + pub const VAConfigAttribTEEType: Type = 43; + #[doc = " \\brief TEE type client is a specific module supporting specific functions in TEE. Read-only"] + pub const VAConfigAttribTEETypeClient: Type = 44; + #[doc = " \\brief Cipher algorithm of the protected content session.\n\n This attribute specifies the cipher algorithm of the protected content session. It\n could be \\c VA_PC_CIPHER_AES, etc...."] + pub const VAConfigAttribProtectedContentCipherAlgorithm: Type = 45; + #[doc = " \\brief Cipher block size of the protected content session.\n\n This attribute specifies the block size of the protected content session. It could be\n \\c VA_PC_BLOCK_SIZE_128, \\c VA_PC_BLOCK_SIZE_192, or \\c VA_PC_BLOCK_SIZE_256, etc...."] + pub const VAConfigAttribProtectedContentCipherBlockSize: Type = 46; + #[doc = " \\brief Cipher mode of the protected content session.\n\n This attribute specifies the cipher mode of the protected content session. It could\n be \\c VA_PC_CIPHER_MODE_ECB, \\c VA_PC_CIPHER_MODE_CBC, \\c VA_PC_CIPHER_MODE_CTR, etc..."] + pub const VAConfigAttribProtectedContentCipherMode: Type = 47; + #[doc = " \\brief Decryption sample type of the protected content session.\n\n This attribute specifies the decryption sample type of the protected content session.\n It could be \\c VA_PC_SAMPLE_TYPE_FULLSAMPLE or \\c VA_PC_SAMPLE_TYPE_SUBSAMPLE."] + pub const VAConfigAttribProtectedContentCipherSampleType: Type = 48; + #[doc = " \\brief Special usage attribute of the protected session.\n\n The attribute specifies the flow for the protected session could be used. For\n example, it could be \\c VA_PC_USAGE_DEFAULT, \\c VA_PC_USAGE_WIDEVINE, etc...."] + pub const VAConfigAttribProtectedContentUsage: Type = 49; + #[doc = " \\brief HEVC/H.265 encoding features. Read-only.\n\n This attribute describes the supported features of an\n HEVC/H.265 encoder configuration. The value returned uses the\n VAConfigAttribValEncHEVCFeatures type.\n\n If this attribute is supported by a driver then it must also\n support the VAConfigAttribEncHEVCBlockSizes attribute."] + pub const VAConfigAttribEncHEVCFeatures: Type = 50; + #[doc = " \\brief HEVC/H.265 encoding block sizes. Read-only.\n\n This attribute describes the supported coding tree and transform\n block sizes of an HEVC/H.265 encoder configuration. The value\n returned uses the VAConfigAttribValEncHEVCBlockSizes type.\n\n If this attribute is supported by a driver then it must also\n support the VAConfigAttribEncHEVCFeatures attribute."] + pub const VAConfigAttribEncHEVCBlockSizes: Type = 51; + #[doc = " \\brief AV1 encoding attribute. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n AV1 implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncAV1 union."] + pub const VAConfigAttribEncAV1: Type = 52; + #[doc = " \\brief AV1 encoding attribute extend1. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n AV1 implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncAV1Ext1 union."] + pub const VAConfigAttribEncAV1Ext1: Type = 53; + #[doc = " \\brief AV1 encoding attribute extend2. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n AV1 implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncAV1Ext2 union."] + pub const VAConfigAttribEncAV1Ext2: Type = 54; + #[doc = " \\brief Settings per block attribute for Encoding. Read-only.\n\n This attribute describes whether to support delta qp per block,\n the supported size of delta qp block and the size of delta QP in bytes.\n The value returned uses the VAConfigAttribValEncPerBlockControl type."] + pub const VAConfigAttribEncPerBlockControl: Type = 55; + #[doc = " \\brief Maximum number of tile rows. Read-only.\n\n This attribute determines the maximum number of tile\n rows supported for encoding with tile support."] + pub const VAConfigAttribEncMaxTileRows: Type = 56; + #[doc = " \\brief Maximum number of tile cols. Read-only.\n\n This attribute determines the maximum number of tile\n columns supported for encoding with tile support."] + pub const VAConfigAttribEncMaxTileCols: Type = 57; + #[doc = " \\brief VP9 encoding attribute. Read-only.\n\n This attribute exposes a number of capabilities of the underlying\n VP9 implementation. The attribute value is partitioned into fields as defined in the\n VAConfigAttribValEncVP9 union."] + pub const VAConfigAttribEncVP9: Type = 58; + #[doc = "@}"] + pub const VAConfigAttribTypeMax: Type = 59; +} +#[doc = " Configuration attributes\n If there is more than one value for an attribute, a default\n value will be assigned to the attribute if the client does not\n specify the attribute when creating a configuration"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAConfigAttrib { + pub type_: VAConfigAttribType::Type, + pub value: u32, +} +impl Default for _VAConfigAttrib { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " Configuration attributes\n If there is more than one value for an attribute, a default\n value will be assigned to the attribute if the client does not\n specify the attribute when creating a configuration"] +pub type VAConfigAttrib = _VAConfigAttrib; +#[doc = " Generic ID type, can be re-typed for specific implementation"] +pub type VAGenericID = ::std::os::raw::c_uint; +pub type VAConfigID = VAGenericID; +#[doc = " Contexts and Surfaces\n\n Context represents a \"virtual\" video decode, encode or video processing\n pipeline. Surfaces are render targets for a given context. The data in the\n surfaces are not accessible to the client except if derived image is supported\n and the internal data format of the surface is implementation specific.\n\n Surfaces are provided as a hint of what surfaces will be used when the context\n is created through vaCreateContext(). A surface may be used by different contexts\n at the same time as soon as application can make sure the operations are synchronized\n between different contexts, e.g. a surface is used as the output of a decode context\n and the input of a video process context. Surfaces can only be destroyed after all\n contexts using these surfaces have been destroyed.\n\n Both contexts and surfaces are identified by unique IDs and its\n implementation specific internals are kept opaque to the clients"] +pub type VAContextID = VAGenericID; +pub type VASurfaceID = VAGenericID; +pub mod VAGenericValueType { + #[doc = " \\brief Generic value types."] + pub type Type = ::std::os::raw::c_uint; + #[doc = "< 32-bit signed integer."] + pub const VAGenericValueTypeInteger: Type = 1; + #[doc = "< 32-bit floating-point value."] + pub const VAGenericValueTypeFloat: Type = 2; + #[doc = "< Generic pointer type"] + pub const VAGenericValueTypePointer: Type = 3; + #[doc = "< Pointer to function"] + pub const VAGenericValueTypeFunc: Type = 4; +} +#[doc = " \\brief Generic function type."] +pub type VAGenericFunc = ::std::option::Option; +#[doc = " \\brief Generic value."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAGenericValue { + #[doc = " \\brief Value type. See #VAGenericValueType."] + pub type_: VAGenericValueType::Type, + pub value: _VAGenericValue__bindgen_ty_1, +} +#[doc = " \\brief Value holder."] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAGenericValue__bindgen_ty_1 { + #[doc = " \\brief 32-bit signed integer."] + pub i: i32, + #[doc = " \\brief 32-bit float."] + pub f: f32, + #[doc = " \\brief Generic pointer."] + pub p: *mut ::std::os::raw::c_void, + #[doc = " \\brief Pointer to function."] + pub fn_: VAGenericFunc, +} +impl Default for _VAGenericValue__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAGenericValue { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Generic value."] +pub type VAGenericValue = _VAGenericValue; +pub mod VASurfaceAttribType { + #[doc = " \\brief Surface attribute types."] + pub type Type = ::std::os::raw::c_uint; + pub const VASurfaceAttribNone: Type = 0; + #[doc = " \\brief Pixel format as a FOURCC (int, read/write).\n\n When vaQuerySurfaceAttributes() is called, the driver will return one\n PixelFormat attribute per supported pixel format.\n\n When provided as an input to vaCreateSurfaces(), the driver will\n allocate a surface with the provided pixel format."] + pub const VASurfaceAttribPixelFormat: Type = 1; + #[doc = " \\brief Minimal width in pixels (int, read-only)."] + pub const VASurfaceAttribMinWidth: Type = 2; + #[doc = " \\brief Maximal width in pixels (int, read-only)."] + pub const VASurfaceAttribMaxWidth: Type = 3; + #[doc = " \\brief Minimal height in pixels (int, read-only)."] + pub const VASurfaceAttribMinHeight: Type = 4; + #[doc = " \\brief Maximal height in pixels (int, read-only)."] + pub const VASurfaceAttribMaxHeight: Type = 5; + #[doc = " \\brief Surface memory type expressed in bit fields (int, read/write)."] + pub const VASurfaceAttribMemoryType: Type = 6; + #[doc = " \\brief External buffer descriptor (pointer, write).\n\n Refer to the documentation for the memory type being created to\n determine what descriptor structure to pass here. If not otherwise\n stated, the common VASurfaceAttribExternalBuffers should be used."] + pub const VASurfaceAttribExternalBufferDescriptor: Type = 7; + #[doc = " \\brief Surface usage hint, gives the driver a hint of intended usage\n to optimize allocation (e.g. tiling) (int, read/write)."] + pub const VASurfaceAttribUsageHint: Type = 8; + #[doc = " \\brief List of possible DRM format modifiers (pointer, write).\n\n The value must be a pointer to a VADRMFormatModifierList. This can only\n be used when allocating a new buffer, it's invalid to use this attribute\n when importing an existing buffer."] + pub const VASurfaceAttribDRMFormatModifiers: Type = 9; + #[doc = " \\brief width and height log2 aligment in pixels (int, read-only)\n\n For special HW requirement used in some codecs, if\n VASurfaceAttribAlignmentSize is not implemented in the driver, then\n the surface_width and surface_height should keep the original logic\n without any modification, this is an add-on requirement to\n surface_width and surface_height."] + pub const VASurfaceAttribAlignmentSize: Type = 10; + #[doc = " \\brief Number of surface attributes."] + pub const VASurfaceAttribCount: Type = 11; +} +#[doc = " \\brief Surface attribute."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VASurfaceAttrib { + #[doc = " \\brief Type."] + pub type_: VASurfaceAttribType::Type, + #[doc = " \\brief Flags. See \"Surface attribute flags\"."] + pub flags: u32, + #[doc = " \\brief Value. See \"Surface attribute types\" for the expected types."] + pub value: VAGenericValue, +} +impl Default for _VASurfaceAttrib { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Surface attribute."] +pub type VASurfaceAttrib = _VASurfaceAttrib; +#[doc = " \\brief VASurfaceAttribExternalBuffers structure for\n the VASurfaceAttribExternalBufferDescriptor attribute."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VASurfaceAttribExternalBuffers { + #[doc = " \\brief pixel format in fourcc."] + pub pixel_format: u32, + #[doc = " \\brief width in pixels."] + pub width: u32, + #[doc = " \\brief height in pixels."] + pub height: u32, + #[doc = " \\brief total size of the buffer in bytes."] + pub data_size: u32, + #[doc = " \\brief number of planes for planar layout"] + pub num_planes: u32, + #[doc = " \\brief pitch for each plane in bytes"] + pub pitches: [u32; 4usize], + #[doc = " \\brief offset for each plane in bytes"] + pub offsets: [u32; 4usize], + #[doc = " \\brief buffer handles or user pointers"] + pub buffers: *mut usize, + #[doc = " \\brief number of elements in the \"buffers\" array"] + pub num_buffers: u32, + #[doc = " \\brief flags. See \"Surface external buffer descriptor flags\"."] + pub flags: u32, + #[doc = " \\brief reserved for passing private data"] + pub private_data: *mut ::std::os::raw::c_void, +} +impl Default for _VASurfaceAttribExternalBuffers { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief VASurfaceAttribExternalBuffers structure for\n the VASurfaceAttribExternalBufferDescriptor attribute."] +pub type VASurfaceAttribExternalBuffers = _VASurfaceAttribExternalBuffers; +pub type VAMFContextID = VAGenericID; +#[doc = " Buffers\n Buffers are used to pass various types of data from the\n client to the server. The server maintains a data store\n for each buffer created, and the client idenfies a buffer\n through a unique buffer id assigned by the server."] +pub type VABufferID = VAGenericID; +pub mod VABufferType { + pub type Type = ::std::os::raw::c_uint; + pub const VAPictureParameterBufferType: Type = 0; + pub const VAIQMatrixBufferType: Type = 1; + pub const VABitPlaneBufferType: Type = 2; + pub const VASliceGroupMapBufferType: Type = 3; + pub const VASliceParameterBufferType: Type = 4; + pub const VASliceDataBufferType: Type = 5; + pub const VAMacroblockParameterBufferType: Type = 6; + pub const VAResidualDataBufferType: Type = 7; + pub const VADeblockingParameterBufferType: Type = 8; + pub const VAImageBufferType: Type = 9; + pub const VAProtectedSliceDataBufferType: Type = 10; + pub const VAQMatrixBufferType: Type = 11; + pub const VAHuffmanTableBufferType: Type = 12; + pub const VAProbabilityBufferType: Type = 13; + pub const VAEncCodedBufferType: Type = 21; + pub const VAEncSequenceParameterBufferType: Type = 22; + pub const VAEncPictureParameterBufferType: Type = 23; + pub const VAEncSliceParameterBufferType: Type = 24; + pub const VAEncPackedHeaderParameterBufferType: Type = 25; + pub const VAEncPackedHeaderDataBufferType: Type = 26; + pub const VAEncMiscParameterBufferType: Type = 27; + pub const VAEncMacroblockParameterBufferType: Type = 28; + pub const VAEncMacroblockMapBufferType: Type = 29; + #[doc = " \\brief Encoding QP buffer\n\n This buffer contains QP per MB for encoding. Currently\n VAEncQPBufferH264 is defined for H.264 encoding, see\n #VAEncQPBufferH264 for details"] + pub const VAEncQPBufferType: Type = 30; + #[doc = " \\brief Video processing pipeline parameter buffer.\n\n This buffer describes the video processing pipeline. See\n #VAProcPipelineParameterBuffer for details."] + pub const VAProcPipelineParameterBufferType: Type = 41; + #[doc = " \\brief Video filter parameter buffer.\n\n This buffer describes the video filter parameters. All buffers\n inherit from #VAProcFilterParameterBufferBase, thus including\n a unique filter buffer type.\n\n The default buffer used by most filters is #VAProcFilterParameterBuffer.\n Filters requiring advanced parameters include, but are not limited to,\n deinterlacing (#VAProcFilterParameterBufferDeinterlacing),\n color balance (#VAProcFilterParameterBufferColorBalance), etc."] + pub const VAProcFilterParameterBufferType: Type = 42; + #[doc = " \\brief FEI specific buffer types"] + pub const VAEncFEIMVBufferType: Type = 43; + #[doc = " \\brief FEI specific buffer types"] + pub const VAEncFEIMBCodeBufferType: Type = 44; + #[doc = " \\brief FEI specific buffer types"] + pub const VAEncFEIDistortionBufferType: Type = 45; + #[doc = " \\brief FEI specific buffer types"] + pub const VAEncFEIMBControlBufferType: Type = 46; + #[doc = " \\brief FEI specific buffer types"] + pub const VAEncFEIMVPredictorBufferType: Type = 47; + #[doc = " \\brief FEI specific buffer types"] + pub const VAStatsStatisticsParameterBufferType: Type = 48; + #[doc = " \\brief Statistics output for VAEntrypointStats progressive and top field of interlaced case"] + pub const VAStatsStatisticsBufferType: Type = 49; + #[doc = " \\brief Statistics output for VAEntrypointStats bottom field of interlaced case"] + pub const VAStatsStatisticsBottomFieldBufferType: Type = 50; + #[doc = " \\brief Statistics output for VAEntrypointStats bottom field of interlaced case"] + pub const VAStatsMVBufferType: Type = 51; + #[doc = " \\brief Statistics output for VAEntrypointStats bottom field of interlaced case"] + pub const VAStatsMVPredictorBufferType: Type = 52; + #[doc = " Force MB's to be non skip for encode.it's per-mb control buffer, The width of the MB map\n Surface is (width of the Picture in MB unit) * 1 byte, multiple of 64 bytes.\n The height is (height of the picture in MB unit). The picture is either\n frame or non-interleaved top or bottom field. If the application provides this\nsurface, it will override the \"skipCheckDisable\" setting in VAEncMiscParameterEncQuality."] + pub const VAEncMacroblockDisableSkipMapBufferType: Type = 53; + #[doc = " \\brief HEVC FEI CTB level cmd buffer\n it is CTB level information for future usage."] + pub const VAEncFEICTBCmdBufferType: Type = 54; + #[doc = " \\brief HEVC FEI CU level data buffer\n it's CTB level information for future usage"] + pub const VAEncFEICURecordBufferType: Type = 55; + #[doc = " decode stream out buffer, intermedia data of decode, it may include MV, MB mode etc.\n it can be used to detect motion and analyze the frame contain"] + pub const VADecodeStreamoutBufferType: Type = 56; + #[doc = " \\brief HEVC Decoding Subset Parameter buffer type\n\n The subsets parameter buffer is concatenation with one or multiple\n subset entry point offsets. All the offset values are layed out one\n by one according to slice order with first slice segment first, second\n slice segment second, etc... The entry number is indicated by parameter\n \\ref num_entry_point_offsets. And the first entry position of the entry\n point offsets for any slice segment is indicated by parameter\n entry_offset_to_subset_array in VAPictureParameterBufferHEVC data structure."] + pub const VASubsetsParameterBufferType: Type = 57; + #[doc = " \\brief adjust context parameters dynamically\n\n this parameter is used to update context parameters, detail parameter is in\n \\c VAContextParameterUpdateBuffer"] + pub const VAContextParameterUpdateBufferType: Type = 58; + #[doc = " \\brief Protected session execution buffer type\n\n It's for TEE execution usage (vaProtectedSessionExecute()). The buffer structure is in\n \\c VAProtectedSessionExecuteBuffer"] + pub const VAProtectedSessionExecuteBufferType: Type = 59; + #[doc = " \\brief Encryption parameters buffer for protected content session.\n\n Refer to \\c VAEncryptionParameters"] + pub const VAEncryptionParameterBufferType: Type = 60; + #[doc = " \\brief Encoding delta QP per block buffer\n\n This buffer only could be created and accepted\n when \\c VAConfigAttribValEncPerBlockControl delta_qp_support == 1.\n This input buffer contains delta QP per block for encoding.\n The supported size of delta QP block and the size of delta QP\n must be quried from \\c VAConfigAttribValEncPerBlockControl."] + pub const VAEncDeltaQpPerBlockBufferType: Type = 61; + #[doc = " \\brief VVC ALF data buffer\n\n Refer to \\c VAAlfDataVVC"] + pub const VAAlfBufferType: Type = 62; + #[doc = " \\brief VVC LMCS data buffer\n\n Refer to \\c VALmcsDataVVC"] + pub const VALmcsBufferType: Type = 63; + #[doc = " \\brief VVC SubPic data buffer\n\n Refer to \\c VASubPicVVC"] + pub const VASubPicBufferType: Type = 64; + #[doc = " \\brief VVC Tile Dimension data buffer\n\n Data buffer of tile widths and heights, with each element formatted as uint16_t"] + pub const VATileBufferType: Type = 65; + #[doc = " \\brief VVC Slice Structure data buffer\n\n Refer to \\c VASliceStructVVC"] + pub const VASliceStructBufferType: Type = 66; + #[doc = " \\brief VVC Slice Structure data buffer\n\n Refer to \\c VASliceStructVVC"] + pub const VABufferTypeMax: Type = 67; +} +#[doc = " Processing rate parameter for encode."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcessingRateParameterEnc { + #[doc = " \\brief Profile level"] + pub level_idc: u8, + pub reserved: [u8; 3usize], + #[doc = " \\brief quality level. When set to 0, default quality\n level is used."] + pub quality_level: u32, + #[doc = " \\brief Period between I frames."] + pub intra_period: u32, + #[doc = " \\brief Period between I/P frames."] + pub ip_period: u32, +} +#[doc = " Processing rate parameter for encode."] +pub type VAProcessingRateParameterEnc = _VAProcessingRateParameterEnc; +#[doc = " Processing rate parameter for decode."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcessingRateParameterDec { + #[doc = " \\brief Profile level"] + pub level_idc: u8, + pub reserved0: [u8; 3usize], + pub reserved: u32, +} +#[doc = " Processing rate parameter for decode."] +pub type VAProcessingRateParameterDec = _VAProcessingRateParameterDec; +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAProcessingRateParameter { + pub __bindgen_anon_1: _VAProcessingRateParameter__bindgen_ty_1, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAProcessingRateParameter__bindgen_ty_1 { + pub proc_buf_enc: VAProcessingRateParameterEnc, + pub proc_buf_dec: VAProcessingRateParameterDec, +} +impl Default for _VAProcessingRateParameter__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAProcessingRateParameter { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VAProcessingRateParameter = _VAProcessingRateParameter; +pub mod VAEncMiscParameterType { + pub type Type = ::std::os::raw::c_uint; + pub const VAEncMiscParameterTypeFrameRate: Type = 0; + pub const VAEncMiscParameterTypeRateControl: Type = 1; + pub const VAEncMiscParameterTypeMaxSliceSize: Type = 2; + pub const VAEncMiscParameterTypeAIR: Type = 3; + #[doc = " \\brief Buffer type used to express a maximum frame size (in bits)."] + pub const VAEncMiscParameterTypeMaxFrameSize: Type = 4; + #[doc = " \\brief Buffer type used for HRD parameters."] + pub const VAEncMiscParameterTypeHRD: Type = 5; + #[doc = " \\brief Buffer type used for HRD parameters."] + pub const VAEncMiscParameterTypeQualityLevel: Type = 6; + #[doc = " \\brief Buffer type used for Rolling intra refresh"] + pub const VAEncMiscParameterTypeRIR: Type = 7; + #[doc = " \\brief Buffer type used for quantization parameters, it's per-sequence parameter"] + pub const VAEncMiscParameterTypeQuantization: Type = 8; + #[doc = " \\brief Buffer type used for sending skip frame parameters to the encoder's\n rate control, when the user has externally skipped frames."] + pub const VAEncMiscParameterTypeSkipFrame: Type = 9; + #[doc = " \\brief Buffer type used for region-of-interest (ROI) parameters."] + pub const VAEncMiscParameterTypeROI: Type = 10; + #[doc = " \\brief Buffer type used to express a maximum frame size (in bytes) settings for multiple pass."] + pub const VAEncMiscParameterTypeMultiPassFrameSize: Type = 11; + #[doc = " \\brief Buffer type used for temporal layer structure"] + pub const VAEncMiscParameterTypeTemporalLayerStructure: Type = 12; + #[doc = " \\brief Buffer type used for dirty region-of-interest (ROI) parameters."] + pub const VAEncMiscParameterTypeDirtyRect: Type = 13; + #[doc = " \\brief Buffer type used for parallel BRC parameters."] + pub const VAEncMiscParameterTypeParallelBRC: Type = 14; + #[doc = " \\brief Set MB partion mode mask and Half-pel/Quant-pel motion search"] + pub const VAEncMiscParameterTypeSubMbPartPel: Type = 15; + #[doc = " \\brief set encode quality tuning"] + pub const VAEncMiscParameterTypeEncQuality: Type = 16; + #[doc = " \\brief Buffer type used for encoder rounding offset parameters."] + pub const VAEncMiscParameterTypeCustomRoundingControl: Type = 17; + #[doc = " \\brief Buffer type used for FEI input frame level parameters"] + pub const VAEncMiscParameterTypeFEIFrameControl: Type = 18; + #[doc = " \\brief encode extension buffer, ect. MPEG2 Sequence extenstion data"] + pub const VAEncMiscParameterTypeExtensionData: Type = 19; +} +pub mod VAEncPackedHeaderType { + #[doc = " \\brief Packed header type."] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Packed sequence header."] + pub const VAEncPackedHeaderSequence: Type = 1; + #[doc = " \\brief Packed picture header."] + pub const VAEncPackedHeaderPicture: Type = 2; + #[doc = " \\brief Packed slice header."] + pub const VAEncPackedHeaderSlice: Type = 3; + #[doc = " \\brief Packed raw header.\n\n Packed raw data header can be used by the client to insert a header\n into the bitstream data buffer at the point it is passed, the driver\n will handle the raw packed header based on \"has_emulation_bytes\" field\n in the packed header parameter structure."] + pub const VAEncPackedHeaderRawData: Type = 4; + #[doc = " \\brief Misc packed header. See codec-specific definitions.\n\n @deprecated\n This is a deprecated packed header type. All applications can use\n \\c VAEncPackedHeaderRawData to insert a codec-specific packed header"] + pub const VAEncPackedHeaderMiscMask: Type = 2147483648; +} +#[doc = " \\brief Packed header parameter."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncPackedHeaderParameterBuffer { + #[doc = " Type of the packed header buffer. See #VAEncPackedHeaderType."] + pub type_: u32, + #[doc = " \\brief Size of the #VAEncPackedHeaderDataBuffer in bits."] + pub bit_length: u32, + #[doc = " \\brief Flag: buffer contains start code emulation prevention bytes?"] + pub has_emulation_bytes: u8, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Packed header parameter."] +pub type VAEncPackedHeaderParameterBuffer = _VAEncPackedHeaderParameterBuffer; +#[doc = " For application, e.g. set a new bitrate\n VABufferID buf_id;\n VAEncMiscParameterBuffer *misc_param;\n VAEncMiscParameterRateControl *misc_rate_ctrl;\n\n vaCreateBuffer(dpy, context, VAEncMiscParameterBufferType,\n sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),\n 1, NULL, &buf_id);\n\n vaMapBuffer(dpy,buf_id,(void **)&misc_param);\n misc_param->type = VAEncMiscParameterTypeRateControl;\n misc_rate_ctrl= (VAEncMiscParameterRateControl *)misc_param->data;\n misc_rate_ctrl->bits_per_second = 6400000;\n vaUnmapBuffer(dpy, buf_id);\n vaRenderPicture(dpy, context, &buf_id, 1);"] +#[repr(C)] +#[derive(Debug)] +pub struct _VAEncMiscParameterBuffer { + pub type_: VAEncMiscParameterType::Type, + pub data: __IncompleteArrayField, +} +impl Default for _VAEncMiscParameterBuffer { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " For application, e.g. set a new bitrate\n VABufferID buf_id;\n VAEncMiscParameterBuffer *misc_param;\n VAEncMiscParameterRateControl *misc_rate_ctrl;\n\n vaCreateBuffer(dpy, context, VAEncMiscParameterBufferType,\n sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),\n 1, NULL, &buf_id);\n\n vaMapBuffer(dpy,buf_id,(void **)&misc_param);\n misc_param->type = VAEncMiscParameterTypeRateControl;\n misc_rate_ctrl= (VAEncMiscParameterRateControl *)misc_param->data;\n misc_rate_ctrl->bits_per_second = 6400000;\n vaUnmapBuffer(dpy, buf_id);\n vaRenderPicture(dpy, context, &buf_id, 1);"] +pub type VAEncMiscParameterBuffer = _VAEncMiscParameterBuffer; +#[doc = " \\brief Temporal layer Structure"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterTemporalLayerStructure { + #[doc = " \\brief The number of temporal layers"] + pub number_of_layers: u32, + #[doc = " \\brief The length of the array defining frame layer membership. Should be 1-32"] + pub periodicity: u32, + #[doc = " \\brief The array indicating the layer id for each frame\n\n The layer id for the first frame in a coded sequence is always 0, so layer_id[] specifies the layer\n ids for frames starting from the 2nd frame."] + pub layer_id: [u32; 32usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Temporal layer Structure"] +pub type VAEncMiscParameterTemporalLayerStructure = _VAEncMiscParameterTemporalLayerStructure; +#[doc = " \\brief Rate control parameters"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterRateControl { + #[doc = " The maximum bit-rate which the the rate controller should generate."] + pub bits_per_second: u32, + #[doc = " The target bit-rate which the rate controller should generate, as a percentage of the\n maximum bit-rate.\n\n In CBR mode this value is ignored (treated as 100%)."] + pub target_percentage: u32, + #[doc = " Rate control window size in milliseconds.\n\n The rate controller will attempt to guarantee that the target and maximum bit-rates are\n correct over this window."] + pub window_size: u32, + #[doc = " Initial quantiser value used at the start of the stream.\n\n Ignored if set to zero."] + pub initial_qp: u32, + #[doc = " Minimum quantiser value to use.\n\n The quantiser will not go below the value - if this limit is hit, the output bitrate may\n be lower than the target. Ignored if set to zero."] + pub min_qp: u32, + #[doc = " Basic unit size.\n\n Only used by some drivers - see driver documentation for details. Set to zero if unused."] + pub basic_unit_size: u32, + pub rc_flags: _VAEncMiscParameterRateControl__bindgen_ty_1, + #[doc = " Initial quality factor used in ICQ mode.\n\n This value must be between 1 and 51.\n this value will be deprecated in future, to use quality_factor instead of it."] + pub ICQ_quality_factor: u32, + #[doc = " Maximum quantiser value to use.\n\n The quantiser will not go above this value - if this limit is hit, the output bitrate\n may exceed the target. Ignored if set to zero."] + pub max_qp: u32, + #[doc = " Quality factor\n\n the range will be different for different codec"] + pub quality_factor: u32, + #[doc = " Target frame size\n\n Desired frame size in bytes.\n This parameter can be used in some RC modes (like Transport Controlled BRC)\n where feedback from the app is required.\n Zero value means no limits.\n"] + pub target_frame_size: u32, + #[doc = " Reserved bytes for future use, must be zero."] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterRateControl__bindgen_ty_1 { + pub bits: _VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterRateControl__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn reset(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_reset(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reset_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reset_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_frame_skip(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_frame_skip(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_frame_skip_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_frame_skip_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_bit_stuffing(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_bit_stuffing(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_bit_stuffing_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_bit_stuffing_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_rate_control(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 4u8) as u32) } + } + #[inline] + pub fn set_mb_rate_control(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_rate_control_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_rate_control_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn temporal_id(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 8u8) as u32) } + } + #[inline] + pub fn set_temporal_id(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn temporal_id_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_temporal_id_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn cfs_I_frames(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_cfs_I_frames(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cfs_I_frames_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cfs_I_frames_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_parallel_brc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_parallel_brc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_parallel_brc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_parallel_brc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_dynamic_scaling(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_dynamic_scaling(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(17usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_dynamic_scaling_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 17usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_dynamic_scaling_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn frame_tolerance_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 2u8) as u32) } + } + #[inline] + pub fn set_frame_tolerance_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn frame_tolerance_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_frame_tolerance_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 12u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 12u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 12u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 12u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let reset: u32 = unsafe { ::std::mem::transmute(reset) }; + reset as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let disable_frame_skip: u32 = unsafe { ::std::mem::transmute(disable_frame_skip) }; + disable_frame_skip as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let disable_bit_stuffing: u32 = unsafe { ::std::mem::transmute(disable_bit_stuffing) }; + disable_bit_stuffing as u64 + }); + __bindgen_bitfield_unit.set(3usize, 4u8, { + let mb_rate_control: u32 = unsafe { ::std::mem::transmute(mb_rate_control) }; + mb_rate_control as u64 + }); + __bindgen_bitfield_unit.set(7usize, 8u8, { + let temporal_id: u32 = unsafe { ::std::mem::transmute(temporal_id) }; + temporal_id as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let cfs_I_frames: u32 = unsafe { ::std::mem::transmute(cfs_I_frames) }; + cfs_I_frames as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let enable_parallel_brc: u32 = unsafe { ::std::mem::transmute(enable_parallel_brc) }; + enable_parallel_brc as u64 + }); + __bindgen_bitfield_unit.set(17usize, 1u8, { + let enable_dynamic_scaling: u32 = unsafe { ::std::mem::transmute(enable_dynamic_scaling) }; + enable_dynamic_scaling as u64 + }); + __bindgen_bitfield_unit.set(18usize, 2u8, { + let frame_tolerance_mode: u32 = unsafe { ::std::mem::transmute(frame_tolerance_mode) }; + frame_tolerance_mode as u64 + }); + __bindgen_bitfield_unit.set(20usize, 12u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterRateControl__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterRateControl { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Rate control parameters"] +pub type VAEncMiscParameterRateControl = _VAEncMiscParameterRateControl; +#[doc = " Encode framerate parameters.\n\n Sets the encode framerate used by the rate controller. This should be\n provided in all modes using a bitrate target (variable framerate is not\n supported)."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterFrameRate { + #[doc = " Encode framerate.\n\n The framerate is specified as a number of frames per second, as a\n fraction. The denominator of the fraction is given in the top half\n (the high two bytes) of the framerate field, and the numerator is\n given in the bottom half (the low two bytes).\n\n That is:\n denominator = framerate >> 16 & 0xffff;\n numerator = framerate & 0xffff;\n fps = numerator / denominator;\n\n For example, if framerate is set to (100 << 16 | 750), this is\n 750 / 100, hence 7.5fps.\n\n If the denominator is zero (the high two bytes are both zero) then\n it takes the value one instead, so the framerate is just the integer\n in the low 2 bytes."] + pub framerate: u32, + pub framerate_flags: _VAEncMiscParameterFrameRate__bindgen_ty_1, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterFrameRate__bindgen_ty_1 { + pub bits: _VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterFrameRate__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn temporal_id(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 8u8) as u32) } + } + #[inline] + pub fn set_temporal_id(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn temporal_id_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_temporal_id_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 24u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 24u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 24u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 24u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(temporal_id: u32, reserved: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 8u8, { + let temporal_id: u32 = unsafe { ::std::mem::transmute(temporal_id) }; + temporal_id as u64 + }); + __bindgen_bitfield_unit.set(8usize, 24u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterFrameRate__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterFrameRate { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " Encode framerate parameters.\n\n Sets the encode framerate used by the rate controller. This should be\n provided in all modes using a bitrate target (variable framerate is not\n supported)."] +pub type VAEncMiscParameterFrameRate = _VAEncMiscParameterFrameRate; +#[doc = " Allow a maximum slice size to be specified (in bits).\n The encoder will attempt to make sure that individual slices do not exceed this size\n Or to signal applicate if the slice size exceed this size, see \"status\" of VACodedBufferSegment"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterMaxSliceSize { + pub max_slice_size: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " Allow a maximum slice size to be specified (in bits).\n The encoder will attempt to make sure that individual slices do not exceed this size\n Or to signal applicate if the slice size exceed this size, see \"status\" of VACodedBufferSegment"] +pub type VAEncMiscParameterMaxSliceSize = _VAEncMiscParameterMaxSliceSize; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterAIR { + pub air_num_mbs: u32, + pub air_threshold: u32, + pub air_auto: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +pub type VAEncMiscParameterAIR = _VAEncMiscParameterAIR; +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterRIR { + pub rir_flags: _VAEncMiscParameterRIR__bindgen_ty_1, + #[doc = " \\brief Indicates the column or row location in MB. It is ignored if\n rir_flags is 0."] + pub intra_insertion_location: u16, + #[doc = " \\brief Indicates the number of columns or rows in MB. It is ignored if\n rir_flags is 0."] + pub intra_insert_size: u16, + #[doc = " \\brief indicates the Qp difference for inserted intra columns or rows.\n App can use this to adjust intra Qp based on bitrate & max frame size."] + pub qp_delta_for_inserted_intra: u8, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterRIR__bindgen_ty_1 { + pub bits: _VAEncMiscParameterRIR__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterRIR__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterRIR__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn enable_rir_column(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_rir_column(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_rir_column_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_rir_column_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_rir_row(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_rir_row(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_rir_row_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_rir_row_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 30u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 30u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 30u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 30u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + enable_rir_column: u32, + enable_rir_row: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let enable_rir_column: u32 = unsafe { ::std::mem::transmute(enable_rir_column) }; + enable_rir_column as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let enable_rir_row: u32 = unsafe { ::std::mem::transmute(enable_rir_row) }; + enable_rir_row as u64 + }); + __bindgen_bitfield_unit.set(2usize, 30u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterRIR__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterRIR { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VAEncMiscParameterRIR = _VAEncMiscParameterRIR; +#[doc = " HRD / VBV buffering parameters for encoding.\n\n This sets the HRD / VBV parameters which will be used by the rate\n controller for encoding. It should be specified in modes using a bitrate\n target when the buffering of the output stream needs to be constrained.\n\n If not provided, the encoder may use arbitrary amounts of buffering."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterHRD { + #[doc = " The initial fullness of the HRD coded picture buffer, in bits.\n\n This sets how full the CPB is when encoding begins - that is, how much\n buffering will happen on the decoder side before the first frame.\n The CPB fullness will be reset to this value after any rate control\n reset (a change in parameters or an explicit reset).\n\n For H.264, it should match the value of initial_cpb_removal_delay in\n buffering_period SEI messages."] + pub initial_buffer_fullness: u32, + #[doc = " The HRD coded picture buffer size, in bits.\n\n For H.264, it should match the value of cpb_size_value_minus1 in the VUI\n parameters."] + pub buffer_size: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " HRD / VBV buffering parameters for encoding.\n\n This sets the HRD / VBV parameters which will be used by the rate\n controller for encoding. It should be specified in modes using a bitrate\n target when the buffering of the output stream needs to be constrained.\n\n If not provided, the encoder may use arbitrary amounts of buffering."] +pub type VAEncMiscParameterHRD = _VAEncMiscParameterHRD; +#[doc = " \\brief Defines a maximum frame size (in bits).\n\n This misc parameter buffer defines the maximum size of a frame (in\n bits). The encoder will try to make sure that each frame does not\n exceed this size. Otherwise, if the frame size exceeds this size,\n the \\c status flag of #VACodedBufferSegment will contain\n #VA_CODED_BUF_STATUS_FRAME_SIZE_OVERFLOW."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterBufferMaxFrameSize { + #[doc = " \\brief Type. Shall be set to #VAEncMiscParameterTypeMaxFrameSize. */\n/** duplicated with VAEncMiscParameterBuffer, should be deprecated"] + pub type_: VAEncMiscParameterType::Type, + #[doc = " \\brief Maximum size of a frame (in bits)."] + pub max_frame_size: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAEncMiscParameterBufferMaxFrameSize { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Defines a maximum frame size (in bits).\n\n This misc parameter buffer defines the maximum size of a frame (in\n bits). The encoder will try to make sure that each frame does not\n exceed this size. Otherwise, if the frame size exceeds this size,\n the \\c status flag of #VACodedBufferSegment will contain\n #VA_CODED_BUF_STATUS_FRAME_SIZE_OVERFLOW."] +pub type VAEncMiscParameterBufferMaxFrameSize = _VAEncMiscParameterBufferMaxFrameSize; +#[doc = " \\brief Maximum frame size (in bytes) settings for multiple pass.\n\n This misc parameter buffer defines the maximum size of a frame (in\n bytes) settings for multiple pass. currently only AVC encoder can\n support this settings in multiple pass case. If the frame size exceeds\n this size, the encoder will do more pak passes to adjust the QP value\n to control the frame size."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterBufferMultiPassFrameSize { + #[doc = " \\brief Type. Shall be set to #VAEncMiscParameterTypeMultiPassMaxFrameSize. */\n/** duplicated with VAEncMiscParameterBuffer, should be deprecated"] + pub type_: VAEncMiscParameterType::Type, + #[doc = " \\brief Maximum size of a frame (in byte)"] + pub max_frame_size: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub reserved: u32, + #[doc = " \\brief number of passes, every pass has different QP, currently AVC encoder can support up to 4 passes"] + pub num_passes: u8, + #[doc = " \\brief delta QP list for every pass"] + pub delta_qp: *mut u8, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [::std::os::raw::c_ulong; 4usize], +} +impl Default for _VAEncMiscParameterBufferMultiPassFrameSize { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Maximum frame size (in bytes) settings for multiple pass.\n\n This misc parameter buffer defines the maximum size of a frame (in\n bytes) settings for multiple pass. currently only AVC encoder can\n support this settings in multiple pass case. If the frame size exceeds\n this size, the encoder will do more pak passes to adjust the QP value\n to control the frame size."] +pub type VAEncMiscParameterBufferMultiPassFrameSize = _VAEncMiscParameterBufferMultiPassFrameSize; +#[doc = " \\brief Encoding quality level.\n\n The encoding quality could be set through this structure, if the implementation\n supports multiple quality levels. The quality level set through this structure is\n persistent over the entire coded sequence, or until a new structure is being sent.\n The quality level range can be queried through the VAConfigAttribEncQualityRange\n attribute. A lower value means higher quality, and a value of 1 represents the highest\n quality. The quality level setting is used as a trade-off between quality and speed/power\n consumption, with higher quality corresponds to lower speed and higher power consumption."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterBufferQualityLevel { + #[doc = " \\brief Encoding quality level setting. When set to 0, default quality\n level is used."] + pub quality_level: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Encoding quality level.\n\n The encoding quality could be set through this structure, if the implementation\n supports multiple quality levels. The quality level set through this structure is\n persistent over the entire coded sequence, or until a new structure is being sent.\n The quality level range can be queried through the VAConfigAttribEncQualityRange\n attribute. A lower value means higher quality, and a value of 1 represents the highest\n quality. The quality level setting is used as a trade-off between quality and speed/power\n consumption, with higher quality corresponds to lower speed and higher power consumption."] +pub type VAEncMiscParameterBufferQualityLevel = _VAEncMiscParameterBufferQualityLevel; +#[doc = " \\brief Quantization settings for encoding.\n\n Some encoders support special types of quantization such as trellis, and this structure\n can be used by the app to control these special types of quantization by the encoder."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterQuantization { + pub quantization_flags: _VAEncMiscParameterQuantization__bindgen_ty_1, + pub va_reserved: u32, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterQuantization__bindgen_ty_1 { + pub bits: _VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterQuantization__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn disable_trellis(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_trellis(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_trellis_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_trellis_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_trellis_I(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_trellis_I(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_trellis_I_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_trellis_I_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_trellis_P(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_trellis_P(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_trellis_P_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_trellis_P_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_trellis_B(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_trellis_B(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_trellis_B_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_trellis_B_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 28u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 28u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 28u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 28u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + disable_trellis: u32, + enable_trellis_I: u32, + enable_trellis_P: u32, + enable_trellis_B: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let disable_trellis: u32 = unsafe { ::std::mem::transmute(disable_trellis) }; + disable_trellis as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let enable_trellis_I: u32 = unsafe { ::std::mem::transmute(enable_trellis_I) }; + enable_trellis_I as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let enable_trellis_P: u32 = unsafe { ::std::mem::transmute(enable_trellis_P) }; + enable_trellis_P as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let enable_trellis_B: u32 = unsafe { ::std::mem::transmute(enable_trellis_B) }; + enable_trellis_B as u64 + }); + __bindgen_bitfield_unit.set(4usize, 28u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterQuantization__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterQuantization { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Quantization settings for encoding.\n\n Some encoders support special types of quantization such as trellis, and this structure\n can be used by the app to control these special types of quantization by the encoder."] +pub type VAEncMiscParameterQuantization = _VAEncMiscParameterQuantization; +#[doc = " \\brief Encoding skip frame.\n\n The application may choose to skip frames externally to the encoder (e.g. drop completely or\n code as all skip's). For rate control purposes the encoder will need to know the size and number\n of skipped frames. Skip frame(s) indicated through this structure is applicable only to the\n current frame. It is allowed for the application to still send in packed headers for the driver to\n pack, although no frame will be encoded (e.g. for HW to encrypt the frame)."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterSkipFrame { + #[doc = " \\brief Indicates skip frames as below.\n 0: Encode as normal, no skip.\n 1: One or more frames were skipped prior to the current frame, encode the current frame as normal.\n 2: The current frame is to be skipped, do not encode it but pack/encrypt the packed header contents\n (all except VAEncPackedHeaderSlice) which could contain actual frame contents (e.g. pack the frame\n in VAEncPackedHeaderPicture)."] + pub skip_frame_flag: u8, + #[doc = " \\brief The number of frames skipped prior to the current frame. Valid when skip_frame_flag = 1."] + pub num_skip_frames: u8, + #[doc = " \\brief When skip_frame_flag = 1, the size of the skipped frames in bits. When skip_frame_flag = 2,\n the size of the current skipped frame that is to be packed/encrypted in bits."] + pub size_skip_frames: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Encoding skip frame.\n\n The application may choose to skip frames externally to the encoder (e.g. drop completely or\n code as all skip's). For rate control purposes the encoder will need to know the size and number\n of skipped frames. Skip frame(s) indicated through this structure is applicable only to the\n current frame. It is allowed for the application to still send in packed headers for the driver to\n pack, although no frame will be encoded (e.g. for HW to encrypt the frame)."] +pub type VAEncMiscParameterSkipFrame = _VAEncMiscParameterSkipFrame; +#[doc = " \\brief Encoding region-of-interest (ROI).\n\n The encoding ROI can be set through VAEncMiscParameterBufferROI, if the implementation\n supports ROI input. The ROI set through this structure is applicable only to the\n current frame or field, so must be sent every frame or field to be applied. The number of\n supported ROIs can be queried through the VAConfigAttribEncROI. The encoder will use the\n ROI information to adjust the QP values of the MB's that fall within the ROIs."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncROI { + #[doc = " \\brief Defines the ROI boundary in pixels, the driver will map it to appropriate\n codec coding units. It is relative to frame coordinates for the frame case and\n to field coordinates for the field case."] + pub roi_rectangle: VARectangle, + #[doc = " \\brief ROI value\n\n \\ref roi_value specifies ROI delta QP or ROI priority.\n -- ROI delta QP is the value that will be added on top of the frame level QP.\n -- ROI priority specifies the priority of a region, it can be positive (more important)\n or negative (less important) values and is compared with non-ROI region (taken as value 0),\n E.g. ROI region with \\ref roi_value -3 is less important than the non-ROI region (\\ref roi_value\n implied to be 0) which is less important than ROI region with roi_value +2. For overlapping\n regions, the roi_value that is first in the ROI array will have priority.\n\n \\ref roi_value always specifes ROI delta QP when VAConfigAttribRateControl == VA_RC_CQP, no matter\n the value of \\c roi_value_is_qp_delta in #VAEncMiscParameterBufferROI.\n\n \\ref roi_value depends on \\c roi_value_is_qp_delta in #VAEncMiscParameterBufferROI when\n VAConfigAttribRateControl != VA_RC_CQP. \\ref roi_value specifies ROI_delta QP if \\c roi_value_is_qp_delta\n in VAEncMiscParameterBufferROI is 1, otherwise \\ref roi_value specifies ROI priority."] + pub roi_value: i8, +} +#[doc = " \\brief Encoding region-of-interest (ROI).\n\n The encoding ROI can be set through VAEncMiscParameterBufferROI, if the implementation\n supports ROI input. The ROI set through this structure is applicable only to the\n current frame or field, so must be sent every frame or field to be applied. The number of\n supported ROIs can be queried through the VAConfigAttribEncROI. The encoder will use the\n ROI information to adjust the QP values of the MB's that fall within the ROIs."] +pub type VAEncROI = _VAEncROI; +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterBufferROI { + #[doc = " \\brief Number of ROIs being sent."] + pub num_roi: u32, + #[doc = " \\brief Valid when VAConfigAttribRateControl != VA_RC_CQP, then the encoder's\n rate control will determine actual delta QPs. Specifies the max/min allowed delta\n QPs."] + pub max_delta_qp: i8, + pub min_delta_qp: i8, + #[doc = " \\brief Pointer to a VAEncROI array with num_roi elements. It is relative to frame\n coordinates for the frame case and to field coordinates for the field case."] + pub roi: *mut VAEncROI, + pub roi_flags: _VAEncMiscParameterBufferROI__bindgen_ty_1, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterBufferROI__bindgen_ty_1 { + pub bits: _VAEncMiscParameterBufferROI__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterBufferROI__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterBufferROI__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn roi_value_is_qp_delta(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_roi_value_is_qp_delta(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn roi_value_is_qp_delta_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_roi_value_is_qp_delta_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 31u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 31u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 31u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 31u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(roi_value_is_qp_delta: u32, reserved: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let roi_value_is_qp_delta: u32 = unsafe { ::std::mem::transmute(roi_value_is_qp_delta) }; + roi_value_is_qp_delta as u64 + }); + __bindgen_bitfield_unit.set(1usize, 31u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterBufferROI__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterBufferROI { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VAEncMiscParameterBufferROI = _VAEncMiscParameterBufferROI; +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterBufferDirtyRect { + #[doc = " \\brief Number of Rectangle being sent."] + pub num_roi_rectangle: u32, + #[doc = " \\brief Pointer to a VARectangle array with num_roi_rectangle elements."] + pub roi_rectangle: *mut VARectangle, +} +impl Default for _VAEncMiscParameterBufferDirtyRect { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VAEncMiscParameterBufferDirtyRect = _VAEncMiscParameterBufferDirtyRect; +#[doc = " \\brief Attribute value for VAConfigAttribEncParallelRateControl"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterParallelRateControl { + #[doc = " brief Number of layers"] + pub num_layers: u32, + #[doc = " brief Number of B frames per layer per GOP.\n\n it should be allocated by application, and the is num_layers.\n num_b_in_gop[0] is the number of regular B which refers to only I or P frames."] + pub num_b_in_gop: *mut u32, +} +impl Default for _VAEncMiscParameterParallelRateControl { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Attribute value for VAConfigAttribEncParallelRateControl"] +pub type VAEncMiscParameterParallelRateControl = _VAEncMiscParameterParallelRateControl; +#[doc = " per frame encoder quality controls, once set they will persist for all future frames\ntill it is updated again."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterEncQuality { + pub __bindgen_anon_1: _VAEncMiscParameterEncQuality__bindgen_ty_1, + #[doc = " Maps QP to skip thresholds when FTQ is enabled. Valid range is 0-255."] + pub FTQSkipThresholdLUT: [u8; 52usize], + #[doc = " Maps QP to skip thresholds when FTQ is disabled. Valid range is 0-65535."] + pub NonFTQSkipThresholdLUT: [u16; 52usize], + pub reserved: [u32; 16usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterEncQuality__bindgen_ty_1 { + pub __bindgen_anon_1: _VAEncMiscParameterEncQuality__bindgen_ty_1__bindgen_ty_1, + pub encControls: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterEncQuality__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, + pub __bindgen_padding_0: u8, +} +impl _VAEncMiscParameterEncQuality__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn useRawPicForRef(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_useRawPicForRef(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn useRawPicForRef_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_useRawPicForRef_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn skipCheckDisable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_skipCheckDisable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn skipCheckDisable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_skipCheckDisable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn FTQOverride(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_FTQOverride(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn FTQOverride_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_FTQOverride_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn FTQEnable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_FTQEnable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn FTQEnable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_FTQEnable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn FTQSkipThresholdLUTInput(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_FTQSkipThresholdLUTInput(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn FTQSkipThresholdLUTInput_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_FTQSkipThresholdLUTInput_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn NonFTQSkipThresholdLUTInput(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_NonFTQSkipThresholdLUTInput(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn NonFTQSkipThresholdLUTInput_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_NonFTQSkipThresholdLUTInput_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ReservedBit(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_ReservedBit(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn ReservedBit_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ReservedBit_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn directBiasAdjustmentEnable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_directBiasAdjustmentEnable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn directBiasAdjustmentEnable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_directBiasAdjustmentEnable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn globalMotionBiasAdjustmentEnable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_globalMotionBiasAdjustmentEnable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn globalMotionBiasAdjustmentEnable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_globalMotionBiasAdjustmentEnable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn HMEMVCostScalingFactor(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 2u8) as u32) } + } + #[inline] + pub fn set_HMEMVCostScalingFactor(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn HMEMVCostScalingFactor_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_HMEMVCostScalingFactor_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn HMEDisable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_HMEDisable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn HMEDisable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_HMEDisable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn SuperHMEDisable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_SuperHMEDisable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn SuperHMEDisable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_SuperHMEDisable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn UltraHMEDisable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_UltraHMEDisable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn UltraHMEDisable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_UltraHMEDisable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn PanicModeDisable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_PanicModeDisable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn PanicModeDisable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_PanicModeDisable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ForceRepartitionCheck(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 2u8) as u32) } + } + #[inline] + pub fn set_ForceRepartitionCheck(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn ForceRepartitionCheck_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ForceRepartitionCheck_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + useRawPicForRef: u32, + skipCheckDisable: u32, + FTQOverride: u32, + FTQEnable: u32, + FTQSkipThresholdLUTInput: u32, + NonFTQSkipThresholdLUTInput: u32, + ReservedBit: u32, + directBiasAdjustmentEnable: u32, + globalMotionBiasAdjustmentEnable: u32, + HMEMVCostScalingFactor: u32, + HMEDisable: u32, + SuperHMEDisable: u32, + UltraHMEDisable: u32, + PanicModeDisable: u32, + ForceRepartitionCheck: u32, + ) -> __BindgenBitfieldUnit<[u8; 3usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 3usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let useRawPicForRef: u32 = unsafe { ::std::mem::transmute(useRawPicForRef) }; + useRawPicForRef as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let skipCheckDisable: u32 = unsafe { ::std::mem::transmute(skipCheckDisable) }; + skipCheckDisable as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let FTQOverride: u32 = unsafe { ::std::mem::transmute(FTQOverride) }; + FTQOverride as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let FTQEnable: u32 = unsafe { ::std::mem::transmute(FTQEnable) }; + FTQEnable as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let FTQSkipThresholdLUTInput: u32 = unsafe { ::std::mem::transmute(FTQSkipThresholdLUTInput) }; + FTQSkipThresholdLUTInput as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let NonFTQSkipThresholdLUTInput: u32 = unsafe { ::std::mem::transmute(NonFTQSkipThresholdLUTInput) }; + NonFTQSkipThresholdLUTInput as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let ReservedBit: u32 = unsafe { ::std::mem::transmute(ReservedBit) }; + ReservedBit as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let directBiasAdjustmentEnable: u32 = unsafe { ::std::mem::transmute(directBiasAdjustmentEnable) }; + directBiasAdjustmentEnable as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let globalMotionBiasAdjustmentEnable: u32 = + unsafe { ::std::mem::transmute(globalMotionBiasAdjustmentEnable) }; + globalMotionBiasAdjustmentEnable as u64 + }); + __bindgen_bitfield_unit.set(9usize, 2u8, { + let HMEMVCostScalingFactor: u32 = unsafe { ::std::mem::transmute(HMEMVCostScalingFactor) }; + HMEMVCostScalingFactor as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let HMEDisable: u32 = unsafe { ::std::mem::transmute(HMEDisable) }; + HMEDisable as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let SuperHMEDisable: u32 = unsafe { ::std::mem::transmute(SuperHMEDisable) }; + SuperHMEDisable as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let UltraHMEDisable: u32 = unsafe { ::std::mem::transmute(UltraHMEDisable) }; + UltraHMEDisable as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let PanicModeDisable: u32 = unsafe { ::std::mem::transmute(PanicModeDisable) }; + PanicModeDisable as u64 + }); + __bindgen_bitfield_unit.set(15usize, 2u8, { + let ForceRepartitionCheck: u32 = unsafe { ::std::mem::transmute(ForceRepartitionCheck) }; + ForceRepartitionCheck as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterEncQuality__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterEncQuality { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " per frame encoder quality controls, once set they will persist for all future frames\ntill it is updated again."] +pub type VAEncMiscParameterEncQuality = _VAEncMiscParameterEncQuality; +#[doc = " \\brief Custom Encoder Rounding Offset Control.\n Application may use this structure to set customized rounding\n offset parameters for quantization.\n Valid when \\c VAConfigAttribCustomRoundingControl equals 1."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterCustomRoundingControl { + pub rounding_offset_setting: _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1 { + pub bits: _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn enable_custom_rouding_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_custom_rouding_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_custom_rouding_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_custom_rouding_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn rounding_offset_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 7u8) as u32) } + } + #[inline] + pub fn set_rounding_offset_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 7u8, val as u64) + } + } + #[inline] + pub unsafe fn rounding_offset_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 7u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_rounding_offset_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 7u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_custom_rounding_inter(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_custom_rounding_inter(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_custom_rounding_inter_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_custom_rounding_inter_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn rounding_offset_inter(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 7u8) as u32) } + } + #[inline] + pub fn set_rounding_offset_inter(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 7u8, val as u64) + } + } + #[inline] + pub unsafe fn rounding_offset_inter_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 7u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_rounding_offset_inter_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 7u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + enable_custom_rouding_intra: u32, + rounding_offset_intra: u32, + enable_custom_rounding_inter: u32, + rounding_offset_inter: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let enable_custom_rouding_intra: u32 = unsafe { ::std::mem::transmute(enable_custom_rouding_intra) }; + enable_custom_rouding_intra as u64 + }); + __bindgen_bitfield_unit.set(1usize, 7u8, { + let rounding_offset_intra: u32 = unsafe { ::std::mem::transmute(rounding_offset_intra) }; + rounding_offset_intra as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let enable_custom_rounding_inter: u32 = unsafe { ::std::mem::transmute(enable_custom_rounding_inter) }; + enable_custom_rounding_inter as u64 + }); + __bindgen_bitfield_unit.set(9usize, 7u8, { + let rounding_offset_inter: u32 = unsafe { ::std::mem::transmute(rounding_offset_inter) }; + rounding_offset_inter as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterCustomRoundingControl__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterCustomRoundingControl { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Custom Encoder Rounding Offset Control.\n Application may use this structure to set customized rounding\n offset parameters for quantization.\n Valid when \\c VAConfigAttribCustomRoundingControl equals 1."] +pub type VAEncMiscParameterCustomRoundingControl = _VAEncMiscParameterCustomRoundingControl; +#[doc = " H.264/AVC data structures"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureH264 { + pub picture_id: VASurfaceID, + pub frame_idx: u32, + pub flags: u32, + pub TopFieldOrderCnt: i32, + pub BottomFieldOrderCnt: i32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " H.264/AVC data structures"] +pub type VAPictureH264 = _VAPictureH264; +#[doc = " H.264 Picture Parameter Buffer"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAPictureParameterBufferH264 { + pub CurrPic: VAPictureH264, + pub ReferenceFrames: [VAPictureH264; 16usize], + pub picture_width_in_mbs_minus1: u16, + pub picture_height_in_mbs_minus1: u16, + pub bit_depth_luma_minus8: u8, + pub bit_depth_chroma_minus8: u8, + pub num_ref_frames: u8, + pub seq_fields: _VAPictureParameterBufferH264__bindgen_ty_1, + pub num_slice_groups_minus1: u8, + pub slice_group_map_type: u8, + pub slice_group_change_rate_minus1: u16, + pub pic_init_qp_minus26: i8, + pub pic_init_qs_minus26: i8, + pub chroma_qp_index_offset: i8, + pub second_chroma_qp_index_offset: i8, + pub pic_fields: _VAPictureParameterBufferH264__bindgen_ty_2, + pub frame_num: u16, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 8usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferH264__bindgen_ty_1 { + pub bits: _VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, + pub __bindgen_padding_0: u8, +} +impl _VAPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn chroma_format_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_chroma_format_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_format_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_format_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn residual_colour_transform_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_residual_colour_transform_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn residual_colour_transform_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_residual_colour_transform_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn gaps_in_frame_num_value_allowed_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_gaps_in_frame_num_value_allowed_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn gaps_in_frame_num_value_allowed_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_gaps_in_frame_num_value_allowed_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn frame_mbs_only_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_frame_mbs_only_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn frame_mbs_only_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_frame_mbs_only_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_adaptive_frame_field_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_adaptive_frame_field_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_adaptive_frame_field_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_adaptive_frame_field_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn direct_8x8_inference_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_direct_8x8_inference_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn direct_8x8_inference_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_direct_8x8_inference_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn MinLumaBiPredSize8x8(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_MinLumaBiPredSize8x8(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn MinLumaBiPredSize8x8_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_MinLumaBiPredSize8x8_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_frame_num_minus4(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 4u8) as u32) } + } + #[inline] + pub fn set_log2_max_frame_num_minus4(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_frame_num_minus4_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_frame_num_minus4_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn pic_order_cnt_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 2u8) as u32) } + } + #[inline] + pub fn set_pic_order_cnt_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn pic_order_cnt_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pic_order_cnt_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_pic_order_cnt_lsb_minus4(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 4u8) as u32) } + } + #[inline] + pub fn set_log2_max_pic_order_cnt_lsb_minus4(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_pic_order_cnt_lsb_minus4_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_pic_order_cnt_lsb_minus4_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn delta_pic_order_always_zero_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u32) } + } + #[inline] + pub fn set_delta_pic_order_always_zero_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn delta_pic_order_always_zero_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_delta_pic_order_always_zero_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + MinLumaBiPredSize8x8: 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, + ) -> __BindgenBitfieldUnit<[u8; 3usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 3usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let chroma_format_idc: u32 = unsafe { ::std::mem::transmute(chroma_format_idc) }; + chroma_format_idc as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let residual_colour_transform_flag: u32 = unsafe { ::std::mem::transmute(residual_colour_transform_flag) }; + residual_colour_transform_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let gaps_in_frame_num_value_allowed_flag: u32 = + unsafe { ::std::mem::transmute(gaps_in_frame_num_value_allowed_flag) }; + gaps_in_frame_num_value_allowed_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let frame_mbs_only_flag: u32 = unsafe { ::std::mem::transmute(frame_mbs_only_flag) }; + frame_mbs_only_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let mb_adaptive_frame_field_flag: u32 = unsafe { ::std::mem::transmute(mb_adaptive_frame_field_flag) }; + mb_adaptive_frame_field_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let direct_8x8_inference_flag: u32 = unsafe { ::std::mem::transmute(direct_8x8_inference_flag) }; + direct_8x8_inference_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let MinLumaBiPredSize8x8: u32 = unsafe { ::std::mem::transmute(MinLumaBiPredSize8x8) }; + MinLumaBiPredSize8x8 as u64 + }); + __bindgen_bitfield_unit.set(8usize, 4u8, { + let log2_max_frame_num_minus4: u32 = unsafe { ::std::mem::transmute(log2_max_frame_num_minus4) }; + log2_max_frame_num_minus4 as u64 + }); + __bindgen_bitfield_unit.set(12usize, 2u8, { + let pic_order_cnt_type: u32 = unsafe { ::std::mem::transmute(pic_order_cnt_type) }; + pic_order_cnt_type as u64 + }); + __bindgen_bitfield_unit.set(14usize, 4u8, { + let log2_max_pic_order_cnt_lsb_minus4: u32 = + unsafe { ::std::mem::transmute(log2_max_pic_order_cnt_lsb_minus4) }; + log2_max_pic_order_cnt_lsb_minus4 as u64 + }); + __bindgen_bitfield_unit.set(18usize, 1u8, { + let delta_pic_order_always_zero_flag: u32 = + unsafe { ::std::mem::transmute(delta_pic_order_always_zero_flag) }; + delta_pic_order_always_zero_flag as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferH264__bindgen_ty_2 { + pub bits: _VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, + pub __bindgen_padding_0: u16, +} +impl _VAPictureParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + #[inline] + pub fn entropy_coding_mode_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_entropy_coding_mode_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn entropy_coding_mode_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_entropy_coding_mode_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_bipred_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_weighted_bipred_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_bipred_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_bipred_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_8x8_mode_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_8x8_mode_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_8x8_mode_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_8x8_mode_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn field_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_field_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn field_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_field_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn constrained_intra_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_constrained_intra_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn constrained_intra_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_constrained_intra_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pic_order_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_pic_order_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pic_order_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pic_order_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn deblocking_filter_control_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_deblocking_filter_control_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn deblocking_filter_control_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_deblocking_filter_control_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn redundant_pic_cnt_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_redundant_pic_cnt_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn redundant_pic_cnt_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_redundant_pic_cnt_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reference_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_reference_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reference_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reference_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + ) -> __BindgenBitfieldUnit<[u8; 2usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let entropy_coding_mode_flag: u32 = unsafe { ::std::mem::transmute(entropy_coding_mode_flag) }; + entropy_coding_mode_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let weighted_pred_flag: u32 = unsafe { ::std::mem::transmute(weighted_pred_flag) }; + weighted_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let weighted_bipred_idc: u32 = unsafe { ::std::mem::transmute(weighted_bipred_idc) }; + weighted_bipred_idc as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let transform_8x8_mode_flag: u32 = unsafe { ::std::mem::transmute(transform_8x8_mode_flag) }; + transform_8x8_mode_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let field_pic_flag: u32 = unsafe { ::std::mem::transmute(field_pic_flag) }; + field_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let constrained_intra_pred_flag: u32 = unsafe { ::std::mem::transmute(constrained_intra_pred_flag) }; + constrained_intra_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let pic_order_present_flag: u32 = unsafe { ::std::mem::transmute(pic_order_present_flag) }; + pic_order_present_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let deblocking_filter_control_present_flag: u32 = + unsafe { ::std::mem::transmute(deblocking_filter_control_present_flag) }; + deblocking_filter_control_present_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let redundant_pic_cnt_present_flag: u32 = unsafe { ::std::mem::transmute(redundant_pic_cnt_present_flag) }; + redundant_pic_cnt_present_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let reference_pic_flag: u32 = unsafe { ::std::mem::transmute(reference_pic_flag) }; + reference_pic_flag as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferH264__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAPictureParameterBufferH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " H.264 Picture Parameter Buffer"] +pub type VAPictureParameterBufferH264 = _VAPictureParameterBufferH264; +#[doc = " H.264 Inverse Quantization Matrix Buffer"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAIQMatrixBufferH264 { + #[doc = " \\brief 4x4 scaling list, in raster scan order."] + pub ScalingList4x4: [[u8; 16usize]; 6usize], + #[doc = " \\brief 8x8 scaling list, in raster scan order."] + pub ScalingList8x8: [[u8; 64usize]; 2usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAIQMatrixBufferH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " H.264 Inverse Quantization Matrix Buffer"] +pub type VAIQMatrixBufferH264 = _VAIQMatrixBufferH264; +#[doc = " H.264 Slice Parameter Buffer"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VASliceParameterBufferH264 { + pub slice_data_size: u32, + #[doc = " \\brief Byte offset to the NAL Header Unit for this slice."] + pub slice_data_offset: u32, + pub slice_data_flag: u32, + #[doc = " \\brief Bit offset from NAL Header Unit to the begining of slice_data().\n\n This bit offset is relative to and includes the NAL unit byte\n and represents the number of bits parsed in the slice_header()\n after the removal of any emulation prevention bytes in\n there. However, the slice data buffer passed to the hardware is\n the original bitstream, thus including any emulation prevention\n bytes."] + pub slice_data_bit_offset: u16, + pub first_mb_in_slice: u16, + pub slice_type: u8, + pub direct_spatial_mv_pred_flag: u8, + #[doc = " H264/AVC syntax element\n\n if num_ref_idx_active_override_flag equals 0, host decoder should\n set its value to num_ref_idx_l0_default_active_minus1."] + pub num_ref_idx_l0_active_minus1: u8, + #[doc = " H264/AVC syntax element\n\n if num_ref_idx_active_override_flag equals 0, host decoder should\n set its value to num_ref_idx_l1_default_active_minus1."] + pub num_ref_idx_l1_active_minus1: u8, + pub cabac_init_idc: u8, + pub slice_qp_delta: i8, + pub disable_deblocking_filter_idc: u8, + pub slice_alpha_c0_offset_div2: i8, + pub slice_beta_offset_div2: i8, + pub RefPicList0: [VAPictureH264; 32usize], + pub RefPicList1: [VAPictureH264; 32usize], + pub luma_log2_weight_denom: u8, + pub chroma_log2_weight_denom: u8, + pub luma_weight_l0_flag: u8, + pub luma_weight_l0: [i16; 32usize], + pub luma_offset_l0: [i16; 32usize], + pub chroma_weight_l0_flag: u8, + pub chroma_weight_l0: [[i16; 2usize]; 32usize], + pub chroma_offset_l0: [[i16; 2usize]; 32usize], + pub luma_weight_l1_flag: u8, + pub luma_weight_l1: [i16; 32usize], + pub luma_offset_l1: [i16; 32usize], + pub chroma_weight_l1_flag: u8, + pub chroma_weight_l1: [[i16; 2usize]; 32usize], + pub chroma_offset_l1: [[i16; 2usize]; 32usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " H.264 Slice Parameter Buffer"] +pub type VASliceParameterBufferH264 = _VASliceParameterBufferH264; +#[doc = " \\brief Coded buffer segment.\n\n #VACodedBufferSegment is an element of a linked list describing\n some information on the coded buffer. The coded buffer segment\n could contain either a single NAL unit, or more than one NAL unit.\n It is recommended (but not required) to return a single NAL unit\n in a coded buffer segment, and the implementation should set the\n VA_CODED_BUF_STATUS_SINGLE_NALU status flag if that is the case."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VACodedBufferSegment { + #[doc = " \\brief Size of the data buffer in this segment (in bytes)."] + pub size: u32, + #[doc = " \\brief Bit offset into the data buffer where the video data starts."] + pub bit_offset: u32, + #[doc = " \\brief Status set by the driver. See \\c VA_CODED_BUF_STATUS_*."] + pub status: u32, + #[doc = " \\brief Reserved for future use."] + pub reserved: u32, + #[doc = " \\brief Pointer to the start of the data buffer."] + pub buf: *mut ::std::os::raw::c_void, + #[doc = " \\brief Pointer to the next #VACodedBufferSegment element,\n or \\c NULL if there is none."] + pub next: *mut ::std::os::raw::c_void, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VACodedBufferSegment { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Coded buffer segment.\n\n #VACodedBufferSegment is an element of a linked list describing\n some information on the coded buffer. The coded buffer segment\n could contain either a single NAL unit, or more than one NAL unit.\n It is recommended (but not required) to return a single NAL unit\n in a coded buffer segment, and the implementation should set the\n VA_CODED_BUF_STATUS_SINGLE_NALU status flag if that is the case."] +pub type VACodedBufferSegment = _VACodedBufferSegment; +#[doc = " \\brief VA buffer information"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct VABufferInfo { + #[doc = " \\brief Buffer handle"] + pub handle: usize, + #[doc = " \\brief Buffer type (See \\ref VABufferType)."] + pub type_: u32, + #[doc = " \\brief Buffer memory type (See \\ref VASurfaceAttribMemoryType).\n\n On input to vaAcquireBufferHandle(), this field can serve as a hint\n to specify the set of memory types the caller is interested in.\n On successful return from vaAcquireBufferHandle(), the field is\n updated with the best matching memory type."] + pub mem_type: u32, + #[doc = " \\brief Size of the underlying buffer."] + pub mem_size: usize, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +pub mod VASurfaceStatus { + pub type Type = ::std::os::raw::c_uint; + pub const VASurfaceRendering: Type = 1; + pub const VASurfaceDisplaying: Type = 2; + pub const VASurfaceReady: Type = 4; + pub const VASurfaceSkipped: Type = 8; +} +pub mod VADecodeErrorType { + pub type Type = ::std::os::raw::c_uint; + pub const VADecodeSliceMissing: Type = 0; + pub const VADecodeMBError: Type = 1; + pub const VADecodeReset: Type = 2; +} +#[doc = " Client calls vaQuerySurfaceError with VA_STATUS_ERROR_DECODING_ERROR, server side returns\n an array of structure VASurfaceDecodeMBErrors, and the array is terminated by setting status=-1"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VASurfaceDecodeMBErrors { + pub status: i32, + pub start_mb: u32, + pub end_mb: u32, + pub decode_error_type: VADecodeErrorType::Type, + pub num_mb: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 3usize], +} +impl Default for _VASurfaceDecodeMBErrors { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " Client calls vaQuerySurfaceError with VA_STATUS_ERROR_DECODING_ERROR, server side returns\n an array of structure VASurfaceDecodeMBErrors, and the array is terminated by setting status=-1"] +pub type VASurfaceDecodeMBErrors = _VASurfaceDecodeMBErrors; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAImageFormat { + pub fourcc: u32, + pub byte_order: u32, + pub bits_per_pixel: u32, + pub depth: u32, + pub red_mask: u32, + pub green_mask: u32, + pub blue_mask: u32, + pub alpha_mask: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +pub type VAImageFormat = _VAImageFormat; +pub type VAImageID = VAGenericID; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAImage { + pub image_id: VAImageID, + pub format: VAImageFormat, + pub buf: VABufferID, + pub width: u16, + pub height: u16, + pub data_size: u32, + pub num_planes: u32, + pub pitches: [u32; 3usize], + pub offsets: [u32; 3usize], + pub num_palette_entries: i32, + pub entry_bytes: i32, + pub component_order: [i8; 4usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +pub type VAImage = _VAImage; +#[doc = " Subpictures\n Subpicture is a special type of image that can be blended\n with a surface during vaPutSurface(). Subpicture can be used to render\n DVD sub-titles or closed captioning text etc."] +pub type VASubpictureID = VAGenericID; +pub mod VADisplayAttribType { + #[doc = " Currently defined display attribute types"] + pub type Type = ::std::os::raw::c_uint; + pub const VADisplayAttribBrightness: Type = 0; + pub const VADisplayAttribContrast: Type = 1; + pub const VADisplayAttribHue: Type = 2; + pub const VADisplayAttribSaturation: Type = 3; + pub const VADisplayAttribBackgroundColor: Type = 4; + pub const VADisplayAttribDirectSurface: Type = 5; + pub const VADisplayAttribRotation: Type = 6; + pub const VADisplayAttribOutofLoopDeblock: Type = 7; + pub const VADisplayAttribBLEBlackMode: Type = 8; + pub const VADisplayAttribBLEWhiteMode: Type = 9; + pub const VADisplayAttribBlueStretch: Type = 10; + pub const VADisplayAttribSkinColorCorrection: Type = 11; + pub const VADisplayAttribCSCMatrix: Type = 12; + pub const VADisplayAttribBlendColor: Type = 13; + pub const VADisplayAttribOverlayAutoPaintColorKey: Type = 14; + pub const VADisplayAttribOverlayColorKey: Type = 15; + pub const VADisplayAttribRenderMode: Type = 16; + pub const VADisplayAttribRenderDevice: Type = 17; + pub const VADisplayAttribRenderRect: Type = 18; + pub const VADisplayAttribSubDevice: Type = 19; + pub const VADisplayAttribCopy: Type = 20; + pub const VADisplayPCIID: Type = 21; +} +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VADisplayAttribute { + pub type_: VADisplayAttribType::Type, + pub min_value: i32, + pub max_value: i32, + pub value: i32, + pub flags: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VADisplayAttribute { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VADisplayAttribute = _VADisplayAttribute; +#[doc = " HEVC data structures\n/\n/**\n \\brief Description of picture properties of those in DPB surfaces.\n\n If only progressive scan is supported, each surface contains one whole\n frame picture.\n Otherwise, each surface contains two fields of whole picture.\n In this case, two entries of ReferenceFrames[] may share same picture_id\n value."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureHEVC { + #[doc = " \\brief reconstructed picture buffer surface index\n invalid when taking value VA_INVALID_SURFACE."] + pub picture_id: VASurfaceID, + #[doc = " \\brief picture order count.\n in HEVC, POCs for top and bottom fields of same picture should\n take different values."] + pub pic_order_cnt: i32, + pub flags: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " HEVC data structures\n/\n/**\n \\brief Description of picture properties of those in DPB surfaces.\n\n If only progressive scan is supported, each surface contains one whole\n frame picture.\n Otherwise, each surface contains two fields of whole picture.\n In this case, two entries of ReferenceFrames[] may share same picture_id\n value."] +pub type VAPictureHEVC = _VAPictureHEVC; +pub mod VACopyObjectType { + pub type Type = ::std::os::raw::c_uint; + pub const VACopyObjectSurface: Type = 0; + pub const VACopyObjectBuffer: Type = 1; +} +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VACopyObject { + pub obj_type: VACopyObjectType::Type, + pub object: _VACopyObject__bindgen_ty_1, + pub va_reserved: [u32; 8usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VACopyObject__bindgen_ty_1 { + pub surface_id: VASurfaceID, + pub buffer_id: VABufferID, +} +impl Default for _VACopyObject__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VACopyObject { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VACopyObject = _VACopyObject; +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VACopyOption { + pub bits: _VACopyOption__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VACopyOption__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VACopyOption__bindgen_ty_1 { + #[inline] + pub fn va_copy_sync(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_va_copy_sync(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn va_copy_sync_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_va_copy_sync_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn va_copy_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 4u8) as u32) } + } + #[inline] + pub fn set_va_copy_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn va_copy_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_va_copy_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 26u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 26u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 26u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 26u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(va_copy_sync: u32, va_copy_mode: u32, reserved: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let va_copy_sync: u32 = unsafe { ::std::mem::transmute(va_copy_sync) }; + va_copy_sync as u64 + }); + __bindgen_bitfield_unit.set(2usize, 4u8, { + let va_copy_mode: u32 = unsafe { ::std::mem::transmute(va_copy_mode) }; + va_copy_mode as u64 + }); + __bindgen_bitfield_unit.set(6usize, 26u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VACopyOption { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub type VACopyOption = _VACopyOption; +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure\n\n This structure conveys picture level parameters and should be sent once\n per frame.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAPictureParameterBufferHEVC { + #[doc = " \\brief buffer description of decoded current picture\n only VA_PICTURE_HEVC_FIELD_PIC and VA_PICTURE_HEVC_BOTTOM_FIELD\n of \"flags\" fields are meaningful."] + pub CurrPic: VAPictureHEVC, + #[doc = " \\brief buffer description of reference frames in DPB"] + pub ReferenceFrames: [VAPictureHEVC; 15usize], + #[doc = " \\brief picture width, shall be integer multiple of minimum CB size."] + pub pic_width_in_luma_samples: u16, + #[doc = " \\brief picture height, shall be integer multiple of minimum CB size."] + pub pic_height_in_luma_samples: u16, + pub pic_fields: _VAPictureParameterBufferHEVC__bindgen_ty_1, + #[doc = " following parameters have same syntax with those in HEVC spec */\n/** \\brief DPB size for current temporal layer"] + pub sps_max_dec_pic_buffering_minus1: u8, + pub bit_depth_luma_minus8: u8, + pub bit_depth_chroma_minus8: u8, + pub pcm_sample_bit_depth_luma_minus1: u8, + pub pcm_sample_bit_depth_chroma_minus1: u8, + pub log2_min_luma_coding_block_size_minus3: u8, + pub log2_diff_max_min_luma_coding_block_size: u8, + pub log2_min_transform_block_size_minus2: u8, + pub log2_diff_max_min_transform_block_size: u8, + pub log2_min_pcm_luma_coding_block_size_minus3: u8, + pub log2_diff_max_min_pcm_luma_coding_block_size: u8, + pub max_transform_hierarchy_depth_intra: u8, + pub max_transform_hierarchy_depth_inter: u8, + pub init_qp_minus26: i8, + pub diff_cu_qp_delta_depth: u8, + pub pps_cb_qp_offset: i8, + pub pps_cr_qp_offset: i8, + pub log2_parallel_merge_level_minus2: u8, + pub num_tile_columns_minus1: u8, + pub num_tile_rows_minus1: u8, + #[doc = " when uniform_spacing_flag equals 1, application should populate\n column_width_minus[], and row_height_minus1[] with approperiate values."] + pub column_width_minus1: [u16; 19usize], + pub row_height_minus1: [u16; 21usize], + pub slice_parsing_fields: _VAPictureParameterBufferHEVC__bindgen_ty_2, + #[doc = " following parameters have same syntax with those in HEVC spec"] + pub log2_max_pic_order_cnt_lsb_minus4: u8, + pub num_short_term_ref_pic_sets: u8, + pub num_long_term_ref_pic_sps: u8, + pub num_ref_idx_l0_default_active_minus1: u8, + pub num_ref_idx_l1_default_active_minus1: u8, + pub pps_beta_offset_div2: i8, + pub pps_tc_offset_div2: i8, + pub num_extra_slice_header_bits: u8, + #[doc = " \\brief number of bits that structure\n short_term_ref_pic_set( num_short_term_ref_pic_sets ) takes in slice\n segment header when short_term_ref_pic_set_sps_flag equals 0.\n if short_term_ref_pic_set_sps_flag equals 1, the value should be 0.\n the bit count is calculated after emulation prevention bytes are removed\n from bit streams.\n This variable is used for accelorater to skip parsing the\n short_term_ref_pic_set( num_short_term_ref_pic_sets ) structure."] + pub st_rps_bits: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 8usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferHEVC__bindgen_ty_1 { + pub bits: _VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn chroma_format_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_chroma_format_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_format_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_format_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn separate_colour_plane_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_separate_colour_plane_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn separate_colour_plane_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_separate_colour_plane_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pcm_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_pcm_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pcm_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pcm_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn scaling_list_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_scaling_list_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn scaling_list_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_scaling_list_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_skip_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_skip_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_skip_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_skip_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn amp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_amp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn amp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_amp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn strong_intra_smoothing_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_strong_intra_smoothing_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn strong_intra_smoothing_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_strong_intra_smoothing_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sign_data_hiding_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_sign_data_hiding_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sign_data_hiding_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sign_data_hiding_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn constrained_intra_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_constrained_intra_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn constrained_intra_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_constrained_intra_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cu_qp_delta_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_cu_qp_delta_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cu_qp_delta_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cu_qp_delta_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_bipred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_bipred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_bipred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_bipred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transquant_bypass_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_transquant_bypass_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transquant_bypass_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transquant_bypass_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn tiles_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_tiles_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn tiles_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_tiles_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn entropy_coding_sync_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_entropy_coding_sync_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn entropy_coding_sync_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_entropy_coding_sync_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pps_loop_filter_across_slices_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_loop_filter_across_slices_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_loop_filter_across_slices_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_loop_filter_across_slices_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn loop_filter_across_tiles_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } + } + #[inline] + pub fn set_loop_filter_across_tiles_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(17usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn loop_filter_across_tiles_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 17usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_loop_filter_across_tiles_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pcm_loop_filter_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u32) } + } + #[inline] + pub fn set_pcm_loop_filter_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pcm_loop_filter_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pcm_loop_filter_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn NoPicReorderingFlag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(19usize, 1u8) as u32) } + } + #[inline] + pub fn set_NoPicReorderingFlag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(19usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn NoPicReorderingFlag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 19usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_NoPicReorderingFlag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 19usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn NoBiPredFlag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 1u8) as u32) } + } + #[inline] + pub fn set_NoBiPredFlag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn NoBiPredFlag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_NoBiPredFlag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ReservedBits(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(21usize, 11u8) as u32) } + } + #[inline] + pub fn set_ReservedBits(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(21usize, 11u8, val as u64) + } + } + #[inline] + pub unsafe fn ReservedBits_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 21usize, + 11u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ReservedBits_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 21usize, + 11u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + NoPicReorderingFlag: u32, + NoBiPredFlag: u32, + ReservedBits: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let chroma_format_idc: u32 = unsafe { ::std::mem::transmute(chroma_format_idc) }; + chroma_format_idc as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let separate_colour_plane_flag: u32 = unsafe { ::std::mem::transmute(separate_colour_plane_flag) }; + separate_colour_plane_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let pcm_enabled_flag: u32 = unsafe { ::std::mem::transmute(pcm_enabled_flag) }; + pcm_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let scaling_list_enabled_flag: u32 = unsafe { ::std::mem::transmute(scaling_list_enabled_flag) }; + scaling_list_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let transform_skip_enabled_flag: u32 = unsafe { ::std::mem::transmute(transform_skip_enabled_flag) }; + transform_skip_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let amp_enabled_flag: u32 = unsafe { ::std::mem::transmute(amp_enabled_flag) }; + amp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let strong_intra_smoothing_enabled_flag: u32 = + unsafe { ::std::mem::transmute(strong_intra_smoothing_enabled_flag) }; + strong_intra_smoothing_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let sign_data_hiding_enabled_flag: u32 = unsafe { ::std::mem::transmute(sign_data_hiding_enabled_flag) }; + sign_data_hiding_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let constrained_intra_pred_flag: u32 = unsafe { ::std::mem::transmute(constrained_intra_pred_flag) }; + constrained_intra_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let cu_qp_delta_enabled_flag: u32 = unsafe { ::std::mem::transmute(cu_qp_delta_enabled_flag) }; + cu_qp_delta_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let weighted_pred_flag: u32 = unsafe { ::std::mem::transmute(weighted_pred_flag) }; + weighted_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let weighted_bipred_flag: u32 = unsafe { ::std::mem::transmute(weighted_bipred_flag) }; + weighted_bipred_flag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let transquant_bypass_enabled_flag: u32 = unsafe { ::std::mem::transmute(transquant_bypass_enabled_flag) }; + transquant_bypass_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let tiles_enabled_flag: u32 = unsafe { ::std::mem::transmute(tiles_enabled_flag) }; + tiles_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let entropy_coding_sync_enabled_flag: u32 = + unsafe { ::std::mem::transmute(entropy_coding_sync_enabled_flag) }; + entropy_coding_sync_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let pps_loop_filter_across_slices_enabled_flag: u32 = + unsafe { ::std::mem::transmute(pps_loop_filter_across_slices_enabled_flag) }; + pps_loop_filter_across_slices_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(17usize, 1u8, { + let loop_filter_across_tiles_enabled_flag: u32 = + unsafe { ::std::mem::transmute(loop_filter_across_tiles_enabled_flag) }; + loop_filter_across_tiles_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(18usize, 1u8, { + let pcm_loop_filter_disabled_flag: u32 = unsafe { ::std::mem::transmute(pcm_loop_filter_disabled_flag) }; + pcm_loop_filter_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(19usize, 1u8, { + let NoPicReorderingFlag: u32 = unsafe { ::std::mem::transmute(NoPicReorderingFlag) }; + NoPicReorderingFlag as u64 + }); + __bindgen_bitfield_unit.set(20usize, 1u8, { + let NoBiPredFlag: u32 = unsafe { ::std::mem::transmute(NoBiPredFlag) }; + NoBiPredFlag as u64 + }); + __bindgen_bitfield_unit.set(21usize, 11u8, { + let ReservedBits: u32 = unsafe { ::std::mem::transmute(ReservedBits) }; + ReservedBits as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferHEVC__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Parameters needed for parsing slice segment headers"] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferHEVC__bindgen_ty_2 { + pub bits: _VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + #[inline] + pub fn lists_modification_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_lists_modification_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn lists_modification_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_lists_modification_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn long_term_ref_pics_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_long_term_ref_pics_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn long_term_ref_pics_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_long_term_ref_pics_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sps_temporal_mvp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_sps_temporal_mvp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sps_temporal_mvp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sps_temporal_mvp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cabac_init_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_cabac_init_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cabac_init_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cabac_init_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn output_flag_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_output_flag_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn output_flag_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_output_flag_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dependent_slice_segments_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_dependent_slice_segments_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dependent_slice_segments_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dependent_slice_segments_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pps_slice_chroma_qp_offsets_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_slice_chroma_qp_offsets_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_slice_chroma_qp_offsets_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_slice_chroma_qp_offsets_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sample_adaptive_offset_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_sample_adaptive_offset_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sample_adaptive_offset_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sample_adaptive_offset_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn deblocking_filter_override_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_deblocking_filter_override_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn deblocking_filter_override_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_deblocking_filter_override_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pps_disable_deblocking_filter_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_disable_deblocking_filter_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_disable_deblocking_filter_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_disable_deblocking_filter_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_segment_header_extension_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_segment_header_extension_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_segment_header_extension_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_segment_header_extension_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn RapPicFlag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_RapPicFlag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn RapPicFlag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_RapPicFlag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn IdrPicFlag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_IdrPicFlag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn IdrPicFlag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_IdrPicFlag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn IntraPicFlag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_IntraPicFlag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn IntraPicFlag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_IntraPicFlag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ReservedBits(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 18u8) as u32) } + } + #[inline] + pub fn set_ReservedBits(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 18u8, val as u64) + } + } + #[inline] + pub unsafe fn ReservedBits_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 18u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ReservedBits_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 18u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + RapPicFlag: u32, + IdrPicFlag: u32, + IntraPicFlag: u32, + ReservedBits: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let lists_modification_present_flag: u32 = + unsafe { ::std::mem::transmute(lists_modification_present_flag) }; + lists_modification_present_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let long_term_ref_pics_present_flag: u32 = + unsafe { ::std::mem::transmute(long_term_ref_pics_present_flag) }; + long_term_ref_pics_present_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let sps_temporal_mvp_enabled_flag: u32 = unsafe { ::std::mem::transmute(sps_temporal_mvp_enabled_flag) }; + sps_temporal_mvp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let cabac_init_present_flag: u32 = unsafe { ::std::mem::transmute(cabac_init_present_flag) }; + cabac_init_present_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let output_flag_present_flag: u32 = unsafe { ::std::mem::transmute(output_flag_present_flag) }; + output_flag_present_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let dependent_slice_segments_enabled_flag: u32 = + unsafe { ::std::mem::transmute(dependent_slice_segments_enabled_flag) }; + dependent_slice_segments_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let pps_slice_chroma_qp_offsets_present_flag: u32 = + unsafe { ::std::mem::transmute(pps_slice_chroma_qp_offsets_present_flag) }; + pps_slice_chroma_qp_offsets_present_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let sample_adaptive_offset_enabled_flag: u32 = + unsafe { ::std::mem::transmute(sample_adaptive_offset_enabled_flag) }; + sample_adaptive_offset_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let deblocking_filter_override_enabled_flag: u32 = + unsafe { ::std::mem::transmute(deblocking_filter_override_enabled_flag) }; + deblocking_filter_override_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let pps_disable_deblocking_filter_flag: u32 = + unsafe { ::std::mem::transmute(pps_disable_deblocking_filter_flag) }; + pps_disable_deblocking_filter_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let slice_segment_header_extension_present_flag: u32 = + unsafe { ::std::mem::transmute(slice_segment_header_extension_present_flag) }; + slice_segment_header_extension_present_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let RapPicFlag: u32 = unsafe { ::std::mem::transmute(RapPicFlag) }; + RapPicFlag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let IdrPicFlag: u32 = unsafe { ::std::mem::transmute(IdrPicFlag) }; + IdrPicFlag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let IntraPicFlag: u32 = unsafe { ::std::mem::transmute(IntraPicFlag) }; + IntraPicFlag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 18u8, { + let ReservedBits: u32 = unsafe { ::std::mem::transmute(ReservedBits) }; + ReservedBits as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferHEVC__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAPictureParameterBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure\n\n This structure conveys picture level parameters and should be sent once\n per frame.\n"] +pub type VAPictureParameterBufferHEVC = _VAPictureParameterBufferHEVC; +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure for Range Extension\n\n This structure conveys picture level HEVC Range Extension parameters\n and should be sent once per frame. This data structure should be sent\n together with VAPictureParameterBufferHEVC in a single buffer of\n \\ref VAPictureParameterBufferHEVCExtension since each frame\n of HEVC range extension contains both picture level parameters and picture\n level range extension parameters. They should be parsed together. The buffer\n type is same as \\ref VAPictureParameterBufferHEVC.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAPictureParameterBufferHEVCRext { + pub range_extension_pic_fields: _VAPictureParameterBufferHEVCRext__bindgen_ty_1, + #[doc = " \\brief HEVC range extension flags\n The following flags bears the same syntax and semantics as\n those defined in HEVC bit stream spec."] + pub diff_cu_chroma_qp_offset_depth: u8, + pub chroma_qp_offset_list_len_minus1: u8, + pub log2_sao_offset_scale_luma: u8, + pub log2_sao_offset_scale_chroma: u8, + pub log2_max_transform_skip_block_size_minus2: u8, + pub cb_qp_offset_list: [i8; 6usize], + pub cr_qp_offset_list: [i8; 6usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + pub bits: _VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAPictureParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn transform_skip_rotation_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_skip_rotation_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_skip_rotation_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_skip_rotation_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_skip_context_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_skip_context_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_skip_context_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_skip_context_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn implicit_rdpcm_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_implicit_rdpcm_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn implicit_rdpcm_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_implicit_rdpcm_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn explicit_rdpcm_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_explicit_rdpcm_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn explicit_rdpcm_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_explicit_rdpcm_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn extended_precision_processing_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_extended_precision_processing_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn extended_precision_processing_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_extended_precision_processing_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_smoothing_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_intra_smoothing_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_smoothing_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_smoothing_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn high_precision_offsets_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_high_precision_offsets_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn high_precision_offsets_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_high_precision_offsets_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn persistent_rice_adaptation_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_persistent_rice_adaptation_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn persistent_rice_adaptation_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_persistent_rice_adaptation_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cabac_bypass_alignment_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_cabac_bypass_alignment_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cabac_bypass_alignment_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cabac_bypass_alignment_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cross_component_prediction_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_cross_component_prediction_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cross_component_prediction_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cross_component_prediction_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn chroma_qp_offset_list_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_chroma_qp_offset_list_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_qp_offset_list_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_qp_offset_list_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 21u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 21u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 21u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 21u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let transform_skip_rotation_enabled_flag: u32 = + unsafe { ::std::mem::transmute(transform_skip_rotation_enabled_flag) }; + transform_skip_rotation_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let transform_skip_context_enabled_flag: u32 = + unsafe { ::std::mem::transmute(transform_skip_context_enabled_flag) }; + transform_skip_context_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let implicit_rdpcm_enabled_flag: u32 = unsafe { ::std::mem::transmute(implicit_rdpcm_enabled_flag) }; + implicit_rdpcm_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let explicit_rdpcm_enabled_flag: u32 = unsafe { ::std::mem::transmute(explicit_rdpcm_enabled_flag) }; + explicit_rdpcm_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let extended_precision_processing_flag: u32 = + unsafe { ::std::mem::transmute(extended_precision_processing_flag) }; + extended_precision_processing_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let intra_smoothing_disabled_flag: u32 = unsafe { ::std::mem::transmute(intra_smoothing_disabled_flag) }; + intra_smoothing_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let high_precision_offsets_enabled_flag: u32 = + unsafe { ::std::mem::transmute(high_precision_offsets_enabled_flag) }; + high_precision_offsets_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let persistent_rice_adaptation_enabled_flag: u32 = + unsafe { ::std::mem::transmute(persistent_rice_adaptation_enabled_flag) }; + persistent_rice_adaptation_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let cabac_bypass_alignment_enabled_flag: u32 = + unsafe { ::std::mem::transmute(cabac_bypass_alignment_enabled_flag) }; + cabac_bypass_alignment_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let cross_component_prediction_enabled_flag: u32 = + unsafe { ::std::mem::transmute(cross_component_prediction_enabled_flag) }; + cross_component_prediction_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let chroma_qp_offset_list_enabled_flag: u32 = + unsafe { ::std::mem::transmute(chroma_qp_offset_list_enabled_flag) }; + chroma_qp_offset_list_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 21u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferHEVCRext__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAPictureParameterBufferHEVCRext { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure for Range Extension\n\n This structure conveys picture level HEVC Range Extension parameters\n and should be sent once per frame. This data structure should be sent\n together with VAPictureParameterBufferHEVC in a single buffer of\n \\ref VAPictureParameterBufferHEVCExtension since each frame\n of HEVC range extension contains both picture level parameters and picture\n level range extension parameters. They should be parsed together. The buffer\n type is same as \\ref VAPictureParameterBufferHEVC.\n"] +pub type VAPictureParameterBufferHEVCRext = _VAPictureParameterBufferHEVCRext; +#[doc = "\\brief HEVC Decoding Picture Parameter Buffer Structure for\nScreen Content extension\n\nThis structure conveys picture level HEVC Scc parameters\nand should be sent once per frame. This data structure should be sent\ntogether with VAPictureParameterBufferHEVC and VAPictureParameterBufferHEVCRext\nin a single buffer of \\ref VAPictureParameterBufferHEVCExtension since each\nframe of HEVC SCC contains picture level parameters, picture level range\nextension parameters and picture level Scc parameters. They should be parsed\ntogether and the buffer type is same as \\ref VAPictureParameterBufferHEVC.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAPictureParameterBufferHEVCScc { + pub screen_content_pic_fields: _VAPictureParameterBufferHEVCScc__bindgen_ty_1, + pub palette_max_size: u8, + pub delta_palette_max_predictor_size: u8, + #[doc = " \\brief Size of initial palette predictor.\n It is derived from pps_num_palette_predictor_initializer or\n sps_num_palette_predictor_initializer_minus1.\n Details in HEVC SCC spec section 9.3.2.3."] + pub predictor_palette_size: u8, + #[doc = " \\brief Palette predictor initializer.\n It is derived from pps_palette_predictor_initializers[][]\n or sps_palette_predictor_initializers[][].\n Details in HEVC SCC spec section 9.3.2.3."] + pub predictor_palette_entries: [[u16; 128usize]; 3usize], + pub pps_act_y_qp_offset_plus5: i8, + pub pps_act_cb_qp_offset_plus5: i8, + pub pps_act_cr_qp_offset_plus3: i8, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + pub bits: _VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAPictureParameterBufferHEVCScc__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn pps_curr_pic_ref_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_curr_pic_ref_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_curr_pic_ref_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_curr_pic_ref_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn palette_mode_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_palette_mode_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn palette_mode_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_palette_mode_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn motion_vector_resolution_control_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_motion_vector_resolution_control_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn motion_vector_resolution_control_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_motion_vector_resolution_control_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_boundary_filtering_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_intra_boundary_filtering_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_boundary_filtering_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_boundary_filtering_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn residual_adaptive_colour_transform_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_residual_adaptive_colour_transform_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn residual_adaptive_colour_transform_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_residual_adaptive_colour_transform_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pps_slice_act_qp_offsets_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_slice_act_qp_offsets_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_slice_act_qp_offsets_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_slice_act_qp_offsets_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 25u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 25u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 25u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 25u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let pps_curr_pic_ref_enabled_flag: u32 = unsafe { ::std::mem::transmute(pps_curr_pic_ref_enabled_flag) }; + pps_curr_pic_ref_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let palette_mode_enabled_flag: u32 = unsafe { ::std::mem::transmute(palette_mode_enabled_flag) }; + palette_mode_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let motion_vector_resolution_control_idc: u32 = + unsafe { ::std::mem::transmute(motion_vector_resolution_control_idc) }; + motion_vector_resolution_control_idc as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let intra_boundary_filtering_disabled_flag: u32 = + unsafe { ::std::mem::transmute(intra_boundary_filtering_disabled_flag) }; + intra_boundary_filtering_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let residual_adaptive_colour_transform_enabled_flag: u32 = + unsafe { ::std::mem::transmute(residual_adaptive_colour_transform_enabled_flag) }; + residual_adaptive_colour_transform_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let pps_slice_act_qp_offsets_present_flag: u32 = + unsafe { ::std::mem::transmute(pps_slice_act_qp_offsets_present_flag) }; + pps_slice_act_qp_offsets_present_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 25u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAPictureParameterBufferHEVCScc__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAPictureParameterBufferHEVCScc { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = "\\brief HEVC Decoding Picture Parameter Buffer Structure for\nScreen Content extension\n\nThis structure conveys picture level HEVC Scc parameters\nand should be sent once per frame. This data structure should be sent\ntogether with VAPictureParameterBufferHEVC and VAPictureParameterBufferHEVCRext\nin a single buffer of \\ref VAPictureParameterBufferHEVCExtension since each\nframe of HEVC SCC contains picture level parameters, picture level range\nextension parameters and picture level Scc parameters. They should be parsed\ntogether and the buffer type is same as \\ref VAPictureParameterBufferHEVC.\n"] +pub type VAPictureParameterBufferHEVCScc = _VAPictureParameterBufferHEVCScc; +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure including Extensions\n\n This structure conveys picture level HEVC parameters including basic version 1\n and range extension and screen content extension.\n The data buffer should be sent once per frame.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAPictureParameterBufferHEVCExtension { + #[doc = " \\brief basic HEVC picture parameters data structure"] + pub base: VAPictureParameterBufferHEVC, + #[doc = " \\brief HEVC range extension picture parameters data structure"] + pub rext: VAPictureParameterBufferHEVCRext, + #[doc = " \\brief HEVC screen content picture parameters data structure"] + pub scc: VAPictureParameterBufferHEVCScc, +} +impl Default for _VAPictureParameterBufferHEVCExtension { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Decoding Picture Parameter Buffer Structure including Extensions\n\n This structure conveys picture level HEVC parameters including basic version 1\n and range extension and screen content extension.\n The data buffer should be sent once per frame.\n"] +pub type VAPictureParameterBufferHEVCExtension = _VAPictureParameterBufferHEVCExtension; +#[doc = " \\brief HEVC Slice Parameter Buffer Structure For Long Format\n\n VASliceParameterBufferHEVC structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice.\n\n For short format, this data structure is not sent by application.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VASliceParameterBufferHEVC { + #[doc = " \\brief Number of bytes in the slice data buffer for this slice\n counting from and including NAL unit header."] + pub slice_data_size: u32, + #[doc = " \\brief The offset to the NAL unit header for this slice"] + pub slice_data_offset: u32, + #[doc = " \\brief Slice data buffer flags. See \\c VA_SLICE_DATA_FLAG_XXX."] + pub slice_data_flag: u32, + #[doc = " \\brief Byte offset from NAL unit header to the begining of slice_data().\n\n This byte offset is relative to and includes the NAL unit header\n and represents the number of bytes parsed in the slice_header()\n after the removal of any emulation prevention bytes in\n there. However, the slice data buffer passed to the hardware is\n the original bitstream, thus including any emulation prevention\n bytes."] + pub slice_data_byte_offset: u32, + #[doc = " HEVC syntax element."] + pub slice_segment_address: u32, + #[doc = " \\brief index into ReferenceFrames[]\n RefPicList[0][] corresponds to RefPicList0[] of HEVC variable.\n RefPicList[1][] corresponds to RefPicList1[] of HEVC variable.\n value range [0..14, 0xFF], where 0xFF indicates invalid entry."] + pub RefPicList: [[u8; 15usize]; 2usize], + pub LongSliceFlags: _VASliceParameterBufferHEVC__bindgen_ty_1, + #[doc = " HEVC syntax element. Collocated Reference Picture Index.\n index to RefPicList[0][] or RefPicList[1][].\n when slice_temporal_mvp_enabled_flag equals 0, it should take value 0xFF.\n value range [0..14, 0xFF]."] + pub collocated_ref_idx: u8, + #[doc = " HEVC syntax element.\n if num_ref_idx_active_override_flag equals 0, host decoder should\n set its value to num_ref_idx_l0_default_active_minus1."] + pub num_ref_idx_l0_active_minus1: u8, + #[doc = " HEVC syntax element.\n if num_ref_idx_active_override_flag equals 0, host decoder should\n set its value to num_ref_idx_l1_default_active_minus1."] + pub num_ref_idx_l1_active_minus1: u8, + #[doc = " HEVC syntax element."] + pub slice_qp_delta: i8, + #[doc = " HEVC syntax element."] + pub slice_cb_qp_offset: i8, + #[doc = " HEVC syntax element."] + pub slice_cr_qp_offset: i8, + #[doc = " HEVC syntax element."] + pub slice_beta_offset_div2: i8, + #[doc = " HEVC syntax element."] + pub slice_tc_offset_div2: i8, + #[doc = " HEVC syntax element."] + pub luma_log2_weight_denom: u8, + #[doc = " HEVC syntax element."] + pub delta_chroma_log2_weight_denom: i8, + #[doc = " HEVC syntax element."] + pub delta_luma_weight_l0: [i8; 15usize], + #[doc = " HEVC syntax element."] + pub luma_offset_l0: [i8; 15usize], + #[doc = " HEVC syntax element."] + pub delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + #[doc = " corresponds to HEVC spec variable of the same name."] + pub ChromaOffsetL0: [[i8; 2usize]; 15usize], + #[doc = " HEVC syntax element."] + pub delta_luma_weight_l1: [i8; 15usize], + #[doc = " HEVC syntax element."] + pub luma_offset_l1: [i8; 15usize], + #[doc = " HEVC syntax element."] + pub delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + #[doc = " corresponds to HEVC spec variable of the same name."] + pub ChromaOffsetL1: [[i8; 2usize]; 15usize], + #[doc = " HEVC syntax element."] + pub five_minus_max_num_merge_cand: u8, + #[doc = " HEVC syntax element."] + pub num_entry_point_offsets: u16, + #[doc = " HEVC syntax element."] + pub entry_offset_to_subset_array: u16, + #[doc = " \\brief Number of emulation prevention bytes in slice header."] + pub slice_data_num_emu_prevn_bytes: u16, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 2usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VASliceParameterBufferHEVC__bindgen_ty_1 { + pub value: u32, + pub fields: _VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VASliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn LastSliceOfPic(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_LastSliceOfPic(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn LastSliceOfPic_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_LastSliceOfPic_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dependent_slice_segment_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_dependent_slice_segment_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dependent_slice_segment_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dependent_slice_segment_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_slice_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn color_plane_id(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 2u8) as u32) } + } + #[inline] + pub fn set_color_plane_id(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn color_plane_id_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_color_plane_id_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_sao_luma_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_sao_luma_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_sao_luma_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_sao_luma_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_sao_chroma_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_sao_chroma_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_sao_chroma_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_sao_chroma_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mvd_l1_zero_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_mvd_l1_zero_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mvd_l1_zero_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mvd_l1_zero_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cabac_init_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_cabac_init_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cabac_init_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cabac_init_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_temporal_mvp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_temporal_mvp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_temporal_mvp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_temporal_mvp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_deblocking_filter_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_deblocking_filter_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_deblocking_filter_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_deblocking_filter_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn collocated_from_l0_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_collocated_from_l0_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn collocated_from_l0_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_collocated_from_l0_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_loop_filter_across_slices_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_loop_filter_across_slices_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_loop_filter_across_slices_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_loop_filter_across_slices_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 18u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 18u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 18u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 18u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + LastSliceOfPic: 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let LastSliceOfPic: u32 = unsafe { ::std::mem::transmute(LastSliceOfPic) }; + LastSliceOfPic as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let dependent_slice_segment_flag: u32 = unsafe { ::std::mem::transmute(dependent_slice_segment_flag) }; + dependent_slice_segment_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let slice_type: u32 = unsafe { ::std::mem::transmute(slice_type) }; + slice_type as u64 + }); + __bindgen_bitfield_unit.set(4usize, 2u8, { + let color_plane_id: u32 = unsafe { ::std::mem::transmute(color_plane_id) }; + color_plane_id as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let slice_sao_luma_flag: u32 = unsafe { ::std::mem::transmute(slice_sao_luma_flag) }; + slice_sao_luma_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let slice_sao_chroma_flag: u32 = unsafe { ::std::mem::transmute(slice_sao_chroma_flag) }; + slice_sao_chroma_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let mvd_l1_zero_flag: u32 = unsafe { ::std::mem::transmute(mvd_l1_zero_flag) }; + mvd_l1_zero_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let cabac_init_flag: u32 = unsafe { ::std::mem::transmute(cabac_init_flag) }; + cabac_init_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let slice_temporal_mvp_enabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_temporal_mvp_enabled_flag) }; + slice_temporal_mvp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let slice_deblocking_filter_disabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_deblocking_filter_disabled_flag) }; + slice_deblocking_filter_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let collocated_from_l0_flag: u32 = unsafe { ::std::mem::transmute(collocated_from_l0_flag) }; + collocated_from_l0_flag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let slice_loop_filter_across_slices_enabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_loop_filter_across_slices_enabled_flag) }; + slice_loop_filter_across_slices_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 18u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VASliceParameterBufferHEVC__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VASliceParameterBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Slice Parameter Buffer Structure For Long Format\n\n VASliceParameterBufferHEVC structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice.\n\n For short format, this data structure is not sent by application.\n"] +pub type VASliceParameterBufferHEVC = _VASliceParameterBufferHEVC; +#[doc = " \\brief HEVC Extented Slice Parameter Buffer Structure For Long Format\n\n This data structure contains extension profiles (range extension and screen content).\n\n VASliceParameterBufferHEVCRext structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice with VASliceParameterBufferHEVC in a single buffer of\n \\ref VASliceParameterBufferHEVCExtension and the buffer type is same as \\ref\n VASliceParameterBufferHEVC.\n\n For short format, this data structure is not sent by application.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VASliceParameterBufferHEVCRext { + pub luma_offset_l0: [i16; 15usize], + pub ChromaOffsetL0: [[i16; 2usize]; 15usize], + pub luma_offset_l1: [i16; 15usize], + pub ChromaOffsetL1: [[i16; 2usize]; 15usize], + pub slice_ext_flags: _VASliceParameterBufferHEVCRext__bindgen_ty_1, + #[doc = " \\brief Screen Content Extension parameters.\n data range [-12..12]"] + pub slice_act_y_qp_offset: i8, + pub slice_act_cb_qp_offset: i8, + pub slice_act_cr_qp_offset: i8, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VASliceParameterBufferHEVCRext__bindgen_ty_1 { + pub bits: _VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VASliceParameterBufferHEVCRext__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn cu_chroma_qp_offset_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_cu_chroma_qp_offset_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cu_chroma_qp_offset_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cu_chroma_qp_offset_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn use_integer_mv_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_use_integer_mv_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn use_integer_mv_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_use_integer_mv_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 30u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 30u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 30u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 30u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + cu_chroma_qp_offset_enabled_flag: u32, + use_integer_mv_flag: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let cu_chroma_qp_offset_enabled_flag: u32 = + unsafe { ::std::mem::transmute(cu_chroma_qp_offset_enabled_flag) }; + cu_chroma_qp_offset_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let use_integer_mv_flag: u32 = unsafe { ::std::mem::transmute(use_integer_mv_flag) }; + use_integer_mv_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 30u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VASliceParameterBufferHEVCRext__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VASliceParameterBufferHEVCRext { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Extented Slice Parameter Buffer Structure For Long Format\n\n This data structure contains extension profiles (range extension and screen content).\n\n VASliceParameterBufferHEVCRext structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice with VASliceParameterBufferHEVC in a single buffer of\n \\ref VASliceParameterBufferHEVCExtension and the buffer type is same as \\ref\n VASliceParameterBufferHEVC.\n\n For short format, this data structure is not sent by application.\n"] +pub type VASliceParameterBufferHEVCRext = _VASliceParameterBufferHEVCRext; +#[doc = " \\brief HEVC Decoding Slice Parameter Buffer Structure For Long Format including Extensions\n\n This data structure contains both baseline HEVC profiles (main, main10)\n and extension profiles (range extension and screen content).\n\n VASliceParameterBufferHEVCExtension structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice. For HEVC range extension and HEVC Scc decoding,\n application should parse both basic slice parameters and extented slice\n parameters into this buffer structure and sent it.\n\n For short format, this data structure is not sent by application.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VASliceParameterBufferHEVCExtension { + #[doc = " \\brief baseline HEVC slice parameters data structure"] + pub base: VASliceParameterBufferHEVC, + #[doc = " \\brief extented HEVC slice parameters data structure"] + pub rext: VASliceParameterBufferHEVCRext, +} +impl Default for _VASliceParameterBufferHEVCExtension { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Decoding Slice Parameter Buffer Structure For Long Format including Extensions\n\n This data structure contains both baseline HEVC profiles (main, main10)\n and extension profiles (range extension and screen content).\n\n VASliceParameterBufferHEVCExtension structure should be accompanied by a\n slice data buffer, which holds the whole raw slice NAL unit bit streams\n including start code prefix and emulation prevention bytes not removed.\n\n This structure conveys parameters related to slice segment header and should\n be sent once per slice. For HEVC range extension and HEVC Scc decoding,\n application should parse both basic slice parameters and extented slice\n parameters into this buffer structure and sent it.\n\n For short format, this data structure is not sent by application.\n"] +pub type VASliceParameterBufferHEVCExtension = _VASliceParameterBufferHEVCExtension; +#[doc = " \\brief HEVC Inverse Quantization Matrix Buffer Structure\n\n This structure is sent once per frame,\n and only when scaling_list_enabled_flag = 1.\n When sps_scaling_list_data_present_flag = 0, app still\n needs to send in this structure with default matrix values.\n\n Matrix entries are in raster scan order which follows HEVC spec."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAIQMatrixBufferHEVC { + #[doc = " \\brief scaling lists,\n corresponds to same HEVC spec syntax element\n ScalingList[ i ][ MatrixID ][ j ].\n\n \\brief 4x4 scaling,\n correspongs i = 0, MatrixID is in the range of 0 to 5,\n inclusive. And j is in the range of 0 to 15, inclusive."] + pub ScalingList4x4: [[u8; 16usize]; 6usize], + #[doc = " \\brief 8x8 scaling,\n correspongs i = 1, MatrixID is in the range of 0 to 5,\n inclusive. And j is in the range of 0 to 63, inclusive."] + pub ScalingList8x8: [[u8; 64usize]; 6usize], + #[doc = " \\brief 16x16 scaling,\n correspongs i = 2, MatrixID is in the range of 0 to 5,\n inclusive. And j is in the range of 0 to 63, inclusive."] + pub ScalingList16x16: [[u8; 64usize]; 6usize], + #[doc = " \\brief 32x32 scaling,\n correspongs i = 3, MatrixID is in the range of 0 to 1,\n inclusive. And j is in the range of 0 to 63, inclusive."] + pub ScalingList32x32: [[u8; 64usize]; 2usize], + #[doc = " \\brief DC values of the 16x16 scaling lists,\n corresponds to HEVC spec syntax\n scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8\n with sizeID = 2 and matrixID in the range of 0 to 5, inclusive."] + pub ScalingListDC16x16: [u8; 6usize], + #[doc = " \\brief DC values of the 32x32 scaling lists,\n corresponds to HEVC spec syntax\n scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8\n with sizeID = 3 and matrixID in the range of 0 to 1, inclusive."] + pub ScalingListDC32x32: [u8; 2usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAIQMatrixBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Inverse Quantization Matrix Buffer Structure\n\n This structure is sent once per frame,\n and only when scaling_list_enabled_flag = 1.\n When sps_scaling_list_data_present_flag = 0, app still\n needs to send in this structure with default matrix values.\n\n Matrix entries are in raster scan order which follows HEVC spec."] +pub type VAIQMatrixBufferHEVC = _VAIQMatrixBufferHEVC; +#[doc = " Attribute value for VAConfigAttribEncHEVCFeatures.\n\n This attribute decribes the supported features of an HEVC/H.265\n encoder configuration.\n\n All of the field values in this attribute are VA_FEATURE_* values,\n indicating support for the corresponding feature."] +#[repr(C)] +#[derive(Copy, Clone)] +pub union VAConfigAttribValEncHEVCFeatures { + pub bits: VAConfigAttribValEncHEVCFeatures__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct VAConfigAttribValEncHEVCFeatures__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl VAConfigAttribValEncHEVCFeatures__bindgen_ty_1 { + #[inline] + pub fn separate_colour_planes(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_separate_colour_planes(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn separate_colour_planes_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_separate_colour_planes_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn scaling_lists(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_scaling_lists(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn scaling_lists_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_scaling_lists_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn amp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 2u8) as u32) } + } + #[inline] + pub fn set_amp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn amp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_amp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn sao(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 2u8) as u32) } + } + #[inline] + pub fn set_sao(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn sao_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sao_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn pcm(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 2u8) as u32) } + } + #[inline] + pub fn set_pcm(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn pcm_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pcm_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn temporal_mvp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 2u8) as u32) } + } + #[inline] + pub fn set_temporal_mvp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn temporal_mvp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_temporal_mvp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn strong_intra_smoothing(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 2u8) as u32) } + } + #[inline] + pub fn set_strong_intra_smoothing(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn strong_intra_smoothing_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_strong_intra_smoothing_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn dependent_slices(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 2u8) as u32) } + } + #[inline] + pub fn set_dependent_slices(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn dependent_slices_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dependent_slices_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn sign_data_hiding(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 2u8) as u32) } + } + #[inline] + pub fn set_sign_data_hiding(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn sign_data_hiding_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sign_data_hiding_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn constrained_intra_pred(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 2u8) as u32) } + } + #[inline] + pub fn set_constrained_intra_pred(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn constrained_intra_pred_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_constrained_intra_pred_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_skip(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 2u8) as u32) } + } + #[inline] + pub fn set_transform_skip(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_skip_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_skip_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn cu_qp_delta(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(22usize, 2u8) as u32) } + } + #[inline] + pub fn set_cu_qp_delta(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(22usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn cu_qp_delta_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 22usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cu_qp_delta_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 22usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_prediction(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 2u8) as u32) } + } + #[inline] + pub fn set_weighted_prediction(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(24usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_prediction_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 24usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_prediction_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn transquant_bypass(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(26usize, 2u8) as u32) } + } + #[inline] + pub fn set_transquant_bypass(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(26usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn transquant_bypass_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 26usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transquant_bypass_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 26usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn deblocking_filter_disable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(28usize, 2u8) as u32) } + } + #[inline] + pub fn set_deblocking_filter_disable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(28usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn deblocking_filter_disable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 28usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_deblocking_filter_disable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 28usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(30usize, 2u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(30usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 30usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 30usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + separate_colour_planes: u32, + scaling_lists: u32, + amp: u32, + sao: u32, + pcm: u32, + temporal_mvp: u32, + strong_intra_smoothing: u32, + dependent_slices: u32, + sign_data_hiding: u32, + constrained_intra_pred: u32, + transform_skip: u32, + cu_qp_delta: u32, + weighted_prediction: u32, + transquant_bypass: u32, + deblocking_filter_disable: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let separate_colour_planes: u32 = unsafe { ::std::mem::transmute(separate_colour_planes) }; + separate_colour_planes as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let scaling_lists: u32 = unsafe { ::std::mem::transmute(scaling_lists) }; + scaling_lists as u64 + }); + __bindgen_bitfield_unit.set(4usize, 2u8, { + let amp: u32 = unsafe { ::std::mem::transmute(amp) }; + amp as u64 + }); + __bindgen_bitfield_unit.set(6usize, 2u8, { + let sao: u32 = unsafe { ::std::mem::transmute(sao) }; + sao as u64 + }); + __bindgen_bitfield_unit.set(8usize, 2u8, { + let pcm: u32 = unsafe { ::std::mem::transmute(pcm) }; + pcm as u64 + }); + __bindgen_bitfield_unit.set(10usize, 2u8, { + let temporal_mvp: u32 = unsafe { ::std::mem::transmute(temporal_mvp) }; + temporal_mvp as u64 + }); + __bindgen_bitfield_unit.set(12usize, 2u8, { + let strong_intra_smoothing: u32 = unsafe { ::std::mem::transmute(strong_intra_smoothing) }; + strong_intra_smoothing as u64 + }); + __bindgen_bitfield_unit.set(14usize, 2u8, { + let dependent_slices: u32 = unsafe { ::std::mem::transmute(dependent_slices) }; + dependent_slices as u64 + }); + __bindgen_bitfield_unit.set(16usize, 2u8, { + let sign_data_hiding: u32 = unsafe { ::std::mem::transmute(sign_data_hiding) }; + sign_data_hiding as u64 + }); + __bindgen_bitfield_unit.set(18usize, 2u8, { + let constrained_intra_pred: u32 = unsafe { ::std::mem::transmute(constrained_intra_pred) }; + constrained_intra_pred as u64 + }); + __bindgen_bitfield_unit.set(20usize, 2u8, { + let transform_skip: u32 = unsafe { ::std::mem::transmute(transform_skip) }; + transform_skip as u64 + }); + __bindgen_bitfield_unit.set(22usize, 2u8, { + let cu_qp_delta: u32 = unsafe { ::std::mem::transmute(cu_qp_delta) }; + cu_qp_delta as u64 + }); + __bindgen_bitfield_unit.set(24usize, 2u8, { + let weighted_prediction: u32 = unsafe { ::std::mem::transmute(weighted_prediction) }; + weighted_prediction as u64 + }); + __bindgen_bitfield_unit.set(26usize, 2u8, { + let transquant_bypass: u32 = unsafe { ::std::mem::transmute(transquant_bypass) }; + transquant_bypass as u64 + }); + __bindgen_bitfield_unit.set(28usize, 2u8, { + let deblocking_filter_disable: u32 = unsafe { ::std::mem::transmute(deblocking_filter_disable) }; + deblocking_filter_disable as u64 + }); + __bindgen_bitfield_unit.set(30usize, 2u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for VAConfigAttribValEncHEVCFeatures { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " Attribute value for VAConfigAttribEncHEVCBlockSizes.\n\n This attribute describes the supported coding tree and transform block\n sizes of an HEVC/H.265 encoder configuration"] +#[repr(C)] +#[derive(Copy, Clone)] +pub union VAConfigAttribValEncHEVCBlockSizes { + pub bits: VAConfigAttribValEncHEVCBlockSizes__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct VAConfigAttribValEncHEVCBlockSizes__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl VAConfigAttribValEncHEVCBlockSizes__bindgen_ty_1 { + #[inline] + pub fn log2_max_coding_tree_block_size_minus3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_max_coding_tree_block_size_minus3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_coding_tree_block_size_minus3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_coding_tree_block_size_minus3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_min_coding_tree_block_size_minus3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_min_coding_tree_block_size_minus3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_min_coding_tree_block_size_minus3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_min_coding_tree_block_size_minus3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_min_luma_coding_block_size_minus3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_min_luma_coding_block_size_minus3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_min_luma_coding_block_size_minus3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_min_luma_coding_block_size_minus3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_luma_transform_block_size_minus2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_max_luma_transform_block_size_minus2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_luma_transform_block_size_minus2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_luma_transform_block_size_minus2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_min_luma_transform_block_size_minus2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_min_luma_transform_block_size_minus2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_min_luma_transform_block_size_minus2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_min_luma_transform_block_size_minus2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn max_max_transform_hierarchy_depth_inter(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 2u8) as u32) } + } + #[inline] + pub fn set_max_max_transform_hierarchy_depth_inter(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn max_max_transform_hierarchy_depth_inter_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_max_max_transform_hierarchy_depth_inter_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn min_max_transform_hierarchy_depth_inter(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 2u8) as u32) } + } + #[inline] + pub fn set_min_max_transform_hierarchy_depth_inter(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn min_max_transform_hierarchy_depth_inter_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_min_max_transform_hierarchy_depth_inter_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn max_max_transform_hierarchy_depth_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 2u8) as u32) } + } + #[inline] + pub fn set_max_max_transform_hierarchy_depth_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn max_max_transform_hierarchy_depth_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_max_max_transform_hierarchy_depth_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn min_max_transform_hierarchy_depth_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 2u8) as u32) } + } + #[inline] + pub fn set_min_max_transform_hierarchy_depth_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn min_max_transform_hierarchy_depth_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_min_max_transform_hierarchy_depth_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_pcm_coding_block_size_minus3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_max_pcm_coding_block_size_minus3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_pcm_coding_block_size_minus3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_pcm_coding_block_size_minus3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_min_pcm_coding_block_size_minus3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 2u8) as u32) } + } + #[inline] + pub fn set_log2_min_pcm_coding_block_size_minus3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_min_pcm_coding_block_size_minus3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_min_pcm_coding_block_size_minus3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(22usize, 10u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(22usize, 10u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 22usize, + 10u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 22usize, + 10u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + log2_max_coding_tree_block_size_minus3: u32, + log2_min_coding_tree_block_size_minus3: u32, + log2_min_luma_coding_block_size_minus3: u32, + log2_max_luma_transform_block_size_minus2: u32, + log2_min_luma_transform_block_size_minus2: u32, + max_max_transform_hierarchy_depth_inter: u32, + min_max_transform_hierarchy_depth_inter: u32, + max_max_transform_hierarchy_depth_intra: u32, + min_max_transform_hierarchy_depth_intra: u32, + log2_max_pcm_coding_block_size_minus3: u32, + log2_min_pcm_coding_block_size_minus3: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let log2_max_coding_tree_block_size_minus3: u32 = + unsafe { ::std::mem::transmute(log2_max_coding_tree_block_size_minus3) }; + log2_max_coding_tree_block_size_minus3 as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let log2_min_coding_tree_block_size_minus3: u32 = + unsafe { ::std::mem::transmute(log2_min_coding_tree_block_size_minus3) }; + log2_min_coding_tree_block_size_minus3 as u64 + }); + __bindgen_bitfield_unit.set(4usize, 2u8, { + let log2_min_luma_coding_block_size_minus3: u32 = + unsafe { ::std::mem::transmute(log2_min_luma_coding_block_size_minus3) }; + log2_min_luma_coding_block_size_minus3 as u64 + }); + __bindgen_bitfield_unit.set(6usize, 2u8, { + let log2_max_luma_transform_block_size_minus2: u32 = + unsafe { ::std::mem::transmute(log2_max_luma_transform_block_size_minus2) }; + log2_max_luma_transform_block_size_minus2 as u64 + }); + __bindgen_bitfield_unit.set(8usize, 2u8, { + let log2_min_luma_transform_block_size_minus2: u32 = + unsafe { ::std::mem::transmute(log2_min_luma_transform_block_size_minus2) }; + log2_min_luma_transform_block_size_minus2 as u64 + }); + __bindgen_bitfield_unit.set(10usize, 2u8, { + let max_max_transform_hierarchy_depth_inter: u32 = + unsafe { ::std::mem::transmute(max_max_transform_hierarchy_depth_inter) }; + max_max_transform_hierarchy_depth_inter as u64 + }); + __bindgen_bitfield_unit.set(12usize, 2u8, { + let min_max_transform_hierarchy_depth_inter: u32 = + unsafe { ::std::mem::transmute(min_max_transform_hierarchy_depth_inter) }; + min_max_transform_hierarchy_depth_inter as u64 + }); + __bindgen_bitfield_unit.set(14usize, 2u8, { + let max_max_transform_hierarchy_depth_intra: u32 = + unsafe { ::std::mem::transmute(max_max_transform_hierarchy_depth_intra) }; + max_max_transform_hierarchy_depth_intra as u64 + }); + __bindgen_bitfield_unit.set(16usize, 2u8, { + let min_max_transform_hierarchy_depth_intra: u32 = + unsafe { ::std::mem::transmute(min_max_transform_hierarchy_depth_intra) }; + min_max_transform_hierarchy_depth_intra as u64 + }); + __bindgen_bitfield_unit.set(18usize, 2u8, { + let log2_max_pcm_coding_block_size_minus3: u32 = + unsafe { ::std::mem::transmute(log2_max_pcm_coding_block_size_minus3) }; + log2_max_pcm_coding_block_size_minus3 as u64 + }); + __bindgen_bitfield_unit.set(20usize, 2u8, { + let log2_min_pcm_coding_block_size_minus3: u32 = + unsafe { ::std::mem::transmute(log2_min_pcm_coding_block_size_minus3) }; + log2_min_pcm_coding_block_size_minus3 as u64 + }); + __bindgen_bitfield_unit.set(22usize, 10u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for VAConfigAttribValEncHEVCBlockSizes { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +pub mod VAEncPackedHeaderTypeHEVC { + #[doc = " \\brief Packed header types specific to HEVC encoding.\n\n Types of packed headers generally used for HEVC encoding. Each\n associated packed header data buffer shall contain the start code\n prefix 0x000001 followed by the complete NAL unit, thus also\n including the \\c nal_unit_type.\n\n Note: the start code prefix can contain an arbitrary number of leading\n zeros. The driver will skip them for emulation prevention bytes insertion,\n if necessary."] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Packed Video Parameter Set (VPS).\n\n The corresponding packed header data buffer shall contain the\n complete video_parameter_set_rbsp() syntax element.\n\n Note: packed \\c nal_unit_type shall be equal to 32."] + pub const VAEncPackedHeaderHEVC_VPS: Type = 1; + #[doc = " \\brief Packed Sequence Parameter Set (SPS).\n\n The corresponding packed header data buffer shall contain the\n complete seq_parameter_set_rbsp() syntax element.\n\n Note: packed \\c nal_unit_type shall be equal to 33."] + pub const VAEncPackedHeaderHEVC_SPS: Type = 1; + #[doc = " \\brief Packed Picture Parameter Set (PPS).\n\n The corresponding packed header data buffer shall contain the\n complete pic_parameter_set_rbsp() syntax element.\n\n Note: packed \\c nal_unit_type shall be equal to 34."] + pub const VAEncPackedHeaderHEVC_PPS: Type = 2; + #[doc = " \\brief Packed slice header.\n\n The corresponding packed header data buffer shall contain the\n \\c slice_header() syntax element only, along with any start\n code prefix and NAL unit type preceeding it. i.e. this means\n that the buffer does not contain any of the \\c slice_data() or\n the \\c rbsp_slice_trailing_bits().\n\n Note: packed \\c nal_unit_type shall be equal to 0 to 9 (non-IRAP\n picture), or 16 to 21 (IRAP picture)."] + pub const VAEncPackedHeaderHEVC_Slice: Type = 3; + #[doc = " \\brief Packed Supplemental Enhancement Information (SEI).\n\n The corresponding packed header data buffer shall contain the\n complete sei_rbsp() syntax element, thus including several\n sei_message() elements if necessary.\n\n Note: packed \\c nal_unit_type shall be equal to 39 or 40.\n\n @deprecated\n This is a deprecated packed header flag, All applications can use\n \\c VA_ENC_PACKED_HEADER_RAW_DATA to pass the corresponding packed\n SEI header data buffer to the driver"] + pub const VAEncPackedHeaderHEVC_SEI: Type = 2147483649; +} +#[doc = " \\brief Sequence parameter for HEVC encoding in main & main 10\n profiles.\n\n This structure holds information for \\c seq_parameter_set_data() as\n defined by the HEVC specification.\n\n If packed sequence headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSequence ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c seq_scaling_matrix_present_flag is set to \\c 1, then a\n #VAQMatrixBufferHEVC buffer shall also be provided within the same\n \\c vaRenderPicture() call as this sequence parameter buffer."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncSequenceParameterBufferHEVC { + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n value range [1..2]."] + pub general_profile_idc: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n general_level_idc shall be set equal to a value of 30 times the level\n numbers allowed [1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2]"] + pub general_level_idc: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n Only value 0 is allowed for level value below 4, exclusive."] + pub general_tier_flag: u8, + #[doc = " \\brief Period between I frames."] + pub intra_period: u32, + #[doc = " \\brief Period between IDR frames."] + pub intra_idr_period: u32, + #[doc = " \\brief Period between I/P frames."] + pub ip_period: u32, + #[doc = " \\brief Initial bitrate set for this sequence in CBR or VBR modes.\n\n This field represents the initial bitrate value for this\n sequence if CBR or VBR mode is used, i.e. if the encoder\n pipeline was created with a #VAConfigAttribRateControl\n attribute set to either \\ref VA_RC_CBR or \\ref VA_RC_VBR.\n\n The bitrate can be modified later on through\n #VAEncMiscParameterRateControl buffers."] + pub bits_per_second: u32, + #[doc = " \\brief Picture width in pixel samples.\n Its value must be multiple of min CU size."] + pub pic_width_in_luma_samples: u16, + #[doc = " \\brief Picture height in pixel samples.\n Its value must be multiple of min CU size."] + pub pic_height_in_luma_samples: u16, + pub seq_fields: _VAEncSequenceParameterBufferHEVC__bindgen_ty_1, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n value range [0..3]"] + pub log2_min_luma_coding_block_size_minus3: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub log2_diff_max_min_luma_coding_block_size: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n value range [0..3]"] + pub log2_min_transform_block_size_minus2: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub log2_diff_max_min_transform_block_size: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n value range [2]"] + pub max_transform_hierarchy_depth_inter: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element.\n value range [2]"] + pub max_transform_hierarchy_depth_intra: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub pcm_sample_bit_depth_luma_minus1: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub pcm_sample_bit_depth_chroma_minus1: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub log2_min_pcm_luma_coding_block_size_minus3: u32, + #[doc = " \\brief Derived from the HEVC bitstream syntax element.\n log2_min_pcm_luma_coding_block_size_minus3 +\n log2_diff_max_min_pcm_luma_coding_block_size"] + pub log2_max_pcm_luma_coding_block_size_minus3: u32, + #[doc = " @name VUI parameters (optional) */\n/**@{*/\n/** \\brief Same as the HEVC bitstream syntax element."] + pub vui_parameters_present_flag: u8, + pub vui_fields: _VAEncSequenceParameterBufferHEVC__bindgen_ty_2, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub aspect_ratio_idc: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub sar_width: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub sar_height: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub vui_num_units_in_tick: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub vui_time_scale: u32, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub min_spatial_segmentation_idc: u16, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub max_bytes_per_pic_denom: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub max_bits_per_min_cu_denom: u8, + pub scc_fields: _VAEncSequenceParameterBufferHEVC__bindgen_ty_3, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 7usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSequenceParameterBufferHEVC__bindgen_ty_1 { + pub bits: _VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncSequenceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn chroma_format_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_chroma_format_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_format_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_format_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn separate_colour_plane_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_separate_colour_plane_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn separate_colour_plane_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_separate_colour_plane_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn bit_depth_luma_minus8(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 3u8) as u32) } + } + #[inline] + pub fn set_bit_depth_luma_minus8(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn bit_depth_luma_minus8_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_bit_depth_luma_minus8_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn bit_depth_chroma_minus8(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 3u8) as u32) } + } + #[inline] + pub fn set_bit_depth_chroma_minus8(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn bit_depth_chroma_minus8_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_bit_depth_chroma_minus8_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn scaling_list_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_scaling_list_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn scaling_list_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_scaling_list_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn strong_intra_smoothing_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_strong_intra_smoothing_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn strong_intra_smoothing_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_strong_intra_smoothing_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn amp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_amp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn amp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_amp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sample_adaptive_offset_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_sample_adaptive_offset_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sample_adaptive_offset_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sample_adaptive_offset_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pcm_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_pcm_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pcm_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pcm_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pcm_loop_filter_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_pcm_loop_filter_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pcm_loop_filter_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pcm_loop_filter_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sps_temporal_mvp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_sps_temporal_mvp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sps_temporal_mvp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sps_temporal_mvp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn low_delay_seq(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_low_delay_seq(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn low_delay_seq_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_low_delay_seq_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn hierachical_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } + } + #[inline] + pub fn set_hierachical_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(17usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn hierachical_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 17usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_hierachical_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved_bits(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 14u8) as u32) } + } + #[inline] + pub fn set_reserved_bits(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 14u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_bits_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 14u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_bits_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 14u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved_bits: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let chroma_format_idc: u32 = unsafe { ::std::mem::transmute(chroma_format_idc) }; + chroma_format_idc as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let separate_colour_plane_flag: u32 = unsafe { ::std::mem::transmute(separate_colour_plane_flag) }; + separate_colour_plane_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 3u8, { + let bit_depth_luma_minus8: u32 = unsafe { ::std::mem::transmute(bit_depth_luma_minus8) }; + bit_depth_luma_minus8 as u64 + }); + __bindgen_bitfield_unit.set(6usize, 3u8, { + let bit_depth_chroma_minus8: u32 = unsafe { ::std::mem::transmute(bit_depth_chroma_minus8) }; + bit_depth_chroma_minus8 as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let scaling_list_enabled_flag: u32 = unsafe { ::std::mem::transmute(scaling_list_enabled_flag) }; + scaling_list_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let strong_intra_smoothing_enabled_flag: u32 = + unsafe { ::std::mem::transmute(strong_intra_smoothing_enabled_flag) }; + strong_intra_smoothing_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let amp_enabled_flag: u32 = unsafe { ::std::mem::transmute(amp_enabled_flag) }; + amp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let sample_adaptive_offset_enabled_flag: u32 = + unsafe { ::std::mem::transmute(sample_adaptive_offset_enabled_flag) }; + sample_adaptive_offset_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let pcm_enabled_flag: u32 = unsafe { ::std::mem::transmute(pcm_enabled_flag) }; + pcm_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let pcm_loop_filter_disabled_flag: u32 = unsafe { ::std::mem::transmute(pcm_loop_filter_disabled_flag) }; + pcm_loop_filter_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let sps_temporal_mvp_enabled_flag: u32 = unsafe { ::std::mem::transmute(sps_temporal_mvp_enabled_flag) }; + sps_temporal_mvp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let low_delay_seq: u32 = unsafe { ::std::mem::transmute(low_delay_seq) }; + low_delay_seq as u64 + }); + __bindgen_bitfield_unit.set(17usize, 1u8, { + let hierachical_flag: u32 = unsafe { ::std::mem::transmute(hierachical_flag) }; + hierachical_flag as u64 + }); + __bindgen_bitfield_unit.set(18usize, 14u8, { + let reserved_bits: u32 = unsafe { ::std::mem::transmute(reserved_bits) }; + reserved_bits as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSequenceParameterBufferHEVC__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSequenceParameterBufferHEVC__bindgen_ty_2 { + pub bits: _VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, + pub __bindgen_padding_0: u8, +} +impl _VAEncSequenceParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + #[inline] + pub fn aspect_ratio_info_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_aspect_ratio_info_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn aspect_ratio_info_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_aspect_ratio_info_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn neutral_chroma_indication_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_neutral_chroma_indication_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn neutral_chroma_indication_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_neutral_chroma_indication_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn field_seq_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_field_seq_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn field_seq_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_field_seq_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn vui_timing_info_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_vui_timing_info_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn vui_timing_info_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_vui_timing_info_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn bitstream_restriction_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_bitstream_restriction_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn bitstream_restriction_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_bitstream_restriction_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn tiles_fixed_structure_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_tiles_fixed_structure_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn tiles_fixed_structure_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_tiles_fixed_structure_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn motion_vectors_over_pic_boundaries_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_motion_vectors_over_pic_boundaries_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn motion_vectors_over_pic_boundaries_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_motion_vectors_over_pic_boundaries_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn restricted_ref_pic_lists_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_restricted_ref_pic_lists_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn restricted_ref_pic_lists_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_restricted_ref_pic_lists_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_mv_length_horizontal(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 5u8) as u32) } + } + #[inline] + pub fn set_log2_max_mv_length_horizontal(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_mv_length_horizontal_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_mv_length_horizontal_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_mv_length_vertical(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 5u8) as u32) } + } + #[inline] + pub fn set_log2_max_mv_length_vertical(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_mv_length_vertical_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_mv_length_vertical_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + ) -> __BindgenBitfieldUnit<[u8; 3usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 3usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let aspect_ratio_info_present_flag: u32 = unsafe { ::std::mem::transmute(aspect_ratio_info_present_flag) }; + aspect_ratio_info_present_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let neutral_chroma_indication_flag: u32 = unsafe { ::std::mem::transmute(neutral_chroma_indication_flag) }; + neutral_chroma_indication_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let field_seq_flag: u32 = unsafe { ::std::mem::transmute(field_seq_flag) }; + field_seq_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let vui_timing_info_present_flag: u32 = unsafe { ::std::mem::transmute(vui_timing_info_present_flag) }; + vui_timing_info_present_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let bitstream_restriction_flag: u32 = unsafe { ::std::mem::transmute(bitstream_restriction_flag) }; + bitstream_restriction_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let tiles_fixed_structure_flag: u32 = unsafe { ::std::mem::transmute(tiles_fixed_structure_flag) }; + tiles_fixed_structure_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let motion_vectors_over_pic_boundaries_flag: u32 = + unsafe { ::std::mem::transmute(motion_vectors_over_pic_boundaries_flag) }; + motion_vectors_over_pic_boundaries_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let restricted_ref_pic_lists_flag: u32 = unsafe { ::std::mem::transmute(restricted_ref_pic_lists_flag) }; + restricted_ref_pic_lists_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 5u8, { + let log2_max_mv_length_horizontal: u32 = unsafe { ::std::mem::transmute(log2_max_mv_length_horizontal) }; + log2_max_mv_length_horizontal as u64 + }); + __bindgen_bitfield_unit.set(13usize, 5u8, { + let log2_max_mv_length_vertical: u32 = unsafe { ::std::mem::transmute(log2_max_mv_length_vertical) }; + log2_max_mv_length_vertical as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSequenceParameterBufferHEVC__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief SCC flags to enable/disable features, including IBC and palette mode at present."] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSequenceParameterBufferHEVC__bindgen_ty_3 { + pub bits: _VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncSequenceParameterBufferHEVC__bindgen_ty_3__bindgen_ty_1 { + #[inline] + pub fn palette_mode_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_palette_mode_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn palette_mode_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_palette_mode_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 31u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 31u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 31u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 31u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(palette_mode_enabled_flag: u32, reserved: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let palette_mode_enabled_flag: u32 = unsafe { ::std::mem::transmute(palette_mode_enabled_flag) }; + palette_mode_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 31u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSequenceParameterBufferHEVC__bindgen_ty_3 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncSequenceParameterBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Sequence parameter for HEVC encoding in main & main 10\n profiles.\n\n This structure holds information for \\c seq_parameter_set_data() as\n defined by the HEVC specification.\n\n If packed sequence headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSequence ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c seq_scaling_matrix_present_flag is set to \\c 1, then a\n #VAQMatrixBufferHEVC buffer shall also be provided within the same\n \\c vaRenderPicture() call as this sequence parameter buffer."] +pub type VAEncSequenceParameterBufferHEVC = _VAEncSequenceParameterBufferHEVC; +#[doc = " HEVC data structures\n/\n/**\n \\brief Picture parameter for HEVC encoding in main & main 10\n profiles.\n\n This structure holds information for \\c pic_parameter_set_rbsp() as\n defined by the HEVC specification.\n\n If packed picture headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderPicture ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c pic_scaling_matrix_present_flag is set to \\c 1, then a\n #VAQMatrixBufferHEVC buffer shall also be provided within the same\n \\c vaRenderPicture() call as this picture parameter buffer."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncPictureParameterBufferHEVC { + #[doc = " \\brief Information about the picture to be encoded.\n\n See #VAPictureHEVC for further description of each field.\n Note that decoded_curr_pic.picture_id represents the reconstructed\n (decoded) picture. User provides a scratch VA surface ID here.\n Long term reference and RPS related fields should be set to 0\n and ignored."] + pub decoded_curr_pic: VAPictureHEVC, + #[doc = " \\brief Decoded Picture Buffer (DPB).\n\n This array represents the list of reconstructed (decoded)\n frames used as reference. It is important to keep track of\n reconstructed frames so that they can be used later on as\n reference for P or B-frames encoding."] + pub reference_frames: [VAPictureHEVC; 15usize], + #[doc = " \\brief Output encoded bitstream.\n\n \\ref coded_buf has type #VAEncCodedBufferType. It should be\n large enough to hold the compressed NAL slice and possibly VPS, SPS\n and PPS NAL units, and other NAL units such as SEI."] + pub coded_buf: VABufferID, + #[doc = " \\brief collocated reference picture buffer index of ReferenceFrames[].\n Please note it is different from HEVC syntac element collocated_ref_idx.\n When the HEVC syntax element slice_temporal_mvp_enable_flag takes value 0,\n collocated_ref_pic_index should take value 0xFF. .\n Range: [0..14, 0xFF]"] + pub collocated_ref_pic_index: u8, + #[doc = " \\brief OR'd flags describing whether the picture is the last one or not.\n\n This fields holds 0 if the picture to be encoded is not the last\n one in the stream or sequence. Otherwise, it is a combination of\n \\ref HEVC_LAST_PICTURE_EOSEQ or \\ref HEVC_LAST_PICTURE_EOSTREAM."] + pub last_picture: u8, + #[doc = " \\brief \\c init_qp_minus26 + 26."] + pub pic_init_qp: u8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub diff_cu_qp_delta_depth: u8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub pps_cb_qp_offset: i8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub pps_cr_qp_offset: i8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub num_tile_columns_minus1: u8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub num_tile_rows_minus1: u8, + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub column_width_minus1: [u8; 19usize], + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub row_height_minus1: [u8; 21usize], + #[doc = " \\brief Corresponds to HEVC syntax element of the same name."] + pub log2_parallel_merge_level_minus2: u8, + #[doc = " \\brief Application may set the CTU bit size limit based on\n spec requirement (A.3.2), or other value for special purpose.\n If the value is set 0, no bit size limit is checked."] + pub ctu_max_bitsize_allowed: u8, + #[doc = " \\brief Maximum reference index for reference picture list 0.\n value range: [0..14]."] + pub num_ref_idx_l0_default_active_minus1: u8, + #[doc = " \\brief Maximum reference index for reference picture list 1.\n value range: [0..14]."] + pub num_ref_idx_l1_default_active_minus1: u8, + #[doc = " \\brief PPS header\n Used by GPU to generate new slice headers in slice size control.\n value range: [0..63]."] + pub slice_pic_parameter_set_id: u8, + #[doc = " \\brief NAL unit type\n Used by GPU to generate new slice headers in slice size control.\n value range: [0..63]."] + pub nal_unit_type: u8, + pub pic_fields: _VAEncPictureParameterBufferHEVC__bindgen_ty_1, + #[doc = " \\brief When hierachical_level_plus1 > 0, hierachical_level_plus1-1 indicates\nthe current frame's level.when it > 0. B1, B2 setting in CodingType can be treated as B,\nhirachical level is determined by this variable.When hierachical_level_plus1 == 0,\nhierarchical level information still comes from coding_type."] + pub hierarchical_level_plus1: u8, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_byte_reserved: u8, + pub scc_fields: _VAEncPictureParameterBufferHEVC__bindgen_ty_2, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 15usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncPictureParameterBufferHEVC__bindgen_ty_1 { + pub bits: _VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncPictureParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn idr_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_idr_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn idr_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_idr_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn coding_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 3u8) as u32) } + } + #[inline] + pub fn set_coding_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn coding_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_coding_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn reference_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_reference_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reference_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reference_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dependent_slice_segments_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_dependent_slice_segments_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dependent_slice_segments_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dependent_slice_segments_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sign_data_hiding_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_sign_data_hiding_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn sign_data_hiding_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sign_data_hiding_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn constrained_intra_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_constrained_intra_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn constrained_intra_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_constrained_intra_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_skip_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_skip_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_skip_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_skip_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cu_qp_delta_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_cu_qp_delta_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cu_qp_delta_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cu_qp_delta_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_bipred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_bipred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_bipred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_bipred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transquant_bypass_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_transquant_bypass_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transquant_bypass_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transquant_bypass_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn tiles_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_tiles_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn tiles_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_tiles_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn entropy_coding_sync_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_entropy_coding_sync_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn entropy_coding_sync_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_entropy_coding_sync_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn loop_filter_across_tiles_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_loop_filter_across_tiles_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn loop_filter_across_tiles_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_loop_filter_across_tiles_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pps_loop_filter_across_slices_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_pps_loop_filter_across_slices_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_loop_filter_across_slices_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pps_loop_filter_across_slices_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn scaling_list_data_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } + } + #[inline] + pub fn set_scaling_list_data_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(17usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn scaling_list_data_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 17usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_scaling_list_data_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn screen_content_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u32) } + } + #[inline] + pub fn set_screen_content_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn screen_content_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_screen_content_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_gpu_weighted_prediction(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(19usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_gpu_weighted_prediction(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(19usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_gpu_weighted_prediction_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 19usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_gpu_weighted_prediction_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 19usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn no_output_of_prior_pics_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 1u8) as u32) } + } + #[inline] + pub fn set_no_output_of_prior_pics_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn no_output_of_prior_pics_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_no_output_of_prior_pics_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(21usize, 11u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(21usize, 11u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 21usize, + 11u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 21usize, + 11u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let idr_pic_flag: u32 = unsafe { ::std::mem::transmute(idr_pic_flag) }; + idr_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 3u8, { + let coding_type: u32 = unsafe { ::std::mem::transmute(coding_type) }; + coding_type as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let reference_pic_flag: u32 = unsafe { ::std::mem::transmute(reference_pic_flag) }; + reference_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let dependent_slice_segments_enabled_flag: u32 = + unsafe { ::std::mem::transmute(dependent_slice_segments_enabled_flag) }; + dependent_slice_segments_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let sign_data_hiding_enabled_flag: u32 = unsafe { ::std::mem::transmute(sign_data_hiding_enabled_flag) }; + sign_data_hiding_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let constrained_intra_pred_flag: u32 = unsafe { ::std::mem::transmute(constrained_intra_pred_flag) }; + constrained_intra_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let transform_skip_enabled_flag: u32 = unsafe { ::std::mem::transmute(transform_skip_enabled_flag) }; + transform_skip_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let cu_qp_delta_enabled_flag: u32 = unsafe { ::std::mem::transmute(cu_qp_delta_enabled_flag) }; + cu_qp_delta_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let weighted_pred_flag: u32 = unsafe { ::std::mem::transmute(weighted_pred_flag) }; + weighted_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let weighted_bipred_flag: u32 = unsafe { ::std::mem::transmute(weighted_bipred_flag) }; + weighted_bipred_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let transquant_bypass_enabled_flag: u32 = unsafe { ::std::mem::transmute(transquant_bypass_enabled_flag) }; + transquant_bypass_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let tiles_enabled_flag: u32 = unsafe { ::std::mem::transmute(tiles_enabled_flag) }; + tiles_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let entropy_coding_sync_enabled_flag: u32 = + unsafe { ::std::mem::transmute(entropy_coding_sync_enabled_flag) }; + entropy_coding_sync_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let loop_filter_across_tiles_enabled_flag: u32 = + unsafe { ::std::mem::transmute(loop_filter_across_tiles_enabled_flag) }; + loop_filter_across_tiles_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let pps_loop_filter_across_slices_enabled_flag: u32 = + unsafe { ::std::mem::transmute(pps_loop_filter_across_slices_enabled_flag) }; + pps_loop_filter_across_slices_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(17usize, 1u8, { + let scaling_list_data_present_flag: u32 = unsafe { ::std::mem::transmute(scaling_list_data_present_flag) }; + scaling_list_data_present_flag as u64 + }); + __bindgen_bitfield_unit.set(18usize, 1u8, { + let screen_content_flag: u32 = unsafe { ::std::mem::transmute(screen_content_flag) }; + screen_content_flag as u64 + }); + __bindgen_bitfield_unit.set(19usize, 1u8, { + let enable_gpu_weighted_prediction: u32 = unsafe { ::std::mem::transmute(enable_gpu_weighted_prediction) }; + enable_gpu_weighted_prediction as u64 + }); + __bindgen_bitfield_unit.set(20usize, 1u8, { + let no_output_of_prior_pics_flag: u32 = unsafe { ::std::mem::transmute(no_output_of_prior_pics_flag) }; + no_output_of_prior_pics_flag as u64 + }); + __bindgen_bitfield_unit.set(21usize, 11u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncPictureParameterBufferHEVC__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief SCC flags to enable/disable feature, only IBC at present."] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncPictureParameterBufferHEVC__bindgen_ty_2 { + pub bits: _VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1, + pub value: u16, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, +} +impl _VAEncPictureParameterBufferHEVC__bindgen_ty_2__bindgen_ty_1 { + #[inline] + pub fn pps_curr_pic_ref_enabled_flag(&self) -> u16 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u16) } + } + #[inline] + pub fn set_pps_curr_pic_ref_enabled_flag(&mut self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pps_curr_pic_ref_enabled_flag_raw(this: *const Self) -> u16 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u16) + } + } + #[inline] + pub unsafe fn set_pps_curr_pic_ref_enabled_flag_raw(this: *mut Self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u16 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 15u8) as u16) } + } + #[inline] + pub fn set_reserved(&mut self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 15u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u16 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 15u8, + ) as u16) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u16) { + unsafe { + let val: u16 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 15u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(pps_curr_pic_ref_enabled_flag: u16, reserved: u16) -> __BindgenBitfieldUnit<[u8; 2usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let pps_curr_pic_ref_enabled_flag: u16 = unsafe { ::std::mem::transmute(pps_curr_pic_ref_enabled_flag) }; + pps_curr_pic_ref_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 15u8, { + let reserved: u16 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncPictureParameterBufferHEVC__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncPictureParameterBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " HEVC data structures\n/\n/**\n \\brief Picture parameter for HEVC encoding in main & main 10\n profiles.\n\n This structure holds information for \\c pic_parameter_set_rbsp() as\n defined by the HEVC specification.\n\n If packed picture headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderPicture ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c pic_scaling_matrix_present_flag is set to \\c 1, then a\n #VAQMatrixBufferHEVC buffer shall also be provided within the same\n \\c vaRenderPicture() call as this picture parameter buffer."] +pub type VAEncPictureParameterBufferHEVC = _VAEncPictureParameterBufferHEVC; +#[doc = " \\brief Slice parameter for HEVC encoding in main & main 10 profiles.\n\n This structure holds information for \\c\n slice_segment_layer_rbsp() as defined by the HEVC\n specification.\n\n If packed slice headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSlice ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncSliceParameterBufferHEVC { + #[doc = " \\brief Starting CTU address for this slice."] + pub slice_segment_address: u32, + #[doc = " \\brief Number of CTUs in this slice."] + pub num_ctu_in_slice: u32, + #[doc = " \\brief Slice type.\n Corresponds to HEVC syntax element of the same name."] + pub slice_type: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_pic_parameter_set_id: u8, + #[doc = " \\brief Maximum reference index for reference picture list 0.\n Range: 0 to 14, inclusive."] + pub num_ref_idx_l0_active_minus1: u8, + #[doc = " \\brief Maximum reference index for reference picture list 1.\n Range: 0 to 14, inclusive."] + pub num_ref_idx_l1_active_minus1: u8, + #[doc = " \\brief Reference picture list 0 (for P slices)."] + pub ref_pic_list0: [VAPictureHEVC; 15usize], + #[doc = " \\brief Reference picture list 1 (for B slices)."] + pub ref_pic_list1: [VAPictureHEVC; 15usize], + #[doc = " @name pred_weight_table() */\n/**@{*/\n/** \\brief Same as the HEVC bitstream syntax element."] + pub luma_log2_weight_denom: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub delta_chroma_log2_weight_denom: i8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub delta_luma_weight_l0: [i8; 15usize], + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub luma_offset_l0: [i8; 15usize], + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub delta_chroma_weight_l0: [[i8; 2usize]; 15usize], + #[doc = " \\brief Same as the HEVC spec variable ChromaOffsetL0[]."] + pub chroma_offset_l0: [[i8; 2usize]; 15usize], + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub delta_luma_weight_l1: [i8; 15usize], + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub luma_offset_l1: [i8; 15usize], + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub delta_chroma_weight_l1: [[i8; 2usize]; 15usize], + #[doc = " \\brief Same as the HEVC spec variable ChromaOffsetL1[]."] + pub chroma_offset_l1: [[i8; 2usize]; 15usize], + #[doc = " \\brief Corresponds to HEVC spec variable MaxNumMergeCand.\n Range: [1..5]."] + pub max_num_merge_cand: u8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_qp_delta: i8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_cb_qp_offset: i8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_cr_qp_offset: i8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_beta_offset_div2: i8, + #[doc = " \\brief Same as the HEVC bitstream syntax element."] + pub slice_tc_offset_div2: i8, + pub slice_fields: _VAEncSliceParameterBufferHEVC__bindgen_ty_1, + #[doc = " \\brief bit offset of syntax element pred_weight_table() in slice segment header.\n It aligns with the starting position of the current packed slice header.\n It is used when encoder prefers to override the weighted prediction parameters passed in\n from application.\n Please refer to enable_gpu_weighted_prediction in VAEncPictureParameterBufferHEVC."] + pub pred_weight_table_bit_offset: u32, + #[doc = " \\brief bit length of syntax element pred_weight_table() in slice segment header.\n It is used when encoder prefers to override the weighted prediction parameters passed in\n from application.\n Please refer to enable_gpu_weighted_prediction in VAEncPictureParameterBufferHEVC."] + pub pred_weight_table_bit_length: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 6usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSliceParameterBufferHEVC__bindgen_ty_1 { + pub bits: _VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, + pub __bindgen_padding_0: u16, +} +impl _VAEncSliceParameterBufferHEVC__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn last_slice_of_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_last_slice_of_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn last_slice_of_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_last_slice_of_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dependent_slice_segment_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_dependent_slice_segment_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dependent_slice_segment_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dependent_slice_segment_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn colour_plane_id(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 2u8) as u32) } + } + #[inline] + pub fn set_colour_plane_id(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn colour_plane_id_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_colour_plane_id_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_temporal_mvp_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_temporal_mvp_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_temporal_mvp_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_temporal_mvp_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_sao_luma_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_sao_luma_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_sao_luma_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_sao_luma_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_sao_chroma_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_sao_chroma_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_sao_chroma_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_sao_chroma_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn num_ref_idx_active_override_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_num_ref_idx_active_override_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn num_ref_idx_active_override_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_ref_idx_active_override_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mvd_l1_zero_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_mvd_l1_zero_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mvd_l1_zero_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mvd_l1_zero_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cabac_init_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_cabac_init_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cabac_init_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cabac_init_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_deblocking_filter_disabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 2u8) as u32) } + } + #[inline] + pub fn set_slice_deblocking_filter_disabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_deblocking_filter_disabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_deblocking_filter_disabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn slice_loop_filter_across_slices_enabled_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_slice_loop_filter_across_slices_enabled_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn slice_loop_filter_across_slices_enabled_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_slice_loop_filter_across_slices_enabled_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn collocated_from_l0_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_collocated_from_l0_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn collocated_from_l0_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_collocated_from_l0_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + ) -> __BindgenBitfieldUnit<[u8; 2usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let last_slice_of_pic_flag: u32 = unsafe { ::std::mem::transmute(last_slice_of_pic_flag) }; + last_slice_of_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let dependent_slice_segment_flag: u32 = unsafe { ::std::mem::transmute(dependent_slice_segment_flag) }; + dependent_slice_segment_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 2u8, { + let colour_plane_id: u32 = unsafe { ::std::mem::transmute(colour_plane_id) }; + colour_plane_id as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let slice_temporal_mvp_enabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_temporal_mvp_enabled_flag) }; + slice_temporal_mvp_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let slice_sao_luma_flag: u32 = unsafe { ::std::mem::transmute(slice_sao_luma_flag) }; + slice_sao_luma_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let slice_sao_chroma_flag: u32 = unsafe { ::std::mem::transmute(slice_sao_chroma_flag) }; + slice_sao_chroma_flag as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let num_ref_idx_active_override_flag: u32 = + unsafe { ::std::mem::transmute(num_ref_idx_active_override_flag) }; + num_ref_idx_active_override_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let mvd_l1_zero_flag: u32 = unsafe { ::std::mem::transmute(mvd_l1_zero_flag) }; + mvd_l1_zero_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let cabac_init_flag: u32 = unsafe { ::std::mem::transmute(cabac_init_flag) }; + cabac_init_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 2u8, { + let slice_deblocking_filter_disabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_deblocking_filter_disabled_flag) }; + slice_deblocking_filter_disabled_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let slice_loop_filter_across_slices_enabled_flag: u32 = + unsafe { ::std::mem::transmute(slice_loop_filter_across_slices_enabled_flag) }; + slice_loop_filter_across_slices_enabled_flag as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let collocated_from_l0_flag: u32 = unsafe { ::std::mem::transmute(collocated_from_l0_flag) }; + collocated_from_l0_flag as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSliceParameterBufferHEVC__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncSliceParameterBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Slice parameter for HEVC encoding in main & main 10 profiles.\n\n This structure holds information for \\c\n slice_segment_layer_rbsp() as defined by the HEVC\n specification.\n\n If packed slice headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSlice ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n"] +pub type VAEncSliceParameterBufferHEVC = _VAEncSliceParameterBufferHEVC; +#[doc = " \\brief HEVC Quantization Matrix Buffer Structure\n\n This structure is sent once per frame,\n and only when scaling_list_enabled_flag = 1 and scaling_list_data_present_flag = 1.\n Only when scaling_list_data_present_flag = 1, app still\n needs to send in this structure. When scaling_list_enabled_flag = 1 and\n scaling_list_data_present_flag = 0, driver is responsible to generate\n the default scaling list values.\n\n Matrix entries are in raster scan order which follows HEVC spec."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAQMatrixBufferHEVC { + #[doc = " \\brief scaling lists,\n corresponds to same HEVC spec syntax element\n ScalingList[ i ][ MatrixID ][ j ].\n\n \\brief 4x4 scaling,"] + pub scaling_lists_4x4: [[[u8; 16usize]; 2usize]; 3usize], + #[doc = " \\brief 8x8 scaling,"] + pub scaling_lists_8x8: [[[u8; 64usize]; 2usize]; 3usize], + #[doc = " \\brief 16x16 scaling,\n correspongs i = 2, MatrixID is in the range of 0 to 5,\n inclusive. And j is in the range of 0 to 63, inclusive."] + pub scaling_lists_16x16: [[[u8; 64usize]; 2usize]; 3usize], + #[doc = " \\brief 32x32 scaling,\n correspongs i = 3, MatrixID is in the range of 0 to 1,\n inclusive. And j is in the range of 0 to 63, inclusive."] + pub scaling_lists_32x32: [[u8; 64usize]; 2usize], + #[doc = " \\brief DC values of the 16x16 scaling lists,\n corresponds to HEVC spec syntax\n scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8\n with sizeID = 2 and matrixID in the range of 0 to 5, inclusive."] + pub scaling_list_dc_16x16: [[u8; 2usize]; 3usize], + #[doc = " \\brief DC values of the 32x32 scaling lists,\n corresponds to HEVC spec syntax\n scaling_list_dc_coef_minus8[ sizeID - 2 ][ matrixID ] + 8\n with sizeID = 3 and matrixID in the range of 0 to 1, inclusive."] + pub scaling_list_dc_32x32: [u8; 2usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAQMatrixBufferHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief HEVC Quantization Matrix Buffer Structure\n\n This structure is sent once per frame,\n and only when scaling_list_enabled_flag = 1 and scaling_list_data_present_flag = 1.\n Only when scaling_list_data_present_flag = 1, app still\n needs to send in this structure. When scaling_list_enabled_flag = 1 and\n scaling_list_data_present_flag = 0, driver is responsible to generate\n the default scaling list values.\n\n Matrix entries are in raster scan order which follows HEVC spec."] +pub type VAQMatrixBufferHEVC = _VAQMatrixBufferHEVC; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAPictureStats { + pub picture_id: VASurfaceID, + pub flags: u32, +} +pub type VAPictureStats = _VAPictureStats; +#[doc = " \\brief Motion Vector and Statistics frame level controls.\n common part VAStatsStatisticsParameterBufferType for a MB or CTB"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAStatsStatisticsParameter { + #[doc = " \\brief Source surface ID."] + pub input: VAPictureStats, + #[doc = " \\brief Past reference surface ID pointer."] + pub past_references: *mut VAPictureStats, + #[doc = " \\brief Past reference surface number"] + pub num_past_references: u32, + #[doc = " \\brief Statistics output for past reference surface.\n Only enabling statistics output for past reference picture when *past_ref_stat_buf is a valid\n VABufferID, it is needed in case app wants statistics data of both reference and current pictures\n in very special use cases for better performance.\n The output layout is defined by VAStatsStatisticsBufferType(for progressive and top field of\n interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case), only\n pixel_average_16x16/pixel_average_8x8 and variance_16x16/variance_8x8 data are valid."] + pub past_ref_stat_buf: *mut VABufferID, + #[doc = " \\brief Future reference surface ID pointer."] + pub future_references: *mut VAPictureStats, + #[doc = " \\brief Future reference surface number"] + pub num_future_references: u32, + #[doc = " \\brief Statistics output for future reference surface.\n Only enabling statistics output for future reference picture when *past_ref_stat_buf is a valid\n VABufferID, it is needed in case app wants statistics data of both reference and current pictures\n in very special use cases for better performance.\n The output layout is defined by VAStatsStatisticsBufferType(for progressive and top field of\n interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case), only\n pixel_average_16x16/pixel_average_8x8 and variance_16x16/variance_8x8 data are valid."] + pub future_ref_stat_buf: *mut VABufferID, + #[doc = " \\brief ID of the output buffer.\n The number of outputs is determined by below DisableMVOutput and DisableStatisticsOutput.\n The output layout is defined by VAStatsMVBufferType, VAStatsStatisticsBufferType(for progressive and\n top field of interlaced case) and VAStatsStatisticsBottomFieldBufferType(only for interlaced case)."] + pub outputs: *mut VABufferID, + #[doc = " \\brief MV predictor. It is valid only when mv_predictor_ctrl is not 0.\n Each block has a pair of MVs, one for past and one for future reference\n as defined by VAMotionVector. The block is in raster scan order.\n Buffer size shall not be less than the number of blocks multiplied by sizeof(VAMotionVector)."] + pub mv_predictor: VABufferID, + #[doc = " \\brief QP input buffer. It is valid only when mb_qp is set to 1.\n The data in this buffer correspond to the input source.\n One QP per MB or CTB block in raster scan order, each QP is a signed char (8-bit) value."] + pub qp: VABufferID, +} +impl Default for _VAStatsStatisticsParameter { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Motion Vector and Statistics frame level controls.\n common part VAStatsStatisticsParameterBufferType for a MB or CTB"] +pub type VAStatsStatisticsParameter = _VAStatsStatisticsParameter; +#[doc = " \\brief FEI frame level control buffer for HEVC"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterFEIFrameControlHEVC { + pub function: u32, + #[doc = " \\brief CTB control input buffer. It is valid only when per_ctb_input\n is set to 1. The data in this buffer correspond to the input source. CTB is in raster scan order,\n each CTB control data structure is defined by VAEncFEICTBControlHEVC.\n Buffer size shall not be less than the number of CTBs multiplied by\n sizeof(VAEncFEICTBControlHEVC)."] + pub ctb_ctrl: VABufferID, + #[doc = " \\brief CTB cmd per CTB data output of ENC\n it is reserved for CTB level information\n it should include CU split information and other CTB datas .\n Each CTB block has one CTB cmd data."] + pub ctb_cmd: VABufferID, + #[doc = " \\brief CU record data output of ENC\n it is reserved for CU level information\n it should include CU detail data. include mode,MV, reference etc.\n Each CTB block has one CU record data."] + pub cu_record: VABufferID, + #[doc = " \\brief distortion output of ENC or ENC_PAK.\n Each CTB has one distortion data with VAEncFEIDistortionHevc\n Buffer size shall not be less than the number of CTBs multiplied by\n sizeof(VAEncFEIDistortionHevc)."] + pub distortion: VABufferID, + #[doc = " \\brief Qp input buffer. It is valid only when per_block_qp is set to 1.\n The data in this buffer correspond to the input source.\n One Qp per block block is in raster scan order, each Qp is a signed char (8-bit) value."] + pub qp: VABufferID, + #[doc = " \\brief MV predictor. It is valid only when mv_predictor_input is set to non-zero.\n Each CTB block has one or more pair of motion vectors and the corresponding\n reference indexes as defined by VAEncFEIMVPredictorHEVC. 32x32 block is in raster scan order.\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAEncFEIMVPredictorHEVC)."] + pub mv_predictor: VABufferID, + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 20usize]>, + #[doc = " \\brief max frame size control with multi passes QP setting"] + pub max_frame_size: u32, + #[doc = " \\brief number of passes, every pass has different QP"] + pub num_passes: u32, + #[doc = " \\brief delta QP list for every pass"] + pub delta_qp: *mut u8, + pub reserved4: [u32; 2usize], +} +impl Default for _VAEncMiscParameterFEIFrameControlHEVC { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl _VAEncMiscParameterFEIFrameControlHEVC { + #[inline] + pub fn num_mv_predictors_l0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_num_mv_predictors_l0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn num_mv_predictors_l0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_mv_predictors_l0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn num_mv_predictors_l1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_num_mv_predictors_l1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn num_mv_predictors_l1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_mv_predictors_l1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn search_path(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 8u8) as u32) } + } + #[inline] + pub fn set_search_path(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn search_path_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_path_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn len_sp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 8u8) as u32) } + } + #[inline] + pub fn set_len_sp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(40usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn len_sp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 40usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_len_sp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn multi_pred_l0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 4u8) as u32) } + } + #[inline] + pub fn set_multi_pred_l0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn multi_pred_l0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_multi_pred_l0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn multi_pred_l1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(68usize, 4u8) as u32) } + } + #[inline] + pub fn set_multi_pred_l1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(68usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn multi_pred_l1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 68usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_multi_pred_l1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 68usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_pel_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(72usize, 2u8) as u32) } + } + #[inline] + pub fn set_sub_pel_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(72usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_pel_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 72usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_pel_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 72usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn adaptive_search(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(74usize, 1u8) as u32) } + } + #[inline] + pub fn set_adaptive_search(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(74usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn adaptive_search_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 74usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_adaptive_search_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 74usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mv_predictor_input(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(75usize, 3u8) as u32) } + } + #[inline] + pub fn set_mv_predictor_input(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(75usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn mv_predictor_input_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 75usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mv_predictor_input_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 75usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn per_block_qp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(78usize, 1u8) as u32) } + } + #[inline] + pub fn set_per_block_qp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(78usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn per_block_qp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 78usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_per_block_qp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 78usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn per_ctb_input(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(79usize, 1u8) as u32) } + } + #[inline] + pub fn set_per_ctb_input(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(79usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn per_ctb_input_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 79usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_per_ctb_input_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 79usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn colocated_ctb_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 1u8) as u32) } + } + #[inline] + pub fn set_colocated_ctb_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn colocated_ctb_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_colocated_ctb_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_lcu_split(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(81usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_lcu_split(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(81usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_lcu_split_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 81usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_lcu_split_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 81usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_cu64_check(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(82usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_cu64_check(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(82usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_cu64_check_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 82usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_cu64_check_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 82usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_cu64_amp_check(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(83usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_cu64_amp_check(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(83usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_cu64_amp_check_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 83usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_cu64_amp_check_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 83usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn cu64_skip_check_only(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(84usize, 1u8) as u32) } + } + #[inline] + pub fn set_cu64_skip_check_only(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(84usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn cu64_skip_check_only_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 84usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cu64_skip_check_only_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 84usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(85usize, 11u8) as u32) } + } + #[inline] + pub fn set_reserved1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(85usize, 11u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 85usize, + 11u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 85usize, + 11u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_width(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_width(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(96usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_width_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 96usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_width_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_height(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(104usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_height(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(104usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_height_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 104usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_height_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 104usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn search_window(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(112usize, 8u8) as u32) } + } + #[inline] + pub fn set_search_window(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(112usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn search_window_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 112usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_window_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 112usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn max_num_ime_search_center(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(120usize, 3u8) as u32) } + } + #[inline] + pub fn set_max_num_ime_search_center(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(120usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn max_num_ime_search_center_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 120usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_max_num_ime_search_center_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 120usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn fast_intra_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(123usize, 1u8) as u32) } + } + #[inline] + pub fn set_fast_intra_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(123usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn fast_intra_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 123usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_fast_intra_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 123usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(124usize, 4u8) as u32) } + } + #[inline] + pub fn set_reserved2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(124usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 124usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 124usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn num_concurrent_enc_frame_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(128usize, 8u8) as u32) } + } + #[inline] + pub fn set_num_concurrent_enc_frame_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(128usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn num_concurrent_enc_frame_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 128usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_concurrent_enc_frame_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 128usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(136usize, 24u8) as u32) } + } + #[inline] + pub fn set_reserved3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(136usize, 24u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 20usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 136usize, + 24u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 20usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 136usize, + 24u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + num_mv_predictors_l0: u32, + num_mv_predictors_l1: u32, + search_path: u32, + len_sp: u32, + reserved0: u32, + multi_pred_l0: u32, + multi_pred_l1: u32, + sub_pel_mode: u32, + adaptive_search: u32, + mv_predictor_input: u32, + per_block_qp: u32, + per_ctb_input: u32, + colocated_ctb_distortion: u32, + force_lcu_split: u32, + enable_cu64_check: u32, + enable_cu64_amp_check: u32, + cu64_skip_check_only: u32, + reserved1: u32, + ref_width: u32, + ref_height: u32, + search_window: u32, + max_num_ime_search_center: u32, + fast_intra_mode: u32, + reserved2: u32, + num_concurrent_enc_frame_partition: u32, + reserved3: u32, + ) -> __BindgenBitfieldUnit<[u8; 20usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 20usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let num_mv_predictors_l0: u32 = unsafe { ::std::mem::transmute(num_mv_predictors_l0) }; + num_mv_predictors_l0 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let num_mv_predictors_l1: u32 = unsafe { ::std::mem::transmute(num_mv_predictors_l1) }; + num_mv_predictors_l1 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 8u8, { + let search_path: u32 = unsafe { ::std::mem::transmute(search_path) }; + search_path as u64 + }); + __bindgen_bitfield_unit.set(40usize, 8u8, { + let len_sp: u32 = unsafe { ::std::mem::transmute(len_sp) }; + len_sp as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 4u8, { + let multi_pred_l0: u32 = unsafe { ::std::mem::transmute(multi_pred_l0) }; + multi_pred_l0 as u64 + }); + __bindgen_bitfield_unit.set(68usize, 4u8, { + let multi_pred_l1: u32 = unsafe { ::std::mem::transmute(multi_pred_l1) }; + multi_pred_l1 as u64 + }); + __bindgen_bitfield_unit.set(72usize, 2u8, { + let sub_pel_mode: u32 = unsafe { ::std::mem::transmute(sub_pel_mode) }; + sub_pel_mode as u64 + }); + __bindgen_bitfield_unit.set(74usize, 1u8, { + let adaptive_search: u32 = unsafe { ::std::mem::transmute(adaptive_search) }; + adaptive_search as u64 + }); + __bindgen_bitfield_unit.set(75usize, 3u8, { + let mv_predictor_input: u32 = unsafe { ::std::mem::transmute(mv_predictor_input) }; + mv_predictor_input as u64 + }); + __bindgen_bitfield_unit.set(78usize, 1u8, { + let per_block_qp: u32 = unsafe { ::std::mem::transmute(per_block_qp) }; + per_block_qp as u64 + }); + __bindgen_bitfield_unit.set(79usize, 1u8, { + let per_ctb_input: u32 = unsafe { ::std::mem::transmute(per_ctb_input) }; + per_ctb_input as u64 + }); + __bindgen_bitfield_unit.set(80usize, 1u8, { + let colocated_ctb_distortion: u32 = unsafe { ::std::mem::transmute(colocated_ctb_distortion) }; + colocated_ctb_distortion as u64 + }); + __bindgen_bitfield_unit.set(81usize, 1u8, { + let force_lcu_split: u32 = unsafe { ::std::mem::transmute(force_lcu_split) }; + force_lcu_split as u64 + }); + __bindgen_bitfield_unit.set(82usize, 1u8, { + let enable_cu64_check: u32 = unsafe { ::std::mem::transmute(enable_cu64_check) }; + enable_cu64_check as u64 + }); + __bindgen_bitfield_unit.set(83usize, 1u8, { + let enable_cu64_amp_check: u32 = unsafe { ::std::mem::transmute(enable_cu64_amp_check) }; + enable_cu64_amp_check as u64 + }); + __bindgen_bitfield_unit.set(84usize, 1u8, { + let cu64_skip_check_only: u32 = unsafe { ::std::mem::transmute(cu64_skip_check_only) }; + cu64_skip_check_only as u64 + }); + __bindgen_bitfield_unit.set(85usize, 11u8, { + let reserved1: u32 = unsafe { ::std::mem::transmute(reserved1) }; + reserved1 as u64 + }); + __bindgen_bitfield_unit.set(96usize, 8u8, { + let ref_width: u32 = unsafe { ::std::mem::transmute(ref_width) }; + ref_width as u64 + }); + __bindgen_bitfield_unit.set(104usize, 8u8, { + let ref_height: u32 = unsafe { ::std::mem::transmute(ref_height) }; + ref_height as u64 + }); + __bindgen_bitfield_unit.set(112usize, 8u8, { + let search_window: u32 = unsafe { ::std::mem::transmute(search_window) }; + search_window as u64 + }); + __bindgen_bitfield_unit.set(120usize, 3u8, { + let max_num_ime_search_center: u32 = unsafe { ::std::mem::transmute(max_num_ime_search_center) }; + max_num_ime_search_center as u64 + }); + __bindgen_bitfield_unit.set(123usize, 1u8, { + let fast_intra_mode: u32 = unsafe { ::std::mem::transmute(fast_intra_mode) }; + fast_intra_mode as u64 + }); + __bindgen_bitfield_unit.set(124usize, 4u8, { + let reserved2: u32 = unsafe { ::std::mem::transmute(reserved2) }; + reserved2 as u64 + }); + __bindgen_bitfield_unit.set(128usize, 8u8, { + let num_concurrent_enc_frame_partition: u32 = + unsafe { ::std::mem::transmute(num_concurrent_enc_frame_partition) }; + num_concurrent_enc_frame_partition as u64 + }); + __bindgen_bitfield_unit.set(136usize, 24u8, { + let reserved3: u32 = unsafe { ::std::mem::transmute(reserved3) }; + reserved3 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief FEI frame level control buffer for HEVC"] +pub type VAEncMiscParameterFEIFrameControlHEVC = _VAEncMiscParameterFEIFrameControlHEVC; +#[doc = " \\brief Application can use this definition as reference to allocate the buffer\n based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query.\n this buffer allocation is always based on 16x16 block even block size is indicated as 32x32 or 64x64, and buffer\n layout is always in 32x32 block raster scan order even block size is 16x16 or 64x64. If 32x32 block size is set,\n only the data in the first 16x16 block (block 0) is used for 32x32 block. If 64x64 block size is set\n MV layout is still in 32x32 raster scan order, the same as 32x32 and the first 16x16\n block within each 32x32 block needs to have intended MV data (four 32x32 blocks will have the same MV data in the\n correspondent first 16x16 block). Data structure for each 16x16 block is defined as below (same as AVC except\n BlockSize/Reserved bits)."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMVPredictorHEVC { + pub ref_idx: [_VAEncFEIMVPredictorHEVC__bindgen_ty_1; 4usize], + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, + pub mv: [VAMotionVector; 4usize], +} +#[doc = " \\brief Feference index corresponding to the entry of RefPicList0 & RefPicList1 in slice header (final reference\n list). Note that RefPicList0 & RefPicList1 needs to be the same for all slices.\n Ref0xIndex – RefPicList0; Ref1xIndex – RefPicList1; x – 0 ~ MaxNumPredictor"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMVPredictorHEVC__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, +} +impl _VAEncFEIMVPredictorHEVC__bindgen_ty_1 { + #[inline] + pub fn ref_idx_l0(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 4u8) as u8) } + } + #[inline] + pub fn set_ref_idx_l0(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 4u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u8) } + } + #[inline] + pub fn set_ref_idx_l1(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 4u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(ref_idx_l0: u8, ref_idx_l1: u8) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 4u8, { + let ref_idx_l0: u8 = unsafe { ::std::mem::transmute(ref_idx_l0) }; + ref_idx_l0 as u64 + }); + __bindgen_bitfield_unit.set(4usize, 4u8, { + let ref_idx_l1: u8 = unsafe { ::std::mem::transmute(ref_idx_l1) }; + ref_idx_l1 as u64 + }); + __bindgen_bitfield_unit + } +} +impl _VAEncFEIMVPredictorHEVC { + #[inline] + pub fn block_size(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_block_size(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn block_size_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_block_size_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 30u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 30u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 30u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 30u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(block_size: u32, reserved: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let block_size: u32 = unsafe { ::std::mem::transmute(block_size) }; + block_size as u64 + }); + __bindgen_bitfield_unit.set(2usize, 30u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief Application can use this definition as reference to allocate the buffer\n based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query.\n this buffer allocation is always based on 16x16 block even block size is indicated as 32x32 or 64x64, and buffer\n layout is always in 32x32 block raster scan order even block size is 16x16 or 64x64. If 32x32 block size is set,\n only the data in the first 16x16 block (block 0) is used for 32x32 block. If 64x64 block size is set\n MV layout is still in 32x32 raster scan order, the same as 32x32 and the first 16x16\n block within each 32x32 block needs to have intended MV data (four 32x32 blocks will have the same MV data in the\n correspondent first 16x16 block). Data structure for each 16x16 block is defined as below (same as AVC except\n BlockSize/Reserved bits)."] +pub type VAEncFEIMVPredictorHEVC = _VAEncFEIMVPredictorHEVC; +#[doc = " \\brief FEI CTB level control data structure"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEICTBControlHEVC { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, + pub reserved1: u32, + pub reserved2: u32, + pub reserved3: u32, +} +impl _VAEncFEICTBControlHEVC { + #[inline] + pub fn force_to_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_to_inter(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_inter(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_inter_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_inter_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_to_skip(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_skip(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_skip_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_skip_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_to_zero_coeff(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_zero_coeff(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_zero_coeff_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_zero_coeff_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 28u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 28u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 28u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 28u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + force_to_intra: u32, + force_to_inter: u32, + force_to_skip: u32, + force_to_zero_coeff: u32, + reserved0: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let force_to_intra: u32 = unsafe { ::std::mem::transmute(force_to_intra) }; + force_to_intra as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let force_to_inter: u32 = unsafe { ::std::mem::transmute(force_to_inter) }; + force_to_inter as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let force_to_skip: u32 = unsafe { ::std::mem::transmute(force_to_skip) }; + force_to_skip as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let force_to_zero_coeff: u32 = unsafe { ::std::mem::transmute(force_to_zero_coeff) }; + force_to_zero_coeff as u64 + }); + __bindgen_bitfield_unit.set(4usize, 28u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief FEI CTB level control data structure"] +pub type VAEncFEICTBControlHEVC = _VAEncFEICTBControlHEVC; +pub mod VAEncPackedHeaderTypeH264 { + #[doc = " \\brief Packed header types specific to H.264 encoding.\n\n Types of packed headers generally used for H.264 encoding. Each\n associated packed header data buffer shall contain the start code\n prefix 0x000001 followed by the complete NAL unit, thus also\n including the \\c nal_unit_type.\n\n Note: the start code prefix can contain an arbitrary number of leading\n zeros. The driver will skip them for emulation prevention bytes insertion,\n if necessary."] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Packed Sequence Parameter Set (SPS).\n\n The corresponding packed header data buffer shall contain the\n complete seq_parameter_set_rbsp() syntax element.\n\n Note: packed \\c nal_unit_type shall be equal to 7."] + pub const VAEncPackedHeaderH264_SPS: Type = 1; + #[doc = " \\brief Packed Picture Parameter Set (PPS).\n\n The corresponding packed header data buffer shall contain the\n complete pic_parameter_set_rbsp() syntax element.\n\n Note: packed \\c nal_unit_type shall be equal to 8."] + pub const VAEncPackedHeaderH264_PPS: Type = 2; + #[doc = " \\brief Packed slice header.\n\n The corresponding packed header data buffer shall contain the\n \\c slice_header() syntax element only, along with any start\n code prefix and NAL unit type preceeding it. i.e. this means\n that the buffer does not contain any of the \\c slice_data() or\n the \\c rbsp_slice_trailing_bits().\n\n Note: packed \\c nal_unit_type shall be equal to 1 (non-IDR\n picture), or 5 (IDR picture)."] + pub const VAEncPackedHeaderH264_Slice: Type = 3; + #[doc = " \\brief Packed Supplemental Enhancement Information (SEI).\n\n The corresponding packed header data buffer shall contain the\n complete sei_rbsp() syntax element, thus including several\n sei_message() elements if necessary.\n\n Note: packed \\c nal_unit_type shall be equal to 6.\n\n @deprecated\n This is a deprecated packed header flag, All applications can use\n \\c VA_ENC_PACKED_HEADER_RAW_DATA to pass the corresponding packed\n SEI header data buffer to the driver"] + pub const VAEncPackedHeaderH264_SEI: Type = 2147483649; +} +#[doc = " \\brief Sequence parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds information for \\c seq_parameter_set_data() as\n defined by the H.264 specification.\n\n If packed sequence headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSequence ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c seq_scaling_matrix_present_flag is set to \\c 1, then a\n #VAIQMatrixBufferH264 buffer shall also be provided within the same\n \\c vaRenderPicture() call as this sequence parameter buffer."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncSequenceParameterBufferH264 { + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub seq_parameter_set_id: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub level_idc: u8, + #[doc = " \\brief Period between I frames."] + pub intra_period: u32, + #[doc = " \\brief Period between IDR frames."] + pub intra_idr_period: u32, + #[doc = " \\brief Period between I/P frames."] + pub ip_period: u32, + #[doc = " \\brief Initial bitrate set for this sequence in CBR or VBR modes.\n\n This field represents the initial bitrate value for this\n sequence if CBR or VBR mode is used, i.e. if the encoder\n pipeline was created with a #VAConfigAttribRateControl\n attribute set to either \\ref VA_RC_CBR or \\ref VA_RC_VBR.\n\n The bitrate can be modified later on through\n #VAEncMiscParameterRateControl buffers."] + pub bits_per_second: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub max_num_ref_frames: u32, + #[doc = " \\brief Picture width in macroblocks."] + pub picture_width_in_mbs: u16, + #[doc = " \\brief Picture height in macroblocks."] + pub picture_height_in_mbs: u16, + pub seq_fields: _VAEncSequenceParameterBufferH264__bindgen_ty_1, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub bit_depth_luma_minus8: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub bit_depth_chroma_minus8: u8, + #[doc = " if pic_order_cnt_type == 1 */\n/**@{*/\n/** \\brief Same as the H.264 bitstream syntax element."] + pub num_ref_frames_in_pic_order_cnt_cycle: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub offset_for_non_ref_pic: i32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub offset_for_top_to_bottom_field: i32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub offset_for_ref_frame: [i32; 256usize], + #[doc = " @name Cropping (optional) */\n/**@{*/\n/** \\brief Same as the H.264 bitstream syntax element."] + pub frame_cropping_flag: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub frame_crop_left_offset: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub frame_crop_right_offset: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub frame_crop_top_offset: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub frame_crop_bottom_offset: u32, + #[doc = " @name VUI parameters (optional) */\n/**@{*/\n/** \\brief Same as the H.264 bitstream syntax element."] + pub vui_parameters_present_flag: u8, + pub vui_fields: _VAEncSequenceParameterBufferH264__bindgen_ty_2, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub aspect_ratio_idc: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub sar_width: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub sar_height: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub num_units_in_tick: u32, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub time_scale: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSequenceParameterBufferH264__bindgen_ty_1 { + pub bits: _VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, + pub __bindgen_padding_0: u8, +} +impl _VAEncSequenceParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn chroma_format_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_chroma_format_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_format_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_format_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn frame_mbs_only_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_frame_mbs_only_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn frame_mbs_only_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_frame_mbs_only_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_adaptive_frame_field_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_adaptive_frame_field_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_adaptive_frame_field_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_adaptive_frame_field_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn seq_scaling_matrix_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_seq_scaling_matrix_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn seq_scaling_matrix_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_seq_scaling_matrix_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn direct_8x8_inference_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_direct_8x8_inference_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn direct_8x8_inference_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_direct_8x8_inference_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_frame_num_minus4(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 4u8) as u32) } + } + #[inline] + pub fn set_log2_max_frame_num_minus4(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_frame_num_minus4_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_frame_num_minus4_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn pic_order_cnt_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 2u8) as u32) } + } + #[inline] + pub fn set_pic_order_cnt_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn pic_order_cnt_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pic_order_cnt_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_pic_order_cnt_lsb_minus4(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 4u8) as u32) } + } + #[inline] + pub fn set_log2_max_pic_order_cnt_lsb_minus4(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_pic_order_cnt_lsb_minus4_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_pic_order_cnt_lsb_minus4_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn delta_pic_order_always_zero_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_delta_pic_order_always_zero_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn delta_pic_order_always_zero_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 3usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_delta_pic_order_always_zero_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 3usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + ) -> __BindgenBitfieldUnit<[u8; 3usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 3usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let chroma_format_idc: u32 = unsafe { ::std::mem::transmute(chroma_format_idc) }; + chroma_format_idc as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let frame_mbs_only_flag: u32 = unsafe { ::std::mem::transmute(frame_mbs_only_flag) }; + frame_mbs_only_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let mb_adaptive_frame_field_flag: u32 = unsafe { ::std::mem::transmute(mb_adaptive_frame_field_flag) }; + mb_adaptive_frame_field_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let seq_scaling_matrix_present_flag: u32 = + unsafe { ::std::mem::transmute(seq_scaling_matrix_present_flag) }; + seq_scaling_matrix_present_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let direct_8x8_inference_flag: u32 = unsafe { ::std::mem::transmute(direct_8x8_inference_flag) }; + direct_8x8_inference_flag as u64 + }); + __bindgen_bitfield_unit.set(6usize, 4u8, { + let log2_max_frame_num_minus4: u32 = unsafe { ::std::mem::transmute(log2_max_frame_num_minus4) }; + log2_max_frame_num_minus4 as u64 + }); + __bindgen_bitfield_unit.set(10usize, 2u8, { + let pic_order_cnt_type: u32 = unsafe { ::std::mem::transmute(pic_order_cnt_type) }; + pic_order_cnt_type as u64 + }); + __bindgen_bitfield_unit.set(12usize, 4u8, { + let log2_max_pic_order_cnt_lsb_minus4: u32 = + unsafe { ::std::mem::transmute(log2_max_pic_order_cnt_lsb_minus4) }; + log2_max_pic_order_cnt_lsb_minus4 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let delta_pic_order_always_zero_flag: u32 = + unsafe { ::std::mem::transmute(delta_pic_order_always_zero_flag) }; + delta_pic_order_always_zero_flag as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSequenceParameterBufferH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSequenceParameterBufferH264__bindgen_ty_2 { + pub bits: _VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncSequenceParameterBufferH264__bindgen_ty_2__bindgen_ty_1 { + #[inline] + pub fn aspect_ratio_info_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_aspect_ratio_info_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn aspect_ratio_info_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_aspect_ratio_info_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn timing_info_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_timing_info_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn timing_info_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_timing_info_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn bitstream_restriction_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_bitstream_restriction_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn bitstream_restriction_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_bitstream_restriction_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_mv_length_horizontal(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 5u8) as u32) } + } + #[inline] + pub fn set_log2_max_mv_length_horizontal(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_mv_length_horizontal_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_mv_length_horizontal_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn log2_max_mv_length_vertical(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 5u8) as u32) } + } + #[inline] + pub fn set_log2_max_mv_length_vertical(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn log2_max_mv_length_vertical_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_log2_max_mv_length_vertical_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn fixed_frame_rate_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_fixed_frame_rate_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn fixed_frame_rate_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_fixed_frame_rate_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn low_delay_hrd_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_low_delay_hrd_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn low_delay_hrd_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_low_delay_hrd_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn motion_vectors_over_pic_boundaries_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_motion_vectors_over_pic_boundaries_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn motion_vectors_over_pic_boundaries_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_motion_vectors_over_pic_boundaries_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let aspect_ratio_info_present_flag: u32 = unsafe { ::std::mem::transmute(aspect_ratio_info_present_flag) }; + aspect_ratio_info_present_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let timing_info_present_flag: u32 = unsafe { ::std::mem::transmute(timing_info_present_flag) }; + timing_info_present_flag as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let bitstream_restriction_flag: u32 = unsafe { ::std::mem::transmute(bitstream_restriction_flag) }; + bitstream_restriction_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 5u8, { + let log2_max_mv_length_horizontal: u32 = unsafe { ::std::mem::transmute(log2_max_mv_length_horizontal) }; + log2_max_mv_length_horizontal as u64 + }); + __bindgen_bitfield_unit.set(8usize, 5u8, { + let log2_max_mv_length_vertical: u32 = unsafe { ::std::mem::transmute(log2_max_mv_length_vertical) }; + log2_max_mv_length_vertical as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let fixed_frame_rate_flag: u32 = unsafe { ::std::mem::transmute(fixed_frame_rate_flag) }; + fixed_frame_rate_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let low_delay_hrd_flag: u32 = unsafe { ::std::mem::transmute(low_delay_hrd_flag) }; + low_delay_hrd_flag as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let motion_vectors_over_pic_boundaries_flag: u32 = + unsafe { ::std::mem::transmute(motion_vectors_over_pic_boundaries_flag) }; + motion_vectors_over_pic_boundaries_flag as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSequenceParameterBufferH264__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncSequenceParameterBufferH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Sequence parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds information for \\c seq_parameter_set_data() as\n defined by the H.264 specification.\n\n If packed sequence headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SEQUENCE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSequence ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c seq_scaling_matrix_present_flag is set to \\c 1, then a\n #VAIQMatrixBufferH264 buffer shall also be provided within the same\n \\c vaRenderPicture() call as this sequence parameter buffer."] +pub type VAEncSequenceParameterBufferH264 = _VAEncSequenceParameterBufferH264; +#[doc = " \\brief Picture parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds information for \\c pic_parameter_set_rbsp() as\n defined by the H.264 specification.\n\n If packed picture headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderPicture ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c pic_scaling_matrix_present_flag is set to \\c 1, then a\n #VAIQMatrixBufferH264 buffer shall also be provided within the same\n \\c vaRenderPicture() call as this picture parameter buffer."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncPictureParameterBufferH264 { + #[doc = " \\brief Information about the picture to be encoded.\n\n See #VAPictureH264 for further description of each field.\n Note that CurrPic.picture_id represents the reconstructed\n (decoded) picture. User provides a scratch VA surface ID here."] + pub CurrPic: VAPictureH264, + #[doc = " \\brief Decoded Picture Buffer (DPB).\n\n This array represents the list of reconstructed (decoded)\n frames used as reference. It is important to keep track of\n reconstructed frames so that they can be used later on as\n reference for P or B-frames encoding."] + pub ReferenceFrames: [VAPictureH264; 16usize], + #[doc = " \\brief Output encoded bitstream.\n\n \\ref coded_buf has type #VAEncCodedBufferType. It should be\n large enough to hold the compressed NAL slice and possibly SPS\n and PPS NAL units."] + pub coded_buf: VABufferID, + #[doc = " \\brief The picture parameter set referred to in the slice header."] + pub pic_parameter_set_id: u8, + #[doc = " \\brief The active sequence parameter set. Range: 0 to 31, inclusive."] + pub seq_parameter_set_id: u8, + #[doc = " \\brief OR'd flags describing whether the picture is the last one or not.\n\n This fields holds 0 if the picture to be encoded is not the last\n one in the stream or sequence. Otherwise, it is a combination of\n \\ref H264_LAST_PICTURE_EOSEQ or \\ref H264_LAST_PICTURE_EOSTREAM."] + pub last_picture: u8, + #[doc = " \\brief The picture identifier.\n Range: 0 to \\f$2^{log2\\_max\\_frame\\_num\\_minus4 + 4} - 1\\f$, inclusive."] + pub frame_num: u16, + #[doc = " \\brief \\c pic_init_qp_minus26 + 26."] + pub pic_init_qp: u8, + #[doc = " \\brief Maximum reference index for reference picture list 0.\n Range: 0 to 31, inclusive."] + pub num_ref_idx_l0_active_minus1: u8, + #[doc = " \\brief Maximum reference index for reference picture list 1.\n Range: 0 to 31, inclusive."] + pub num_ref_idx_l1_active_minus1: u8, + #[doc = " \\brief Range: -12 to 12, inclusive."] + pub chroma_qp_index_offset: i8, + #[doc = " \\brief Range: -12 to 12, inclusive."] + pub second_chroma_qp_index_offset: i8, + pub pic_fields: _VAEncPictureParameterBufferH264__bindgen_ty_1, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncPictureParameterBufferH264__bindgen_ty_1 { + pub bits: _VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, + pub __bindgen_padding_0: u16, +} +impl _VAEncPictureParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn idr_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_idr_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn idr_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_idr_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reference_pic_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 2u8) as u32) } + } + #[inline] + pub fn set_reference_pic_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn reference_pic_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reference_pic_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn entropy_coding_mode_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_entropy_coding_mode_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn entropy_coding_mode_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_entropy_coding_mode_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_weighted_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn weighted_bipred_idc(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 2u8) as u32) } + } + #[inline] + pub fn set_weighted_bipred_idc(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn weighted_bipred_idc_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_weighted_bipred_idc_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn constrained_intra_pred_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_constrained_intra_pred_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn constrained_intra_pred_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_constrained_intra_pred_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transform_8x8_mode_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform_8x8_mode_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform_8x8_mode_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform_8x8_mode_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn deblocking_filter_control_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(9usize, 1u8) as u32) } + } + #[inline] + pub fn set_deblocking_filter_control_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(9usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn deblocking_filter_control_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 9usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_deblocking_filter_control_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 9usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn redundant_pic_cnt_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(10usize, 1u8) as u32) } + } + #[inline] + pub fn set_redundant_pic_cnt_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(10usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn redundant_pic_cnt_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 10usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_redundant_pic_cnt_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 10usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pic_order_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(11usize, 1u8) as u32) } + } + #[inline] + pub fn set_pic_order_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(11usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pic_order_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 11usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pic_order_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 11usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pic_scaling_matrix_present_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(12usize, 1u8) as u32) } + } + #[inline] + pub fn set_pic_scaling_matrix_present_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(12usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pic_scaling_matrix_present_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 12usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pic_scaling_matrix_present_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 12usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + 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, + ) -> __BindgenBitfieldUnit<[u8; 2usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let idr_pic_flag: u32 = unsafe { ::std::mem::transmute(idr_pic_flag) }; + idr_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 2u8, { + let reference_pic_flag: u32 = unsafe { ::std::mem::transmute(reference_pic_flag) }; + reference_pic_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let entropy_coding_mode_flag: u32 = unsafe { ::std::mem::transmute(entropy_coding_mode_flag) }; + entropy_coding_mode_flag as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let weighted_pred_flag: u32 = unsafe { ::std::mem::transmute(weighted_pred_flag) }; + weighted_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(5usize, 2u8, { + let weighted_bipred_idc: u32 = unsafe { ::std::mem::transmute(weighted_bipred_idc) }; + weighted_bipred_idc as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let constrained_intra_pred_flag: u32 = unsafe { ::std::mem::transmute(constrained_intra_pred_flag) }; + constrained_intra_pred_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 1u8, { + let transform_8x8_mode_flag: u32 = unsafe { ::std::mem::transmute(transform_8x8_mode_flag) }; + transform_8x8_mode_flag as u64 + }); + __bindgen_bitfield_unit.set(9usize, 1u8, { + let deblocking_filter_control_present_flag: u32 = + unsafe { ::std::mem::transmute(deblocking_filter_control_present_flag) }; + deblocking_filter_control_present_flag as u64 + }); + __bindgen_bitfield_unit.set(10usize, 1u8, { + let redundant_pic_cnt_present_flag: u32 = unsafe { ::std::mem::transmute(redundant_pic_cnt_present_flag) }; + redundant_pic_cnt_present_flag as u64 + }); + __bindgen_bitfield_unit.set(11usize, 1u8, { + let pic_order_present_flag: u32 = unsafe { ::std::mem::transmute(pic_order_present_flag) }; + pic_order_present_flag as u64 + }); + __bindgen_bitfield_unit.set(12usize, 1u8, { + let pic_scaling_matrix_present_flag: u32 = + unsafe { ::std::mem::transmute(pic_scaling_matrix_present_flag) }; + pic_scaling_matrix_present_flag as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncPictureParameterBufferH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncPictureParameterBufferH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Picture parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds information for \\c pic_parameter_set_rbsp() as\n defined by the H.264 specification.\n\n If packed picture headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_PICTURE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderPicture ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If \\c pic_scaling_matrix_present_flag is set to \\c 1, then a\n #VAIQMatrixBufferH264 buffer shall also be provided within the same\n \\c vaRenderPicture() call as this picture parameter buffer."] +pub type VAEncPictureParameterBufferH264 = _VAEncPictureParameterBufferH264; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncQPBufferH264 { + pub qp: u8, +} +pub type VAEncQPBufferH264 = _VAEncQPBufferH264; +#[doc = " \\brief Slice parameter for H.264 encoding in baseline, main & high profiles.\n\n This structure holds information for \\c\n slice_layer_without_partitioning_rbsp() as defined by the H.264\n specification.\n\n If packed slice headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSlice ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If per-macroblock encoder configuration is needed, \\c macroblock_info\n references a buffer of type #VAEncMacroblockParameterBufferH264. This\n buffer is not passed to vaRenderPicture() and it can be re-used\n without re-allocating the whole buffer."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSliceParameterBufferH264 { + #[doc = " \\brief Starting MB address for this slice."] + pub macroblock_address: u32, + #[doc = " \\brief Number of macroblocks in this slice."] + pub num_macroblocks: u32, + #[doc = " \\brief Per-MB encoder configuration buffer, or \\c VA_INVALID_ID.\n\n If per-MB encoder configuration is needed, then \\ref macroblock_info\n references a buffer of type #VAEncMacroblockParameterBufferH264\n (\\c VAEncMacroblockParameterBufferType). Otherwise, buffer id\n is set to \\c VA_INVALID_ID and per-MB configuration is derived\n from this slice parameter.\n\n The \\c macroblock_info buffer must hold \\ref num_macroblocks\n elements."] + pub macroblock_info: VABufferID, + #[doc = " \\brief Slice type.\n Range: 0..2, 5..7, i.e. no switching slices."] + pub slice_type: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub pic_parameter_set_id: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub idr_pic_id: u16, + #[doc = " @name If pic_order_cnt_type == 0 */\n/**@{*/\n/** \\brief The picture order count modulo MaxPicOrderCntLsb."] + pub pic_order_cnt_lsb: u16, + #[doc = " \\brief Valid if \\c pic_order_present_flag and this is a bottom field."] + pub delta_pic_order_cnt_bottom: i32, + #[doc = "@}*/\n/** @name If pic_order_cnt_type == 1 && !delta_pic_order_always_zero_flag */\n/**@{*/\n/** \\brief [0]: top, [1]: bottom."] + pub delta_pic_order_cnt: [i32; 2usize], + #[doc = " @name If slice_type == B */\n/**@{"] + pub direct_spatial_mv_pred_flag: u8, + #[doc = " @name If slice_type == P */\n/**@{*/\n/** \\brief Specifies if\n \\ref _VAEncPictureParameterBufferH264::num_ref_idx_l0_active_minus1 or\n \\ref _VAEncPictureParameterBufferH264::num_ref_idx_l1_active_minus1 are\n overriden by the values for this slice."] + pub num_ref_idx_active_override_flag: u8, + #[doc = " \\brief Maximum reference index for reference picture list 0.\n Range: 0 to 31, inclusive."] + pub num_ref_idx_l0_active_minus1: u8, + #[doc = " \\brief Maximum reference index for reference picture list 1.\n Range: 0 to 31, inclusive."] + pub num_ref_idx_l1_active_minus1: u8, + #[doc = " \\brief Reference picture list 0 (for P slices)."] + pub RefPicList0: [VAPictureH264; 32usize], + #[doc = " \\brief Reference picture list 1 (for B slices)."] + pub RefPicList1: [VAPictureH264; 32usize], + #[doc = " @name pred_weight_table() */\n/**@{*/\n/** \\brief Same as the H.264 bitstream syntax element."] + pub luma_log2_weight_denom: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_log2_weight_denom: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_weight_l0_flag: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_weight_l0: [::std::os::raw::c_short; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_offset_l0: [::std::os::raw::c_short; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_weight_l0_flag: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_weight_l0: [[::std::os::raw::c_short; 2usize]; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_offset_l0: [[::std::os::raw::c_short; 2usize]; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_weight_l1_flag: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_weight_l1: [::std::os::raw::c_short; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub luma_offset_l1: [::std::os::raw::c_short; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_weight_l1_flag: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_weight_l1: [[::std::os::raw::c_short; 2usize]; 32usize], + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub chroma_offset_l1: [[::std::os::raw::c_short; 2usize]; 32usize], + #[doc = " \\brief Range: 0 to 2, inclusive."] + pub cabac_init_idc: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub slice_qp_delta: i8, + #[doc = " @name If deblocking_filter_control_present_flag */\n/**@{*/\n/** \\brief Range: 0 to 2, inclusive."] + pub disable_deblocking_filter_idc: u8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub slice_alpha_c0_offset_div2: i8, + #[doc = " \\brief Same as the H.264 bitstream syntax element."] + pub slice_beta_offset_div2: i8, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Slice parameter for H.264 encoding in baseline, main & high profiles.\n\n This structure holds information for \\c\n slice_layer_without_partitioning_rbsp() as defined by the H.264\n specification.\n\n If packed slice headers mode is used, i.e. if the encoding\n pipeline was configured with the #VA_ENC_PACKED_HEADER_SLICE\n flag, then the driver expects two more buffers to be provided to\n the same \\c vaRenderPicture() as this buffer:\n - a #VAEncPackedHeaderParameterBuffer with type set to\n VAEncPackedHeaderType::VAEncPackedHeaderSlice ;\n - a #VAEncPackedHeaderDataBuffer which holds the actual packed\n header data.\n\n If per-macroblock encoder configuration is needed, \\c macroblock_info\n references a buffer of type #VAEncMacroblockParameterBufferH264. This\n buffer is not passed to vaRenderPicture() and it can be re-used\n without re-allocating the whole buffer."] +pub type VAEncSliceParameterBufferH264 = _VAEncSliceParameterBufferH264; +#[doc = " \\brief Macroblock parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds per-macroblock information. The buffer must be\n allocated with as many elements (macroblocks) as necessary to fit\n the slice to be encoded. Besides, the per-macroblock records must\n be written in a strict raster order and with no gap. i.e. every\n macroblock, regardless of its type, shall have an entry."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMacroblockParameterBufferH264 { + #[doc = " \\brief Quantization parameter.\n\n Requested quantization parameter. Range: 0 to 51, inclusive.\n If \\ref qp is set to 0xff, then the actual value is derived\n from the slice-level value: \\c pic_init_qp + \\c slice_qp_delta."] + pub qp: u8, + pub info: _VAEncMacroblockParameterBufferH264__bindgen_ty_1, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + pub intra_fields: _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1, + pub inter_fields: _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2, +} +#[doc = " @name Data for intra macroblock */\n/**@{"] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + pub bits: _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, + pub __bindgen_padding_0: u16, +} +impl _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn pred_avail_override_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_pred_avail_override_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn pred_avail_override_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pred_avail_override_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn pred_avail_flags(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 8u8) as u32) } + } + #[inline] + pub fn set_pred_avail_flags(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn pred_avail_flags_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 2usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_pred_avail_flags_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 2usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(pred_avail_override_flag: u32, pred_avail_flags: u32) -> __BindgenBitfieldUnit<[u8; 2usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let pred_avail_override_flag: u32 = unsafe { ::std::mem::transmute(pred_avail_override_flag) }; + pred_avail_override_flag as u64 + }); + __bindgen_bitfield_unit.set(1usize, 8u8, { + let pred_avail_flags: u32 = unsafe { ::std::mem::transmute(pred_avail_flags) }; + pred_avail_flags as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " @name Data for inter macroblock */\n/**@{"] +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2 { + pub bits: _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2__bindgen_ty_1, + pub value: u32, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2__bindgen_ty_1 { + pub reserved: u32, +} +impl Default for _VAEncMacroblockParameterBufferH264__bindgen_ty_1__bindgen_ty_2 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMacroblockParameterBufferH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMacroblockParameterBufferH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Macroblock parameter for H.264 encoding in baseline, main & high\n profiles.\n\n This structure holds per-macroblock information. The buffer must be\n allocated with as many elements (macroblocks) as necessary to fit\n the slice to be encoded. Besides, the per-macroblock records must\n be written in a strict raster order and with no gap. i.e. every\n macroblock, regardless of its type, shall have an entry."] +pub type VAEncMacroblockParameterBufferH264 = _VAEncMacroblockParameterBufferH264; +#[doc = " \\brief MB partition modes and 1/2 1/4 motion search configuration\n\n Specifies MB partition modes that are disabled. Specifies Half-pel\n mode and Quarter-pel mode searching"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterSubMbPartPelH264 { + pub disable_inter_sub_mb_partition: u32, + pub inter_sub_mb_partition_mask: _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1, + #[doc = " \\brief Precison of motion search\n 0:Integer mode searching\n 1:Half-pel mode searching\n 2:Reserved\n 3:Quarter-pel mode searching"] + pub enable_sub_pel_mode: u32, + pub sub_pel_mode: u8, + pub reserved: [u8; 3usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1 { + pub bits: _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1__bindgen_ty_1, + pub value: u8, +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, + pub __bindgen_padding_0: [u8; 3usize], +} +impl _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn disable_16x16_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_16x16_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_16x16_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_16x16_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_16x8_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_16x8_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_16x8_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_16x8_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_8x16_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_8x16_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_8x16_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_8x16_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_8x8_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_8x8_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_8x8_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_8x8_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_8x4_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_8x4_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_8x4_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_8x4_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_4x8_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_4x8_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_4x8_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_4x8_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_4x4_inter_mb_partition(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_4x4_inter_mb_partition(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_4x4_inter_mb_partition_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_4x4_inter_mb_partition_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_reserved(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + disable_16x16_inter_mb_partition: u32, + disable_16x8_inter_mb_partition: u32, + disable_8x16_inter_mb_partition: u32, + disable_8x8_inter_mb_partition: u32, + disable_8x4_inter_mb_partition: u32, + disable_4x8_inter_mb_partition: u32, + disable_4x4_inter_mb_partition: u32, + reserved: u32, + ) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let disable_16x16_inter_mb_partition: u32 = + unsafe { ::std::mem::transmute(disable_16x16_inter_mb_partition) }; + disable_16x16_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let disable_16x8_inter_mb_partition: u32 = + unsafe { ::std::mem::transmute(disable_16x8_inter_mb_partition) }; + disable_16x8_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let disable_8x16_inter_mb_partition: u32 = + unsafe { ::std::mem::transmute(disable_8x16_inter_mb_partition) }; + disable_8x16_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let disable_8x8_inter_mb_partition: u32 = unsafe { ::std::mem::transmute(disable_8x8_inter_mb_partition) }; + disable_8x8_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let disable_8x4_inter_mb_partition: u32 = unsafe { ::std::mem::transmute(disable_8x4_inter_mb_partition) }; + disable_8x4_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(5usize, 1u8, { + let disable_4x8_inter_mb_partition: u32 = unsafe { ::std::mem::transmute(disable_4x8_inter_mb_partition) }; + disable_4x8_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let disable_4x4_inter_mb_partition: u32 = unsafe { ::std::mem::transmute(disable_4x4_inter_mb_partition) }; + disable_4x4_inter_mb_partition as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let reserved: u32 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncMiscParameterSubMbPartPelH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncMiscParameterSubMbPartPelH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief MB partition modes and 1/2 1/4 motion search configuration\n\n Specifies MB partition modes that are disabled. Specifies Half-pel\n mode and Quarter-pel mode searching"] +pub type VAEncMiscParameterSubMbPartPelH264 = _VAEncMiscParameterSubMbPartPelH264; +pub mod VAEncPackedHeaderTypeMPEG2 { + #[doc = " \\brief Packed header types specific to MPEG-2 encoding.\n\n Types of packed headers generally used for MPEG-2 encoding."] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Packed Sequence Parameter Set (SPS).\n"] + pub const VAEncPackedHeaderMPEG2_SPS: Type = 1; + #[doc = " \\brief Packed Picture Parameter Set (PPS).\n"] + pub const VAEncPackedHeaderMPEG2_PPS: Type = 2; + #[doc = " \\brief Packed slice header.\n"] + pub const VAEncPackedHeaderMPEG2_Slice: Type = 3; +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterExtensionDataSeqDisplayMPEG2 { + #[doc = " should always be 0x02 to identify it is Sequence Display Extension ISO-13818"] + pub extension_start_code_identifier: u8, + #[doc = " these field should follow ISO-13818 6.3.6"] + pub video_format: u8, + pub colour_description: u8, + pub colour_primaries: u8, + pub transfer_characteristics: u8, + pub matrix_coefficients: u8, + pub display_horizontal_size: u16, + pub display_vertical_size: u16, +} +pub type VAEncMiscParameterExtensionDataSeqDisplayMPEG2 = _VAEncMiscParameterExtensionDataSeqDisplayMPEG2; +#[doc = " \\brief Per segment parameters"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncSegParamVP9 { + pub seg_flags: _VAEncSegParamVP9__bindgen_ty_1, + #[doc = " \\brief Specifies per segment Loop Filter Delta.\n Must be 0 when segmentation_enabled == 0.\n value range: [-63..63]"] + pub segment_lf_level_delta: i8, + #[doc = " \\brief Specifies per segment QIndex Delta.\n Must be 0 when segmentation_enabled == 0.\n value range: [-255..255]"] + pub segment_qindex_delta: i16, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncSegParamVP9__bindgen_ty_1 { + pub bits: _VAEncSegParamVP9__bindgen_ty_1__bindgen_ty_1, + pub value: u8, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncSegParamVP9__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, +} +impl _VAEncSegParamVP9__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn segment_reference_enabled(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u8) } + } + #[inline] + pub fn set_segment_reference_enabled(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn segment_reference_enabled_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_segment_reference_enabled_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn segment_reference(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 2u8) as u8) } + } + #[inline] + pub fn set_segment_reference(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn segment_reference_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 2u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_segment_reference_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn segment_reference_skipped(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u8) } + } + #[inline] + pub fn set_segment_reference_skipped(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn segment_reference_skipped_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_segment_reference_skipped_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u8) } + } + #[inline] + pub fn set_reserved(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 4u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_reserved_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + segment_reference_enabled: u8, + segment_reference: u8, + segment_reference_skipped: u8, + reserved: u8, + ) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let segment_reference_enabled: u8 = unsafe { ::std::mem::transmute(segment_reference_enabled) }; + segment_reference_enabled as u64 + }); + __bindgen_bitfield_unit.set(1usize, 2u8, { + let segment_reference: u8 = unsafe { ::std::mem::transmute(segment_reference) }; + segment_reference as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let segment_reference_skipped: u8 = unsafe { ::std::mem::transmute(segment_reference_skipped) }; + segment_reference_skipped as u64 + }); + __bindgen_bitfield_unit.set(4usize, 4u8, { + let reserved: u8 = unsafe { ::std::mem::transmute(reserved) }; + reserved as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncSegParamVP9__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncSegParamVP9 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Per segment parameters"] +pub type VAEncSegParamVP9 = _VAEncSegParamVP9; +#[doc = " Structure to convey all segment related information.\n If segmentation is disabled, this data structure is still required.\n In this case, only seg_data[0] contains valid data.\n This buffer is sent once per frame.\n\n The buffer is created with VABufferType VAQMatrixBufferType.\n"] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncMiscParameterTypeVP9PerSegmantParam { + #[doc = " Parameters for 8 segments."] + pub seg_data: [VAEncSegParamVP9; 8usize], + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAEncMiscParameterTypeVP9PerSegmantParam { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " Structure to convey all segment related information.\n If segmentation is disabled, this data structure is still required.\n In this case, only seg_data[0] contains valid data.\n This buffer is sent once per frame.\n\n The buffer is created with VABufferType VAQMatrixBufferType.\n"] +pub type VAEncMiscParameterTypeVP9PerSegmantParam = _VAEncMiscParameterTypeVP9PerSegmantParam; +pub mod VAEncPackedHeaderTypeAV1 { + #[doc = " \\brief Packed header types specific to AV1 encoding.\n\n Types of packed headers generally used for AV1 encoding.\n"] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Packed Sequence Parameter Set (SPS).\n\n The corresponding packed header data buffer shall contain the\n complete sequence_header_obu() syntax element.\n"] + pub const VAEncPackedHeaderAV1_SPS: Type = 1; + #[doc = " \\brief Packed Picture Parameter Set (PPS).\n\n The corresponding packed header data buffer shall contain the\n complete frame_header_obu() syntax element.\n"] + pub const VAEncPackedHeaderAV1_PPS: Type = 2; +} +#[doc = " \\brief FEI frame level control buffer for H.264"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncMiscParameterFEIFrameControlH264 { + pub function: u32, + #[doc = " \\brief MB (16x16) control input buffer. It is valid only when (mb_input | mb_size_ctrl)\n is set to 1. The data in this buffer correspond to the input source. 16x16 MB is in raster scan order,\n each MB control data structure is defined by VAEncFEIMBControlH264.\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAEncFEIMBControlH264).\n Note: if mb_qp is set, VAEncQPBufferH264 is expected."] + pub mb_ctrl: VABufferID, + #[doc = " \\brief distortion output of MB ENC or ENC_PAK.\n Each 16x16 block has one distortion data with VAEncFEIDistortionH264 layout\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAEncFEIDistortionH264)."] + pub distortion: VABufferID, + #[doc = " \\brief MVs data output of MB ENC.\n Each 16x16 block has one MVs data with layout VAMotionVector\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAMotionVector) * 16."] + pub mv_data: VABufferID, + #[doc = " \\brief MBCode data output of MB ENC.\n Each 16x16 block has one MB Code data with layout VAEncFEIMBCodeH264\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAEncFEIMBCodeH264)."] + pub mb_code_data: VABufferID, + #[doc = " \\brief QP input buffer with layout VAEncQPBufferH264. It is valid only when mb_qp is set to 1.\n The data in this buffer correspond to the input source.\n One QP per 16x16 block in raster scan order, each QP is a signed char (8-bit) value."] + pub qp: VABufferID, + #[doc = " \\brief MV predictor. It is valid only when mv_predictor_enable is set to 1.\n Each 16x16 block has one or more pair of motion vectors and the corresponding\n reference indexes as defined by VAEncFEIMVPredictorH264. 16x16 block is in raster scan order.\n Buffer size shall not be less than the number of 16x16 blocks multiplied by\n sizeof(VAEncFEIMVPredictorH264)."] + pub mv_predictor: VABufferID, + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, + #[doc = " \\brief max frame size control with multi passes QP setting"] + pub max_frame_size: u32, + #[doc = " \\brief number of passes, every pass has different QP"] + pub num_passes: u32, + #[doc = " \\brief delta QP list for every pass"] + pub delta_qp: *mut u8, + pub reserved3: [u32; 4usize], +} +impl Default for _VAEncMiscParameterFEIFrameControlH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl _VAEncMiscParameterFEIFrameControlH264 { + #[inline] + pub fn num_mv_predictors_l0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_num_mv_predictors_l0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn num_mv_predictors_l0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_mv_predictors_l0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn num_mv_predictors_l1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_num_mv_predictors_l1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn num_mv_predictors_l1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_mv_predictors_l1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn search_path(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 8u8) as u32) } + } + #[inline] + pub fn set_search_path(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn search_path_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_path_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn len_sp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 8u8) as u32) } + } + #[inline] + pub fn set_len_sp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(40usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn len_sp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 40usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_len_sp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_mb_part_mask(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 7u8) as u32) } + } + #[inline] + pub fn set_sub_mb_part_mask(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 7u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_mb_part_mask_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 7u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_mb_part_mask_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 7u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_part_mask(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(71usize, 5u8) as u32) } + } + #[inline] + pub fn set_intra_part_mask(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(71usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_part_mask_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 71usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_part_mask_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 71usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn multi_pred_l0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(76usize, 1u8) as u32) } + } + #[inline] + pub fn set_multi_pred_l0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(76usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn multi_pred_l0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 76usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_multi_pred_l0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 76usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn multi_pred_l1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(77usize, 1u8) as u32) } + } + #[inline] + pub fn set_multi_pred_l1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(77usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn multi_pred_l1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 77usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_multi_pred_l1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 77usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_pel_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(78usize, 2u8) as u32) } + } + #[inline] + pub fn set_sub_pel_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(78usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_pel_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 78usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_pel_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 78usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn inter_sad(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 2u8) as u32) } + } + #[inline] + pub fn set_inter_sad(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn inter_sad_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_inter_sad_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_sad(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(82usize, 2u8) as u32) } + } + #[inline] + pub fn set_intra_sad(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(82usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_sad_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 82usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_sad_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 82usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn distortion_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(84usize, 1u8) as u32) } + } + #[inline] + pub fn set_distortion_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(84usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn distortion_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 84usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_distortion_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 84usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn repartition_check_enable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(85usize, 1u8) as u32) } + } + #[inline] + pub fn set_repartition_check_enable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(85usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn repartition_check_enable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 85usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_repartition_check_enable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 85usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn adaptive_search(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(86usize, 1u8) as u32) } + } + #[inline] + pub fn set_adaptive_search(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(86usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn adaptive_search_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 86usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_adaptive_search_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 86usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mv_predictor_enable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(87usize, 1u8) as u32) } + } + #[inline] + pub fn set_mv_predictor_enable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(87usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mv_predictor_enable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 87usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mv_predictor_enable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 87usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_qp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(88usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_qp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(88usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_qp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 88usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_qp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 88usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_input(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(89usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_input(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(89usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_input_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 89usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_input_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 89usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_size_ctrl(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(90usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_size_ctrl(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(90usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_size_ctrl_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 90usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_size_ctrl_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 90usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn colocated_mb_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(91usize, 1u8) as u32) } + } + #[inline] + pub fn set_colocated_mb_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(91usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn colocated_mb_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 91usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_colocated_mb_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 91usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(92usize, 4u8) as u32) } + } + #[inline] + pub fn set_reserved1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(92usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 92usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 92usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_width(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_width(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(96usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_width_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 96usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_width_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_height(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(104usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_height(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(104usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_height_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 104usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_height_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 104usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn search_window(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(112usize, 4u8) as u32) } + } + #[inline] + pub fn set_search_window(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(112usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn search_window_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 112usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_window_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 112usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(116usize, 12u8) as u32) } + } + #[inline] + pub fn set_reserved2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(116usize, 12u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 116usize, + 12u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 116usize, + 12u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + num_mv_predictors_l0: u32, + num_mv_predictors_l1: u32, + search_path: u32, + len_sp: u32, + reserved0: u32, + sub_mb_part_mask: u32, + intra_part_mask: u32, + multi_pred_l0: u32, + multi_pred_l1: u32, + sub_pel_mode: u32, + inter_sad: u32, + intra_sad: u32, + distortion_type: u32, + repartition_check_enable: u32, + adaptive_search: u32, + mv_predictor_enable: u32, + mb_qp: u32, + mb_input: u32, + mb_size_ctrl: u32, + colocated_mb_distortion: u32, + reserved1: u32, + ref_width: u32, + ref_height: u32, + search_window: u32, + reserved2: u32, + ) -> __BindgenBitfieldUnit<[u8; 16usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let num_mv_predictors_l0: u32 = unsafe { ::std::mem::transmute(num_mv_predictors_l0) }; + num_mv_predictors_l0 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let num_mv_predictors_l1: u32 = unsafe { ::std::mem::transmute(num_mv_predictors_l1) }; + num_mv_predictors_l1 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 8u8, { + let search_path: u32 = unsafe { ::std::mem::transmute(search_path) }; + search_path as u64 + }); + __bindgen_bitfield_unit.set(40usize, 8u8, { + let len_sp: u32 = unsafe { ::std::mem::transmute(len_sp) }; + len_sp as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 7u8, { + let sub_mb_part_mask: u32 = unsafe { ::std::mem::transmute(sub_mb_part_mask) }; + sub_mb_part_mask as u64 + }); + __bindgen_bitfield_unit.set(71usize, 5u8, { + let intra_part_mask: u32 = unsafe { ::std::mem::transmute(intra_part_mask) }; + intra_part_mask as u64 + }); + __bindgen_bitfield_unit.set(76usize, 1u8, { + let multi_pred_l0: u32 = unsafe { ::std::mem::transmute(multi_pred_l0) }; + multi_pred_l0 as u64 + }); + __bindgen_bitfield_unit.set(77usize, 1u8, { + let multi_pred_l1: u32 = unsafe { ::std::mem::transmute(multi_pred_l1) }; + multi_pred_l1 as u64 + }); + __bindgen_bitfield_unit.set(78usize, 2u8, { + let sub_pel_mode: u32 = unsafe { ::std::mem::transmute(sub_pel_mode) }; + sub_pel_mode as u64 + }); + __bindgen_bitfield_unit.set(80usize, 2u8, { + let inter_sad: u32 = unsafe { ::std::mem::transmute(inter_sad) }; + inter_sad as u64 + }); + __bindgen_bitfield_unit.set(82usize, 2u8, { + let intra_sad: u32 = unsafe { ::std::mem::transmute(intra_sad) }; + intra_sad as u64 + }); + __bindgen_bitfield_unit.set(84usize, 1u8, { + let distortion_type: u32 = unsafe { ::std::mem::transmute(distortion_type) }; + distortion_type as u64 + }); + __bindgen_bitfield_unit.set(85usize, 1u8, { + let repartition_check_enable: u32 = unsafe { ::std::mem::transmute(repartition_check_enable) }; + repartition_check_enable as u64 + }); + __bindgen_bitfield_unit.set(86usize, 1u8, { + let adaptive_search: u32 = unsafe { ::std::mem::transmute(adaptive_search) }; + adaptive_search as u64 + }); + __bindgen_bitfield_unit.set(87usize, 1u8, { + let mv_predictor_enable: u32 = unsafe { ::std::mem::transmute(mv_predictor_enable) }; + mv_predictor_enable as u64 + }); + __bindgen_bitfield_unit.set(88usize, 1u8, { + let mb_qp: u32 = unsafe { ::std::mem::transmute(mb_qp) }; + mb_qp as u64 + }); + __bindgen_bitfield_unit.set(89usize, 1u8, { + let mb_input: u32 = unsafe { ::std::mem::transmute(mb_input) }; + mb_input as u64 + }); + __bindgen_bitfield_unit.set(90usize, 1u8, { + let mb_size_ctrl: u32 = unsafe { ::std::mem::transmute(mb_size_ctrl) }; + mb_size_ctrl as u64 + }); + __bindgen_bitfield_unit.set(91usize, 1u8, { + let colocated_mb_distortion: u32 = unsafe { ::std::mem::transmute(colocated_mb_distortion) }; + colocated_mb_distortion as u64 + }); + __bindgen_bitfield_unit.set(92usize, 4u8, { + let reserved1: u32 = unsafe { ::std::mem::transmute(reserved1) }; + reserved1 as u64 + }); + __bindgen_bitfield_unit.set(96usize, 8u8, { + let ref_width: u32 = unsafe { ::std::mem::transmute(ref_width) }; + ref_width as u64 + }); + __bindgen_bitfield_unit.set(104usize, 8u8, { + let ref_height: u32 = unsafe { ::std::mem::transmute(ref_height) }; + ref_height as u64 + }); + __bindgen_bitfield_unit.set(112usize, 4u8, { + let search_window: u32 = unsafe { ::std::mem::transmute(search_window) }; + search_window as u64 + }); + __bindgen_bitfield_unit.set(116usize, 12u8, { + let reserved2: u32 = unsafe { ::std::mem::transmute(reserved2) }; + reserved2 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief FEI frame level control buffer for H.264"] +pub type VAEncMiscParameterFEIFrameControlH264 = _VAEncMiscParameterFEIFrameControlH264; +#[doc = " \\brief FEI MB level control data structure"] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMBControlH264 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, + pub reserved1: u32, + pub reserved2: u32, + pub _bitfield_align_2: [u16; 0], + pub _bitfield_2: __BindgenBitfieldUnit<[u8; 4usize]>, +} +impl _VAEncFEIMBControlH264 { + #[inline] + pub fn force_to_intra(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_intra(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_intra_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_intra_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_to_skip(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_skip(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(1usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_skip_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 1usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_skip_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 1usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn force_to_nonskip(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_force_to_nonskip(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn force_to_nonskip_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_force_to_nonskip_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_direct_bias_adjustment(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_direct_bias_adjustment(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_direct_bias_adjustment_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_direct_bias_adjustment_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_motion_bias_adjustment(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_motion_bias_adjustment(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_motion_bias_adjustment_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_motion_bias_adjustment_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ext_mv_cost_scaling_factor(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 3u8) as u32) } + } + #[inline] + pub fn set_ext_mv_cost_scaling_factor(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(5usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn ext_mv_cost_scaling_factor_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 5usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ext_mv_cost_scaling_factor_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 5usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 24u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 24u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 24u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 24u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + force_to_intra: u32, + force_to_skip: u32, + force_to_nonskip: u32, + enable_direct_bias_adjustment: u32, + enable_motion_bias_adjustment: u32, + ext_mv_cost_scaling_factor: u32, + reserved0: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let force_to_intra: u32 = unsafe { ::std::mem::transmute(force_to_intra) }; + force_to_intra as u64 + }); + __bindgen_bitfield_unit.set(1usize, 1u8, { + let force_to_skip: u32 = unsafe { ::std::mem::transmute(force_to_skip) }; + force_to_skip as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let force_to_nonskip: u32 = unsafe { ::std::mem::transmute(force_to_nonskip) }; + force_to_nonskip as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let enable_direct_bias_adjustment: u32 = unsafe { ::std::mem::transmute(enable_direct_bias_adjustment) }; + enable_direct_bias_adjustment as u64 + }); + __bindgen_bitfield_unit.set(4usize, 1u8, { + let enable_motion_bias_adjustment: u32 = unsafe { ::std::mem::transmute(enable_motion_bias_adjustment) }; + enable_motion_bias_adjustment as u64 + }); + __bindgen_bitfield_unit.set(5usize, 3u8, { + let ext_mv_cost_scaling_factor: u32 = unsafe { ::std::mem::transmute(ext_mv_cost_scaling_factor) }; + ext_mv_cost_scaling_factor as u64 + }); + __bindgen_bitfield_unit.set(8usize, 24u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit + } + #[inline] + pub fn reserved3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn target_size_in_word(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(16usize, 8u8) as u32) } + } + #[inline] + pub fn set_target_size_in_word(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(16usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn target_size_in_word_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 16usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_target_size_in_word_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn max_size_in_word(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(24usize, 8u8) as u32) } + } + #[inline] + pub fn set_max_size_in_word(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(24usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn max_size_in_word_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 24usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_max_size_in_word_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_2( + reserved3: u32, + target_size_in_word: u32, + max_size_in_word: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let reserved3: u32 = unsafe { ::std::mem::transmute(reserved3) }; + reserved3 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 8u8, { + let target_size_in_word: u32 = unsafe { ::std::mem::transmute(target_size_in_word) }; + target_size_in_word as u64 + }); + __bindgen_bitfield_unit.set(24usize, 8u8, { + let max_size_in_word: u32 = unsafe { ::std::mem::transmute(max_size_in_word) }; + max_size_in_word as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief FEI MB level control data structure"] +pub type VAEncFEIMBControlH264 = _VAEncFEIMBControlH264; +#[doc = " \\brief Application can use this definition as reference to allocate the buffer\n based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMVPredictorH264 { + pub ref_idx: [_VAEncFEIMVPredictorH264__bindgen_ty_1; 4usize], + pub reserved: u32, + #[doc = " \\brief MV. MaxNumPredictor must be the returned value from attribute VAConfigAttribFEIMVPredictors query.\n Even application doesn't use the maximum predictors, the VAFEIMVPredictorH264 structure size\n has to be defined as maximum so each MB can be at a fixed location.\n Note that 0x8000 must be used for correspondent intra block."] + pub mv: [VAMotionVector; 4usize], +} +#[doc = " \\brief Reference index corresponding to the entry of RefPicList0 & RefPicList1 in VAEncSliceParameterBufferH264.\n Note that RefPicList0 & RefPicList1 needs to be the same for all slices.\n ref_idx_l0_x : index to RefPicList0; ref_idx_l1_x : index to RefPicList1; x : 0 - MaxNumPredictor."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMVPredictorH264__bindgen_ty_1 { + pub _bitfield_align_1: [u8; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, +} +impl _VAEncFEIMVPredictorH264__bindgen_ty_1 { + #[inline] + pub fn ref_idx_l0(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 4u8) as u8) } + } + #[inline] + pub fn set_ref_idx_l0(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 4u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1(&self) -> u8 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u8) } + } + #[inline] + pub fn set_ref_idx_l1(&mut self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_raw(this: *const Self) -> u8 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 1usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 4u8, + ) as u8) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_raw(this: *mut Self, val: u8) { + unsafe { + let val: u8 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 1usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1(ref_idx_l0: u8, ref_idx_l1: u8) -> __BindgenBitfieldUnit<[u8; 1usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 4u8, { + let ref_idx_l0: u8 = unsafe { ::std::mem::transmute(ref_idx_l0) }; + ref_idx_l0 as u64 + }); + __bindgen_bitfield_unit.set(4usize, 4u8, { + let ref_idx_l1: u8 = unsafe { ::std::mem::transmute(ref_idx_l1) }; + ref_idx_l1 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief Application can use this definition as reference to allocate the buffer\n based on MaxNumPredictor returned from attribute VAConfigAttribFEIMVPredictors query."] +pub type VAEncFEIMVPredictorH264 = _VAEncFEIMVPredictorH264; +#[doc = " \\brief VAEncFEIMBCodeH264 defines the data structure for VAEncFEIMBCodeBufferType per 16x16 MB block.\n it is output buffer of ENC and ENC_PAK modes, it's also input buffer of PAK mode.\n The 16x16 block is in raster scan order. Buffer size shall not be less than the number of 16x16 blocks\n multiplied by sizeof(VAEncFEIMBCodeH264). Note that, when separate ENC and PAK is enabled,\n the exact layout of this buffer is needed for PAK input. App can reuse this buffer,\n or copy to a different buffer as PAK input, reserved elements must not be modified when used as PAK input."] +#[repr(C)] +#[derive(Copy, Clone)] +pub struct _VAEncFEIMBCodeH264 { + pub reserved0: [u32; 3usize], + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, + pub mb_mode: _VAEncFEIMBCodeH264__bindgen_ty_1, + pub _bitfield_align_2: [u16; 0], + pub _bitfield_2: __BindgenBitfieldUnit<[u8; 4usize]>, + pub reserved9: [u32; 4usize], + pub reserved10: u32, +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union _VAEncFEIMBCodeH264__bindgen_ty_1 { + pub intra_mb: _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_1, + pub inter_mb: _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_2, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_1 { + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 12usize]>, +} +impl _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_1 { + #[inline] + pub fn luma_intra_pred_modes0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_luma_intra_pred_modes0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn luma_intra_pred_modes0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_luma_intra_pred_modes0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn luma_intra_pred_modes1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_luma_intra_pred_modes1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn luma_intra_pred_modes1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_luma_intra_pred_modes1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn luma_intra_pred_modes2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 16u8) as u32) } + } + #[inline] + pub fn set_luma_intra_pred_modes2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn luma_intra_pred_modes2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_luma_intra_pred_modes2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn luma_intra_pred_modes3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_luma_intra_pred_modes3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn luma_intra_pred_modes3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_luma_intra_pred_modes3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn chroma_intra_pred_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 2u8) as u32) } + } + #[inline] + pub fn set_chroma_intra_pred_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn chroma_intra_pred_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_chroma_intra_pred_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_pred_avail_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(66usize, 5u8) as u32) } + } + #[inline] + pub fn set_intra_pred_avail_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(66usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_pred_avail_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 66usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_pred_avail_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 66usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_pred_avail_flagF(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(71usize, 1u8) as u32) } + } + #[inline] + pub fn set_intra_pred_avail_flagF(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(71usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_pred_avail_flagF_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 71usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_pred_avail_flagF_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 71usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved6(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(72usize, 24u8) as u32) } + } + #[inline] + pub fn set_reserved6(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(72usize, 24u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved6_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 72usize, + 24u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved6_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 72usize, + 24u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + luma_intra_pred_modes0: u32, + luma_intra_pred_modes1: u32, + luma_intra_pred_modes2: u32, + luma_intra_pred_modes3: u32, + chroma_intra_pred_mode: u32, + intra_pred_avail_flag: u32, + intra_pred_avail_flagF: u32, + reserved6: u32, + ) -> __BindgenBitfieldUnit<[u8; 12usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 12usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let luma_intra_pred_modes0: u32 = unsafe { ::std::mem::transmute(luma_intra_pred_modes0) }; + luma_intra_pred_modes0 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let luma_intra_pred_modes1: u32 = unsafe { ::std::mem::transmute(luma_intra_pred_modes1) }; + luma_intra_pred_modes1 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 16u8, { + let luma_intra_pred_modes2: u32 = unsafe { ::std::mem::transmute(luma_intra_pred_modes2) }; + luma_intra_pred_modes2 as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let luma_intra_pred_modes3: u32 = unsafe { ::std::mem::transmute(luma_intra_pred_modes3) }; + luma_intra_pred_modes3 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 2u8, { + let chroma_intra_pred_mode: u32 = unsafe { ::std::mem::transmute(chroma_intra_pred_mode) }; + chroma_intra_pred_mode as u64 + }); + __bindgen_bitfield_unit.set(66usize, 5u8, { + let intra_pred_avail_flag: u32 = unsafe { ::std::mem::transmute(intra_pred_avail_flag) }; + intra_pred_avail_flag as u64 + }); + __bindgen_bitfield_unit.set(71usize, 1u8, { + let intra_pred_avail_flagF: u32 = unsafe { ::std::mem::transmute(intra_pred_avail_flagF) }; + intra_pred_avail_flagF as u64 + }); + __bindgen_bitfield_unit.set(72usize, 24u8, { + let reserved6: u32 = unsafe { ::std::mem::transmute(reserved6) }; + reserved6 as u64 + }); + __bindgen_bitfield_unit + } +} +#[repr(C)] +#[repr(align(4))] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_2 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 12usize]>, +} +impl _VAEncFEIMBCodeH264__bindgen_ty_1__bindgen_ty_2 { + #[inline] + pub fn sub_mb_shapes(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 8u8) as u32) } + } + #[inline] + pub fn set_sub_mb_shapes(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_mb_shapes_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_mb_shapes_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_mb_pred_modes(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 8u8) as u32) } + } + #[inline] + pub fn set_sub_mb_pred_modes(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_mb_pred_modes_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_mb_pred_modes_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved7(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved7(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved7_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved7_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l0_0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l0_0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l0_1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l0_1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(40usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 40usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l0_2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l0_2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l0_3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(56usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l0_3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(56usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l0_3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 56usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l0_3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 56usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1_0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l1_0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1_1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(72usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l1_1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(72usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 72usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 72usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1_2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l1_2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_idx_l1_3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(88usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_idx_l1_3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(88usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_idx_l1_3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 12usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 88usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_idx_l1_3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 12usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 88usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + sub_mb_shapes: u32, + sub_mb_pred_modes: u32, + reserved7: u32, + ref_idx_l0_0: u32, + ref_idx_l0_1: u32, + ref_idx_l0_2: u32, + ref_idx_l0_3: u32, + ref_idx_l1_0: u32, + ref_idx_l1_1: u32, + ref_idx_l1_2: u32, + ref_idx_l1_3: u32, + ) -> __BindgenBitfieldUnit<[u8; 12usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 12usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 8u8, { + let sub_mb_shapes: u32 = unsafe { ::std::mem::transmute(sub_mb_shapes) }; + sub_mb_shapes as u64 + }); + __bindgen_bitfield_unit.set(8usize, 8u8, { + let sub_mb_pred_modes: u32 = unsafe { ::std::mem::transmute(sub_mb_pred_modes) }; + sub_mb_pred_modes as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let reserved7: u32 = unsafe { ::std::mem::transmute(reserved7) }; + reserved7 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 8u8, { + let ref_idx_l0_0: u32 = unsafe { ::std::mem::transmute(ref_idx_l0_0) }; + ref_idx_l0_0 as u64 + }); + __bindgen_bitfield_unit.set(40usize, 8u8, { + let ref_idx_l0_1: u32 = unsafe { ::std::mem::transmute(ref_idx_l0_1) }; + ref_idx_l0_1 as u64 + }); + __bindgen_bitfield_unit.set(48usize, 8u8, { + let ref_idx_l0_2: u32 = unsafe { ::std::mem::transmute(ref_idx_l0_2) }; + ref_idx_l0_2 as u64 + }); + __bindgen_bitfield_unit.set(56usize, 8u8, { + let ref_idx_l0_3: u32 = unsafe { ::std::mem::transmute(ref_idx_l0_3) }; + ref_idx_l0_3 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 8u8, { + let ref_idx_l1_0: u32 = unsafe { ::std::mem::transmute(ref_idx_l1_0) }; + ref_idx_l1_0 as u64 + }); + __bindgen_bitfield_unit.set(72usize, 8u8, { + let ref_idx_l1_1: u32 = unsafe { ::std::mem::transmute(ref_idx_l1_1) }; + ref_idx_l1_1 as u64 + }); + __bindgen_bitfield_unit.set(80usize, 8u8, { + let ref_idx_l1_2: u32 = unsafe { ::std::mem::transmute(ref_idx_l1_2) }; + ref_idx_l1_2 as u64 + }); + __bindgen_bitfield_unit.set(88usize, 8u8, { + let ref_idx_l1_3: u32 = unsafe { ::std::mem::transmute(ref_idx_l1_3) }; + ref_idx_l1_3 as u64 + }); + __bindgen_bitfield_unit + } +} +impl Default for _VAEncFEIMBCodeH264__bindgen_ty_1 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl Default for _VAEncFEIMBCodeH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl _VAEncFEIMBCodeH264 { + #[inline] + pub fn inter_mb_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 2u8) as u32) } + } + #[inline] + pub fn set_inter_mb_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn inter_mb_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_inter_mb_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_skip_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_skip_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(2usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_skip_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 2usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_skip_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 2usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) } + } + #[inline] + pub fn set_reserved1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(3usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 3usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 3usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_mb_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 2u8) as u32) } + } + #[inline] + pub fn set_intra_mb_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(4usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_mb_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 4usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_mb_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 4usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) } + } + #[inline] + pub fn set_reserved2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(6usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 6usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 6usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn field_mb_polarity_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) } + } + #[inline] + pub fn set_field_mb_polarity_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(7usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn field_mb_polarity_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 7usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_field_mb_polarity_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 7usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_type(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 5u8) as u32) } + } + #[inline] + pub fn set_mb_type(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_type_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_type_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_mb_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(13usize, 1u8) as u32) } + } + #[inline] + pub fn set_intra_mb_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(13usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_mb_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 13usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_mb_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 13usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn field_mb_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(14usize, 1u8) as u32) } + } + #[inline] + pub fn set_field_mb_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(14usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn field_mb_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 14usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_field_mb_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 14usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn transform8x8_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(15usize, 1u8) as u32) } + } + #[inline] + pub fn set_transform8x8_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(15usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn transform8x8_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 15usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_transform8x8_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 15usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 1u8) as u32) } + } + #[inline] + pub fn set_reserved3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dc_block_coded_cr_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(17usize, 1u8) as u32) } + } + #[inline] + pub fn set_dc_block_coded_cr_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(17usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dc_block_coded_cr_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 17usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dc_block_coded_cr_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 17usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dc_block_coded_cb_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(18usize, 1u8) as u32) } + } + #[inline] + pub fn set_dc_block_coded_cb_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(18usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dc_block_coded_cb_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 18usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dc_block_coded_cb_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 18usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn dc_block_coded_y_flag(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(19usize, 1u8) as u32) } + } + #[inline] + pub fn set_dc_block_coded_y_flag(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(19usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn dc_block_coded_y_flag_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 19usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_dc_block_coded_y_flag_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 19usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved4(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(20usize, 12u8) as u32) } + } + #[inline] + pub fn set_reserved4(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(20usize, 12u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved4_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 20usize, + 12u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved4_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 20usize, + 12u8, + val as u64, + ) + } + } + #[inline] + pub fn horz_origin(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 8u8) as u32) } + } + #[inline] + pub fn set_horz_origin(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn horz_origin_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_horz_origin_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn vert_origin(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(40usize, 8u8) as u32) } + } + #[inline] + pub fn set_vert_origin(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(40usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn vert_origin_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 40usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_vert_origin_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 40usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn cbp_y(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_cbp_y(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn cbp_y_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cbp_y_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn cbp_cb(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 16u8) as u32) } + } + #[inline] + pub fn set_cbp_cb(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn cbp_cb_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cbp_cb_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn cbp_cr(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 16u8) as u32) } + } + #[inline] + pub fn set_cbp_cr(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn cbp_cr_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_cbp_cr_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn qp_prime_y(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 8u8) as u32) } + } + #[inline] + pub fn set_qp_prime_y(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(96usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn qp_prime_y_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 96usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_qp_prime_y_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved5(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(104usize, 17u8) as u32) } + } + #[inline] + pub fn set_reserved5(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(104usize, 17u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved5_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 104usize, + 17u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved5_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 104usize, + 17u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_skip_conv_disable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(121usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_skip_conv_disable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(121usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_skip_conv_disable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 121usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_skip_conv_disable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 121usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn is_last_mb(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(122usize, 1u8) as u32) } + } + #[inline] + pub fn set_is_last_mb(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(122usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn is_last_mb_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 122usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_is_last_mb_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 122usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_coefficient_clamp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(123usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_coefficient_clamp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(123usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_coefficient_clamp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 123usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_coefficient_clamp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 123usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn direct8x8_pattern(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(124usize, 4u8) as u32) } + } + #[inline] + pub fn set_direct8x8_pattern(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(124usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn direct8x8_pattern_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 124usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_direct8x8_pattern_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 124usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + inter_mb_mode: u32, + mb_skip_flag: u32, + reserved1: u32, + intra_mb_mode: u32, + reserved2: u32, + field_mb_polarity_flag: u32, + mb_type: u32, + intra_mb_flag: u32, + field_mb_flag: u32, + transform8x8_flag: u32, + reserved3: u32, + dc_block_coded_cr_flag: u32, + dc_block_coded_cb_flag: u32, + dc_block_coded_y_flag: u32, + reserved4: u32, + horz_origin: u32, + vert_origin: u32, + cbp_y: u32, + cbp_cb: u32, + cbp_cr: u32, + qp_prime_y: u32, + reserved5: u32, + mb_skip_conv_disable: u32, + is_last_mb: u32, + enable_coefficient_clamp: u32, + direct8x8_pattern: u32, + ) -> __BindgenBitfieldUnit<[u8; 16usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 2u8, { + let inter_mb_mode: u32 = unsafe { ::std::mem::transmute(inter_mb_mode) }; + inter_mb_mode as u64 + }); + __bindgen_bitfield_unit.set(2usize, 1u8, { + let mb_skip_flag: u32 = unsafe { ::std::mem::transmute(mb_skip_flag) }; + mb_skip_flag as u64 + }); + __bindgen_bitfield_unit.set(3usize, 1u8, { + let reserved1: u32 = unsafe { ::std::mem::transmute(reserved1) }; + reserved1 as u64 + }); + __bindgen_bitfield_unit.set(4usize, 2u8, { + let intra_mb_mode: u32 = unsafe { ::std::mem::transmute(intra_mb_mode) }; + intra_mb_mode as u64 + }); + __bindgen_bitfield_unit.set(6usize, 1u8, { + let reserved2: u32 = unsafe { ::std::mem::transmute(reserved2) }; + reserved2 as u64 + }); + __bindgen_bitfield_unit.set(7usize, 1u8, { + let field_mb_polarity_flag: u32 = unsafe { ::std::mem::transmute(field_mb_polarity_flag) }; + field_mb_polarity_flag as u64 + }); + __bindgen_bitfield_unit.set(8usize, 5u8, { + let mb_type: u32 = unsafe { ::std::mem::transmute(mb_type) }; + mb_type as u64 + }); + __bindgen_bitfield_unit.set(13usize, 1u8, { + let intra_mb_flag: u32 = unsafe { ::std::mem::transmute(intra_mb_flag) }; + intra_mb_flag as u64 + }); + __bindgen_bitfield_unit.set(14usize, 1u8, { + let field_mb_flag: u32 = unsafe { ::std::mem::transmute(field_mb_flag) }; + field_mb_flag as u64 + }); + __bindgen_bitfield_unit.set(15usize, 1u8, { + let transform8x8_flag: u32 = unsafe { ::std::mem::transmute(transform8x8_flag) }; + transform8x8_flag as u64 + }); + __bindgen_bitfield_unit.set(16usize, 1u8, { + let reserved3: u32 = unsafe { ::std::mem::transmute(reserved3) }; + reserved3 as u64 + }); + __bindgen_bitfield_unit.set(17usize, 1u8, { + let dc_block_coded_cr_flag: u32 = unsafe { ::std::mem::transmute(dc_block_coded_cr_flag) }; + dc_block_coded_cr_flag as u64 + }); + __bindgen_bitfield_unit.set(18usize, 1u8, { + let dc_block_coded_cb_flag: u32 = unsafe { ::std::mem::transmute(dc_block_coded_cb_flag) }; + dc_block_coded_cb_flag as u64 + }); + __bindgen_bitfield_unit.set(19usize, 1u8, { + let dc_block_coded_y_flag: u32 = unsafe { ::std::mem::transmute(dc_block_coded_y_flag) }; + dc_block_coded_y_flag as u64 + }); + __bindgen_bitfield_unit.set(20usize, 12u8, { + let reserved4: u32 = unsafe { ::std::mem::transmute(reserved4) }; + reserved4 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 8u8, { + let horz_origin: u32 = unsafe { ::std::mem::transmute(horz_origin) }; + horz_origin as u64 + }); + __bindgen_bitfield_unit.set(40usize, 8u8, { + let vert_origin: u32 = unsafe { ::std::mem::transmute(vert_origin) }; + vert_origin as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let cbp_y: u32 = unsafe { ::std::mem::transmute(cbp_y) }; + cbp_y as u64 + }); + __bindgen_bitfield_unit.set(64usize, 16u8, { + let cbp_cb: u32 = unsafe { ::std::mem::transmute(cbp_cb) }; + cbp_cb as u64 + }); + __bindgen_bitfield_unit.set(80usize, 16u8, { + let cbp_cr: u32 = unsafe { ::std::mem::transmute(cbp_cr) }; + cbp_cr as u64 + }); + __bindgen_bitfield_unit.set(96usize, 8u8, { + let qp_prime_y: u32 = unsafe { ::std::mem::transmute(qp_prime_y) }; + qp_prime_y as u64 + }); + __bindgen_bitfield_unit.set(104usize, 17u8, { + let reserved5: u32 = unsafe { ::std::mem::transmute(reserved5) }; + reserved5 as u64 + }); + __bindgen_bitfield_unit.set(121usize, 1u8, { + let mb_skip_conv_disable: u32 = unsafe { ::std::mem::transmute(mb_skip_conv_disable) }; + mb_skip_conv_disable as u64 + }); + __bindgen_bitfield_unit.set(122usize, 1u8, { + let is_last_mb: u32 = unsafe { ::std::mem::transmute(is_last_mb) }; + is_last_mb as u64 + }); + __bindgen_bitfield_unit.set(123usize, 1u8, { + let enable_coefficient_clamp: u32 = unsafe { ::std::mem::transmute(enable_coefficient_clamp) }; + enable_coefficient_clamp as u64 + }); + __bindgen_bitfield_unit.set(124usize, 4u8, { + let direct8x8_pattern: u32 = unsafe { ::std::mem::transmute(direct8x8_pattern) }; + direct8x8_pattern as u64 + }); + __bindgen_bitfield_unit + } + #[inline] + pub fn reserved8(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved8(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved8_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved8_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn target_size_in_word(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(16usize, 8u8) as u32) } + } + #[inline] + pub fn set_target_size_in_word(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(16usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn target_size_in_word_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 16usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_target_size_in_word_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn max_size_in_word(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(24usize, 8u8) as u32) } + } + #[inline] + pub fn set_max_size_in_word(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(24usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn max_size_in_word_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 24usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_max_size_in_word_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_2( + reserved8: u32, + target_size_in_word: u32, + max_size_in_word: u32, + ) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let reserved8: u32 = unsafe { ::std::mem::transmute(reserved8) }; + reserved8 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 8u8, { + let target_size_in_word: u32 = unsafe { ::std::mem::transmute(target_size_in_word) }; + target_size_in_word as u64 + }); + __bindgen_bitfield_unit.set(24usize, 8u8, { + let max_size_in_word: u32 = unsafe { ::std::mem::transmute(max_size_in_word) }; + max_size_in_word as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief VAEncFEIMBCodeH264 defines the data structure for VAEncFEIMBCodeBufferType per 16x16 MB block.\n it is output buffer of ENC and ENC_PAK modes, it's also input buffer of PAK mode.\n The 16x16 block is in raster scan order. Buffer size shall not be less than the number of 16x16 blocks\n multiplied by sizeof(VAEncFEIMBCodeH264). Note that, when separate ENC and PAK is enabled,\n the exact layout of this buffer is needed for PAK input. App can reuse this buffer,\n or copy to a different buffer as PAK input, reserved elements must not be modified when used as PAK input."] +pub type VAEncFEIMBCodeH264 = _VAEncFEIMBCodeH264; +#[doc = " \\brief VAEncFEIDistortionH264 defines the data structure for VAEncFEIDistortionBufferType per 16x16 MB block.\n It is output buffer of ENC and ENC_PAK modes, The 16x16 block is in raster scan order.\n Buffer size shall not be less than the number of 16x16 blocks multiple by sizeof(VAEncFEIDistortionH264)."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAEncFEIDistortionH264 { + #[doc = " \\brief Inter-prediction-distortion associated with motion vector i (co-located with subblock_4x4_i).\n Its meaning is determined by sub-shape. It must be zero if the corresponding sub-shape is not chosen."] + pub inter_distortion: [u16; 16usize], + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, + pub reserved1: [u32; 2usize], +} +impl _VAEncFEIDistortionH264 { + #[inline] + pub fn best_inter_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_best_inter_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn best_inter_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 8usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_best_inter_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 8usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn best_intra_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_best_intra_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn best_intra_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 8usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_best_intra_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 8usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn colocated_mb_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 16u8) as u32) } + } + #[inline] + pub fn set_colocated_mb_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn colocated_mb_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 8usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_colocated_mb_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 8usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 8usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 8usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + best_inter_distortion: u32, + best_intra_distortion: u32, + colocated_mb_distortion: u32, + reserved0: u32, + ) -> __BindgenBitfieldUnit<[u8; 8usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let best_inter_distortion: u32 = unsafe { ::std::mem::transmute(best_inter_distortion) }; + best_inter_distortion as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let best_intra_distortion: u32 = unsafe { ::std::mem::transmute(best_intra_distortion) }; + best_intra_distortion as u64 + }); + __bindgen_bitfield_unit.set(32usize, 16u8, { + let colocated_mb_distortion: u32 = unsafe { ::std::mem::transmute(colocated_mb_distortion) }; + colocated_mb_distortion as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief VAEncFEIDistortionH264 defines the data structure for VAEncFEIDistortionBufferType per 16x16 MB block.\n It is output buffer of ENC and ENC_PAK modes, The 16x16 block is in raster scan order.\n Buffer size shall not be less than the number of 16x16 blocks multiple by sizeof(VAEncFEIDistortionH264)."] +pub type VAEncFEIDistortionH264 = _VAEncFEIDistortionH264; +#[doc = " \\brief Motion Vector and Statistics frame level controls.\n VAStatsStatisticsParameterBufferType for H264 16x16 block"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAStatsStatisticsParameterH264 { + pub stats_params: VAStatsStatisticsParameter, + pub _bitfield_align_1: [u32; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, + pub reserved4: [u32; 2usize], +} +impl Default for _VAStatsStatisticsParameterH264 { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +impl _VAStatsStatisticsParameterH264 { + #[inline] + pub fn frame_qp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 8u8) as u32) } + } + #[inline] + pub fn set_frame_qp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn frame_qp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_frame_qp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn len_sp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(8usize, 8u8) as u32) } + } + #[inline] + pub fn set_len_sp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(8usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn len_sp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 8usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_len_sp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 8usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn search_path(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 8u8) as u32) } + } + #[inline] + pub fn set_search_path(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn search_path_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_path_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(24usize, 8u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(24usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 24usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 24usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_mb_part_mask(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 7u8) as u32) } + } + #[inline] + pub fn set_sub_mb_part_mask(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 7u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_mb_part_mask_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 7u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_mb_part_mask_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 7u8, + val as u64, + ) + } + } + #[inline] + pub fn sub_pel_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(39usize, 2u8) as u32) } + } + #[inline] + pub fn set_sub_pel_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(39usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn sub_pel_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 39usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_sub_pel_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 39usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn inter_sad(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(41usize, 2u8) as u32) } + } + #[inline] + pub fn set_inter_sad(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(41usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn inter_sad_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 41usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_inter_sad_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 41usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_sad(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(43usize, 2u8) as u32) } + } + #[inline] + pub fn set_intra_sad(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(43usize, 2u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_sad_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 43usize, + 2u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_sad_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 43usize, + 2u8, + val as u64, + ) + } + } + #[inline] + pub fn adaptive_search(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(45usize, 1u8) as u32) } + } + #[inline] + pub fn set_adaptive_search(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(45usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn adaptive_search_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 45usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_adaptive_search_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 45usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn mv_predictor_ctrl(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(46usize, 3u8) as u32) } + } + #[inline] + pub fn set_mv_predictor_ctrl(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(46usize, 3u8, val as u64) + } + } + #[inline] + pub unsafe fn mv_predictor_ctrl_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 46usize, + 3u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mv_predictor_ctrl_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 46usize, + 3u8, + val as u64, + ) + } + } + #[inline] + pub fn mb_qp(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(49usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_qp(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(49usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_qp_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 49usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_qp_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 49usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn ft_enable(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(50usize, 1u8) as u32) } + } + #[inline] + pub fn set_ft_enable(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(50usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn ft_enable_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 50usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ft_enable_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 50usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_part_mask(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(51usize, 5u8) as u32) } + } + #[inline] + pub fn set_intra_part_mask(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(51usize, 5u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_part_mask_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 51usize, + 5u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_part_mask_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 51usize, + 5u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(56usize, 8u8) as u32) } + } + #[inline] + pub fn set_reserved1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(56usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 56usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 56usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_width(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_width(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_width_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_width_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn ref_height(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(72usize, 8u8) as u32) } + } + #[inline] + pub fn set_ref_height(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(72usize, 8u8, val as u64) + } + } + #[inline] + pub unsafe fn ref_height_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 72usize, + 8u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_ref_height_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 72usize, + 8u8, + val as u64, + ) + } + } + #[inline] + pub fn search_window(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 4u8) as u32) } + } + #[inline] + pub fn set_search_window(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 4u8, val as u64) + } + } + #[inline] + pub unsafe fn search_window_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 4u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_search_window_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 4u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved2(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(84usize, 12u8) as u32) } + } + #[inline] + pub fn set_reserved2(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(84usize, 12u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved2_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 84usize, + 12u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved2_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 84usize, + 12u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_mv_output(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_mv_output(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(96usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_mv_output_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 96usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_mv_output_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn disable_statistics_output(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(97usize, 1u8) as u32) } + } + #[inline] + pub fn set_disable_statistics_output(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(97usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn disable_statistics_output_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 97usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_disable_statistics_output_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 97usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn enable_8x8_statistics(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(98usize, 1u8) as u32) } + } + #[inline] + pub fn set_enable_8x8_statistics(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(98usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn enable_8x8_statistics_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 98usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_enable_8x8_statistics_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 98usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved3(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(99usize, 29u8) as u32) } + } + #[inline] + pub fn set_reserved3(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(99usize, 29u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved3_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 99usize, + 29u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved3_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 99usize, + 29u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + frame_qp: u32, + len_sp: u32, + search_path: u32, + reserved0: u32, + sub_mb_part_mask: u32, + sub_pel_mode: u32, + inter_sad: u32, + intra_sad: u32, + adaptive_search: u32, + mv_predictor_ctrl: u32, + mb_qp: u32, + ft_enable: u32, + intra_part_mask: u32, + reserved1: u32, + ref_width: u32, + ref_height: u32, + search_window: u32, + reserved2: u32, + disable_mv_output: u32, + disable_statistics_output: u32, + enable_8x8_statistics: u32, + reserved3: u32, + ) -> __BindgenBitfieldUnit<[u8; 16usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 8u8, { + let frame_qp: u32 = unsafe { ::std::mem::transmute(frame_qp) }; + frame_qp as u64 + }); + __bindgen_bitfield_unit.set(8usize, 8u8, { + let len_sp: u32 = unsafe { ::std::mem::transmute(len_sp) }; + len_sp as u64 + }); + __bindgen_bitfield_unit.set(16usize, 8u8, { + let search_path: u32 = unsafe { ::std::mem::transmute(search_path) }; + search_path as u64 + }); + __bindgen_bitfield_unit.set(24usize, 8u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 7u8, { + let sub_mb_part_mask: u32 = unsafe { ::std::mem::transmute(sub_mb_part_mask) }; + sub_mb_part_mask as u64 + }); + __bindgen_bitfield_unit.set(39usize, 2u8, { + let sub_pel_mode: u32 = unsafe { ::std::mem::transmute(sub_pel_mode) }; + sub_pel_mode as u64 + }); + __bindgen_bitfield_unit.set(41usize, 2u8, { + let inter_sad: u32 = unsafe { ::std::mem::transmute(inter_sad) }; + inter_sad as u64 + }); + __bindgen_bitfield_unit.set(43usize, 2u8, { + let intra_sad: u32 = unsafe { ::std::mem::transmute(intra_sad) }; + intra_sad as u64 + }); + __bindgen_bitfield_unit.set(45usize, 1u8, { + let adaptive_search: u32 = unsafe { ::std::mem::transmute(adaptive_search) }; + adaptive_search as u64 + }); + __bindgen_bitfield_unit.set(46usize, 3u8, { + let mv_predictor_ctrl: u32 = unsafe { ::std::mem::transmute(mv_predictor_ctrl) }; + mv_predictor_ctrl as u64 + }); + __bindgen_bitfield_unit.set(49usize, 1u8, { + let mb_qp: u32 = unsafe { ::std::mem::transmute(mb_qp) }; + mb_qp as u64 + }); + __bindgen_bitfield_unit.set(50usize, 1u8, { + let ft_enable: u32 = unsafe { ::std::mem::transmute(ft_enable) }; + ft_enable as u64 + }); + __bindgen_bitfield_unit.set(51usize, 5u8, { + let intra_part_mask: u32 = unsafe { ::std::mem::transmute(intra_part_mask) }; + intra_part_mask as u64 + }); + __bindgen_bitfield_unit.set(56usize, 8u8, { + let reserved1: u32 = unsafe { ::std::mem::transmute(reserved1) }; + reserved1 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 8u8, { + let ref_width: u32 = unsafe { ::std::mem::transmute(ref_width) }; + ref_width as u64 + }); + __bindgen_bitfield_unit.set(72usize, 8u8, { + let ref_height: u32 = unsafe { ::std::mem::transmute(ref_height) }; + ref_height as u64 + }); + __bindgen_bitfield_unit.set(80usize, 4u8, { + let search_window: u32 = unsafe { ::std::mem::transmute(search_window) }; + search_window as u64 + }); + __bindgen_bitfield_unit.set(84usize, 12u8, { + let reserved2: u32 = unsafe { ::std::mem::transmute(reserved2) }; + reserved2 as u64 + }); + __bindgen_bitfield_unit.set(96usize, 1u8, { + let disable_mv_output: u32 = unsafe { ::std::mem::transmute(disable_mv_output) }; + disable_mv_output as u64 + }); + __bindgen_bitfield_unit.set(97usize, 1u8, { + let disable_statistics_output: u32 = unsafe { ::std::mem::transmute(disable_statistics_output) }; + disable_statistics_output as u64 + }); + __bindgen_bitfield_unit.set(98usize, 1u8, { + let enable_8x8_statistics: u32 = unsafe { ::std::mem::transmute(enable_8x8_statistics) }; + enable_8x8_statistics as u64 + }); + __bindgen_bitfield_unit.set(99usize, 29u8, { + let reserved3: u32 = unsafe { ::std::mem::transmute(reserved3) }; + reserved3 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief Motion Vector and Statistics frame level controls.\n VAStatsStatisticsParameterBufferType for H264 16x16 block"] +pub type VAStatsStatisticsParameterH264 = _VAStatsStatisticsParameterH264; +#[doc = " \\brief VAStatsStatisticsH264. H264 Statistics buffer layout for VAStatsStatisticsBufferType\n and VAStatsStatisticsBottomFieldBufferType(for interlaced only).\n Statistics output is per 16x16 block. Data structure per 16x16 block is defined below.\n The 16x16 block is in raster scan order. The buffer size shall be greater than or equal to\n the number of 16x16 blocks multiplied by sizeof(VAStatsStatisticsH264)."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAStatsStatisticsH264 { + pub _bitfield_align_1: [u16; 0], + pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, + pub sum_coef: u32, + pub _bitfield_align_2: [u32; 0], + pub _bitfield_2: __BindgenBitfieldUnit<[u8; 4usize]>, + #[doc = " \\brief DWORD 6 variance for block16x16"] + pub variance_16x16: u32, + #[doc = " \\brief DWORD 7 ~ 10, variance for block8x8"] + pub variance_8x8: [u32; 4usize], + #[doc = " \\brief DWORD 11 pixel_average for block16x16"] + pub pixel_average_16x16: u32, + #[doc = " \\brief DWORD 12 ~ 15, pixel_average for block8x8"] + pub pixel_average_8x8: [u32; 4usize], +} +impl _VAStatsStatisticsH264 { + #[inline] + pub fn best_inter_distortion0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 16u8) as u32) } + } + #[inline] + pub fn set_best_inter_distortion0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(0usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn best_inter_distortion0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 0usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_best_inter_distortion0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 0usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn inter_mode0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(16usize, 16u8) as u32) } + } + #[inline] + pub fn set_inter_mode0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(16usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn inter_mode0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 16usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_inter_mode0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 16usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn best_inter_distortion1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(32usize, 16u8) as u32) } + } + #[inline] + pub fn set_best_inter_distortion1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(32usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn best_inter_distortion1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 32usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_best_inter_distortion1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 32usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn inter_mode1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(48usize, 16u8) as u32) } + } + #[inline] + pub fn set_inter_mode1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(48usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn inter_mode1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 48usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_inter_mode1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 48usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn best_intra_distortion(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(64usize, 16u8) as u32) } + } + #[inline] + pub fn set_best_intra_distortion(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(64usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn best_intra_distortion_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 64usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_best_intra_distortion_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 64usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn intra_mode(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(80usize, 16u8) as u32) } + } + #[inline] + pub fn set_intra_mode(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(80usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn intra_mode_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 80usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_intra_mode_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 80usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn num_non_zero_coef(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(96usize, 16u8) as u32) } + } + #[inline] + pub fn set_num_non_zero_coef(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(96usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn num_non_zero_coef_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 96usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_num_non_zero_coef_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 96usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved0(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_1.get(112usize, 16u8) as u32) } + } + #[inline] + pub fn set_reserved0(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_1.set(112usize, 16u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved0_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 16usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_1), + 112usize, + 16u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved0_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 16usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_1), + 112usize, + 16u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_1( + best_inter_distortion0: u32, + inter_mode0: u32, + best_inter_distortion1: u32, + inter_mode1: u32, + best_intra_distortion: u32, + intra_mode: u32, + num_non_zero_coef: u32, + reserved0: u32, + ) -> __BindgenBitfieldUnit<[u8; 16usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 16u8, { + let best_inter_distortion0: u32 = unsafe { ::std::mem::transmute(best_inter_distortion0) }; + best_inter_distortion0 as u64 + }); + __bindgen_bitfield_unit.set(16usize, 16u8, { + let inter_mode0: u32 = unsafe { ::std::mem::transmute(inter_mode0) }; + inter_mode0 as u64 + }); + __bindgen_bitfield_unit.set(32usize, 16u8, { + let best_inter_distortion1: u32 = unsafe { ::std::mem::transmute(best_inter_distortion1) }; + best_inter_distortion1 as u64 + }); + __bindgen_bitfield_unit.set(48usize, 16u8, { + let inter_mode1: u32 = unsafe { ::std::mem::transmute(inter_mode1) }; + inter_mode1 as u64 + }); + __bindgen_bitfield_unit.set(64usize, 16u8, { + let best_intra_distortion: u32 = unsafe { ::std::mem::transmute(best_intra_distortion) }; + best_intra_distortion as u64 + }); + __bindgen_bitfield_unit.set(80usize, 16u8, { + let intra_mode: u32 = unsafe { ::std::mem::transmute(intra_mode) }; + intra_mode as u64 + }); + __bindgen_bitfield_unit.set(96usize, 16u8, { + let num_non_zero_coef: u32 = unsafe { ::std::mem::transmute(num_non_zero_coef) }; + num_non_zero_coef as u64 + }); + __bindgen_bitfield_unit.set(112usize, 16u8, { + let reserved0: u32 = unsafe { ::std::mem::transmute(reserved0) }; + reserved0 as u64 + }); + __bindgen_bitfield_unit + } + #[inline] + pub fn mb_is_flat(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(0usize, 1u8) as u32) } + } + #[inline] + pub fn set_mb_is_flat(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(0usize, 1u8, val as u64) + } + } + #[inline] + pub unsafe fn mb_is_flat_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 0usize, + 1u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_mb_is_flat_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 0usize, + 1u8, + val as u64, + ) + } + } + #[inline] + pub fn reserved1(&self) -> u32 { + unsafe { ::std::mem::transmute(self._bitfield_2.get(1usize, 31u8) as u32) } + } + #[inline] + pub fn set_reserved1(&mut self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + self._bitfield_2.set(1usize, 31u8, val as u64) + } + } + #[inline] + pub unsafe fn reserved1_raw(this: *const Self) -> u32 { + unsafe { + ::std::mem::transmute(<__BindgenBitfieldUnit<[u8; 4usize]>>::raw_get( + ::std::ptr::addr_of!((*this)._bitfield_2), + 1usize, + 31u8, + ) as u32) + } + } + #[inline] + pub unsafe fn set_reserved1_raw(this: *mut Self, val: u32) { + unsafe { + let val: u32 = ::std::mem::transmute(val); + <__BindgenBitfieldUnit<[u8; 4usize]>>::raw_set( + ::std::ptr::addr_of_mut!((*this)._bitfield_2), + 1usize, + 31u8, + val as u64, + ) + } + } + #[inline] + pub fn new_bitfield_2(mb_is_flat: u32, reserved1: u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { + let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); + __bindgen_bitfield_unit.set(0usize, 1u8, { + let mb_is_flat: u32 = unsafe { ::std::mem::transmute(mb_is_flat) }; + mb_is_flat as u64 + }); + __bindgen_bitfield_unit.set(1usize, 31u8, { + let reserved1: u32 = unsafe { ::std::mem::transmute(reserved1) }; + reserved1 as u64 + }); + __bindgen_bitfield_unit + } +} +#[doc = " \\brief VAStatsStatisticsH264. H264 Statistics buffer layout for VAStatsStatisticsBufferType\n and VAStatsStatisticsBottomFieldBufferType(for interlaced only).\n Statistics output is per 16x16 block. Data structure per 16x16 block is defined below.\n The 16x16 block is in raster scan order. The buffer size shall be greater than or equal to\n the number of 16x16 blocks multiplied by sizeof(VAStatsStatisticsH264)."] +pub type VAStatsStatisticsH264 = _VAStatsStatisticsH264; +pub const _VAProcFilterType_VAProcFilterNone: _VAProcFilterType = 0; +#[doc = " \\brief Noise reduction filter."] +pub const _VAProcFilterType_VAProcFilterNoiseReduction: _VAProcFilterType = 1; +#[doc = " \\brief Deinterlacing filter."] +pub const _VAProcFilterType_VAProcFilterDeinterlacing: _VAProcFilterType = 2; +#[doc = " \\brief Sharpening filter."] +pub const _VAProcFilterType_VAProcFilterSharpening: _VAProcFilterType = 3; +#[doc = " \\brief Color balance parameters."] +pub const _VAProcFilterType_VAProcFilterColorBalance: _VAProcFilterType = 4; +#[doc = " \\brief Skin Tone Enhancement."] +pub const _VAProcFilterType_VAProcFilterSkinToneEnhancement: _VAProcFilterType = 5; +#[doc = " \\brief Total Color Correction."] +pub const _VAProcFilterType_VAProcFilterTotalColorCorrection: _VAProcFilterType = 6; +#[doc = " \\brief Human Vision System(HVS) Noise reduction filter."] +pub const _VAProcFilterType_VAProcFilterHVSNoiseReduction: _VAProcFilterType = 7; +#[doc = " \\brief High Dynamic Range Tone Mapping."] +pub const _VAProcFilterType_VAProcFilterHighDynamicRangeToneMapping: _VAProcFilterType = 8; +#[doc = " \\brief Three-Dimensional Look Up Table (3DLUT)."] +pub const _VAProcFilterType_VAProcFilter3DLUT: _VAProcFilterType = 9; +#[doc = " \\brief Number of video filters."] +pub const _VAProcFilterType_VAProcFilterCount: _VAProcFilterType = 10; +#[doc = " \\brief Video filter types."] +pub type _VAProcFilterType = ::std::os::raw::c_uint; +#[doc = " \\brief Video filter types."] +pub use self::_VAProcFilterType as VAProcFilterType; +pub const _VAProcDeinterlacingType_VAProcDeinterlacingNone: _VAProcDeinterlacingType = 0; +#[doc = " \\brief Bob deinterlacing algorithm."] +pub const _VAProcDeinterlacingType_VAProcDeinterlacingBob: _VAProcDeinterlacingType = 1; +#[doc = " \\brief Weave deinterlacing algorithm."] +pub const _VAProcDeinterlacingType_VAProcDeinterlacingWeave: _VAProcDeinterlacingType = 2; +#[doc = " \\brief Motion adaptive deinterlacing algorithm."] +pub const _VAProcDeinterlacingType_VAProcDeinterlacingMotionAdaptive: _VAProcDeinterlacingType = 3; +#[doc = " \\brief Motion compensated deinterlacing algorithm."] +pub const _VAProcDeinterlacingType_VAProcDeinterlacingMotionCompensated: _VAProcDeinterlacingType = 4; +#[doc = " \\brief Number of deinterlacing algorithms."] +pub const _VAProcDeinterlacingType_VAProcDeinterlacingCount: _VAProcDeinterlacingType = 5; +#[doc = " \\brief Deinterlacing types."] +pub type _VAProcDeinterlacingType = ::std::os::raw::c_uint; +#[doc = " \\brief Deinterlacing types."] +pub use self::_VAProcDeinterlacingType as VAProcDeinterlacingType; +pub const _VAProcColorBalanceType_VAProcColorBalanceNone: _VAProcColorBalanceType = 0; +#[doc = " \\brief Hue."] +pub const _VAProcColorBalanceType_VAProcColorBalanceHue: _VAProcColorBalanceType = 1; +#[doc = " \\brief Saturation."] +pub const _VAProcColorBalanceType_VAProcColorBalanceSaturation: _VAProcColorBalanceType = 2; +#[doc = " \\brief Brightness."] +pub const _VAProcColorBalanceType_VAProcColorBalanceBrightness: _VAProcColorBalanceType = 3; +#[doc = " \\brief Contrast."] +pub const _VAProcColorBalanceType_VAProcColorBalanceContrast: _VAProcColorBalanceType = 4; +#[doc = " \\brief Automatically adjusted saturation."] +pub const _VAProcColorBalanceType_VAProcColorBalanceAutoSaturation: _VAProcColorBalanceType = 5; +#[doc = " \\brief Automatically adjusted brightness."] +pub const _VAProcColorBalanceType_VAProcColorBalanceAutoBrightness: _VAProcColorBalanceType = 6; +#[doc = " \\brief Automatically adjusted contrast."] +pub const _VAProcColorBalanceType_VAProcColorBalanceAutoContrast: _VAProcColorBalanceType = 7; +#[doc = " \\brief Number of color balance attributes."] +pub const _VAProcColorBalanceType_VAProcColorBalanceCount: _VAProcColorBalanceType = 8; +#[doc = " \\brief Color balance types."] +pub type _VAProcColorBalanceType = ::std::os::raw::c_uint; +#[doc = " \\brief Color balance types."] +pub use self::_VAProcColorBalanceType as VAProcColorBalanceType; +pub const _VAProcColorStandardType_VAProcColorStandardNone: _VAProcColorStandardType = 0; +#[doc = " \\brief ITU-R BT.601.\n\n It is unspecified whether this will use 525-line or 625-line values;\n specify the colour primaries and matrix coefficients explicitly if\n it is known which one is required.\n\n Equivalent to:\n colour_primaries = 5 or 6\n transfer_characteristics = 6\n matrix_coefficients = 5 or 6"] +pub const _VAProcColorStandardType_VAProcColorStandardBT601: _VAProcColorStandardType = 1; +#[doc = " \\brief ITU-R BT.709.\n\n Equivalent to:\n colour_primaries = 1\n transfer_characteristics = 1\n matrix_coefficients = 1"] +pub const _VAProcColorStandardType_VAProcColorStandardBT709: _VAProcColorStandardType = 2; +#[doc = " \\brief ITU-R BT.470-2 System M.\n\n Equivalent to:\n colour_primaries = 4\n transfer_characteristics = 4\n matrix_coefficients = 4"] +pub const _VAProcColorStandardType_VAProcColorStandardBT470M: _VAProcColorStandardType = 3; +#[doc = " \\brief ITU-R BT.470-2 System B, G.\n\n Equivalent to:\n colour_primaries = 5\n transfer_characteristics = 5\n matrix_coefficients = 5"] +pub const _VAProcColorStandardType_VAProcColorStandardBT470BG: _VAProcColorStandardType = 4; +#[doc = " \\brief SMPTE-170M.\n\n Equivalent to:\n colour_primaries = 6\n transfer_characteristics = 6\n matrix_coefficients = 6"] +pub const _VAProcColorStandardType_VAProcColorStandardSMPTE170M: _VAProcColorStandardType = 5; +#[doc = " \\brief SMPTE-240M.\n\n Equivalent to:\n colour_primaries = 7\n transfer_characteristics = 7\n matrix_coefficients = 7"] +pub const _VAProcColorStandardType_VAProcColorStandardSMPTE240M: _VAProcColorStandardType = 6; +#[doc = " \\brief Generic film.\n\n Equivalent to:\n colour_primaries = 8\n transfer_characteristics = 1\n matrix_coefficients = 1"] +pub const _VAProcColorStandardType_VAProcColorStandardGenericFilm: _VAProcColorStandardType = 7; +#[doc = " \\brief sRGB.\n\n Equivalent to:\n colour_primaries = 1\n transfer_characteristics = 13\n matrix_coefficients = 0"] +pub const _VAProcColorStandardType_VAProcColorStandardSRGB: _VAProcColorStandardType = 8; +#[doc = " \\brief stRGB.\n\n ???"] +pub const _VAProcColorStandardType_VAProcColorStandardSTRGB: _VAProcColorStandardType = 9; +#[doc = " \\brief xvYCC601.\n\n Equivalent to:\n colour_primaries = 1\n transfer_characteristics = 11\n matrix_coefficients = 5"] +pub const _VAProcColorStandardType_VAProcColorStandardXVYCC601: _VAProcColorStandardType = 10; +#[doc = " \\brief xvYCC709.\n\n Equivalent to:\n colour_primaries = 1\n transfer_characteristics = 11\n matrix_coefficients = 1"] +pub const _VAProcColorStandardType_VAProcColorStandardXVYCC709: _VAProcColorStandardType = 11; +#[doc = " \\brief ITU-R BT.2020.\n\n Equivalent to:\n colour_primaries = 9\n transfer_characteristics = 14\n matrix_coefficients = 9"] +pub const _VAProcColorStandardType_VAProcColorStandardBT2020: _VAProcColorStandardType = 12; +#[doc = " \\brief Explicitly specified color properties.\n\n Use corresponding color properties section.\n For example, HDR10 content:\n colour_primaries = 9 (BT2020)\n transfer_characteristics = 16 (SMPTE ST2084)\n matrix_coefficients = 9"] +pub const _VAProcColorStandardType_VAProcColorStandardExplicit: _VAProcColorStandardType = 13; +#[doc = " \\brief Number of color standards."] +pub const _VAProcColorStandardType_VAProcColorStandardCount: _VAProcColorStandardType = 14; +#[doc = " \\brief Color standard types.\n\n These define a set of color properties corresponding to particular\n video standards.\n\n Where matrix_coefficients is specified, it applies only to YUV data -\n RGB data always use the identity matrix (matrix_coefficients = 0)."] +pub type _VAProcColorStandardType = ::std::os::raw::c_uint; +#[doc = " \\brief Color standard types.\n\n These define a set of color properties corresponding to particular\n video standards.\n\n Where matrix_coefficients is specified, it applies only to YUV data -\n RGB data always use the identity matrix (matrix_coefficients = 0)."] +pub use self::_VAProcColorStandardType as VAProcColorStandardType; +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionNone: _VAProcTotalColorCorrectionType = 0; +#[doc = " \\brief Red Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionRed: _VAProcTotalColorCorrectionType = 1; +#[doc = " \\brief Green Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionGreen: _VAProcTotalColorCorrectionType = 2; +#[doc = " \\brief Blue Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionBlue: _VAProcTotalColorCorrectionType = 3; +#[doc = " \\brief Cyan Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionCyan: _VAProcTotalColorCorrectionType = 4; +#[doc = " \\brief Magenta Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionMagenta: _VAProcTotalColorCorrectionType = 5; +#[doc = " \\brief Yellow Saturation."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionYellow: _VAProcTotalColorCorrectionType = 6; +#[doc = " \\brief Number of color correction attributes."] +pub const _VAProcTotalColorCorrectionType_VAProcTotalColorCorrectionCount: _VAProcTotalColorCorrectionType = 7; +#[doc = " \\brief Total color correction types."] +pub type _VAProcTotalColorCorrectionType = ::std::os::raw::c_uint; +#[doc = " \\brief Total color correction types."] +pub use self::_VAProcTotalColorCorrectionType as VAProcTotalColorCorrectionType; +pub const _VAProcHighDynamicRangeMetadataType_VAProcHighDynamicRangeMetadataNone: _VAProcHighDynamicRangeMetadataType = + 0; +#[doc = " \\brief Metadata type for HDR10."] +pub const _VAProcHighDynamicRangeMetadataType_VAProcHighDynamicRangeMetadataHDR10: _VAProcHighDynamicRangeMetadataType = + 1; +#[doc = " \\brief Number of Metadata type."] +pub const _VAProcHighDynamicRangeMetadataType_VAProcHighDynamicRangeMetadataTypeCount: + _VAProcHighDynamicRangeMetadataType = 2; +#[doc = " \\brief High Dynamic Range Metadata types."] +pub type _VAProcHighDynamicRangeMetadataType = ::std::os::raw::c_uint; +#[doc = " \\brief High Dynamic Range Metadata types."] +pub use self::_VAProcHighDynamicRangeMetadataType as VAProcHighDynamicRangeMetadataType; +#[doc = " \\brief Default Mode.\n In this mode, pipeline is decided in driver to the appropriate mode.\n e.g. a mode that's a balance between power and performance."] +pub const _VAProcMode_VAProcDefaultMode: _VAProcMode = 0; +#[doc = " \\brief Power Saving Mode.\n In this mode, pipeline is optimized for power saving."] +pub const _VAProcMode_VAProcPowerSavingMode: _VAProcMode = 1; +#[doc = " \\brief Performance Mode.\n In this mode, pipeline is optimized for performance."] +pub const _VAProcMode_VAProcPerformanceMode: _VAProcMode = 2; +#[doc = " \\brief Video Processing Mode."] +pub type _VAProcMode = ::std::os::raw::c_uint; +#[doc = " \\brief Video Processing Mode."] +pub use self::_VAProcMode as VAProcMode; +#[doc = " \\brief Video blending state definition."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq)] +pub struct _VABlendState { + #[doc = " \\brief Video blending flags."] + pub flags: ::std::os::raw::c_uint, + #[doc = " \\brief Global alpha value.\n\n Valid if \\ref flags has VA_BLEND_GLOBAL_ALPHA.\n Valid range is 0.0 to 1.0 inclusive."] + pub global_alpha: f32, + #[doc = " \\brief Minimum luma value.\n\n Valid if \\ref flags has VA_BLEND_LUMA_KEY.\n Valid range is 0.0 to 1.0 inclusive.\n \\ref min_luma shall be set to a sensible value lower than \\ref max_luma."] + pub min_luma: f32, + #[doc = " \\brief Maximum luma value.\n\n Valid if \\ref flags has VA_BLEND_LUMA_KEY.\n Valid range is 0.0 to 1.0 inclusive.\n \\ref max_luma shall be set to a sensible value larger than \\ref min_luma."] + pub max_luma: f32, +} +#[doc = " \\brief Video blending state definition."] +pub type VABlendState = _VABlendState; +#[doc = " \\brief Video processing pipeline capabilities."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcPipelineCaps { + #[doc = " \\brief Pipeline flags. See VAProcPipelineParameterBuffer::pipeline_flags."] + pub pipeline_flags: u32, + #[doc = " \\brief Extra filter flags. See VAProcPipelineParameterBuffer::filter_flags."] + pub filter_flags: u32, + #[doc = " \\brief Number of forward reference frames that are needed."] + pub num_forward_references: u32, + #[doc = " \\brief Number of backward reference frames that are needed."] + pub num_backward_references: u32, + #[doc = " \\brief List of color standards supported on input."] + pub input_color_standards: *mut VAProcColorStandardType, + #[doc = " \\brief Number of elements in \\ref input_color_standards array."] + pub num_input_color_standards: u32, + #[doc = " \\brief List of color standards supported on output."] + pub output_color_standards: *mut VAProcColorStandardType, + #[doc = " \\brief Number of elements in \\ref output_color_standards array."] + pub num_output_color_standards: u32, + #[doc = " \\brief Rotation flags.\n\n For each rotation angle supported by the underlying hardware,\n the corresponding bit is set in \\ref rotation_flags. See\n \"Rotation angles\" for a description of rotation angles.\n\n A value of 0 means the underlying hardware does not support any\n rotation. Otherwise, a check for a specific rotation angle can be\n performed as follows:\n\n \\code\n VAProcPipelineCaps pipeline_caps;\n ...\n vaQueryVideoProcPipelineCaps(va_dpy, vpp_ctx,\n filter_bufs, num_filter_bufs,\n &pipeline_caps\n );\n ...\n if (pipeline_caps.rotation_flags & (1 << VA_ROTATION_xxx)) {\n // Clockwise rotation by xxx degrees is supported\n ...\n }\n \\endcode"] + pub rotation_flags: u32, + #[doc = " \\brief Blend flags. See \"Video blending flags\"."] + pub blend_flags: u32, + #[doc = " \\brief Mirroring flags.\n\n For each mirroring direction supported by the underlying hardware,\n the corresponding bit is set in \\ref mirror_flags. See\n \"Mirroring directions\" for a description of mirroring directions.\n"] + pub mirror_flags: u32, + #[doc = " \\brief Number of additional output surfaces supported by the pipeline"] + pub num_additional_outputs: u32, + #[doc = " \\brief Number of elements in \\ref input_pixel_format array."] + pub num_input_pixel_formats: u32, + #[doc = " \\brief List of input pixel formats in fourcc."] + pub input_pixel_format: *mut u32, + #[doc = " \\brief Number of elements in \\ref output_pixel_format array."] + pub num_output_pixel_formats: u32, + #[doc = " \\brief List of output pixel formats in fourcc."] + pub output_pixel_format: *mut u32, + #[doc = " \\brief Max supported input width in pixels."] + pub max_input_width: u32, + #[doc = " \\brief Max supported input height in pixels."] + pub max_input_height: u32, + #[doc = " \\brief Min supported input width in pixels."] + pub min_input_width: u32, + #[doc = " \\brief Min supported input height in pixels."] + pub min_input_height: u32, + #[doc = " \\brief Max supported output width in pixels."] + pub max_output_width: u32, + #[doc = " \\brief Max supported output height in pixels."] + pub max_output_height: u32, + #[doc = " \\brief Min supported output width in pixels."] + pub min_output_width: u32, + #[doc = " \\brief Min supported output height in pixels."] + pub min_output_height: u32, + #[cfg(any(target_arch = "x86_64", all(target_pointer_width = "64", not(windows))))] + pub va_reserved: [u32; 14usize], + #[cfg(not(any(target_arch = "x86_64", all(target_pointer_width = "64", not(windows)))))] + pub va_reserved: [u32; 16usize], +} +impl Default for _VAProcPipelineCaps { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Video processing pipeline capabilities."] +pub type VAProcPipelineCaps = _VAProcPipelineCaps; +#[doc = " \\brief Specification of values supported by the filter."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq)] +pub struct _VAProcFilterValueRange { + #[doc = " \\brief Minimum value supported, inclusive."] + pub min_value: f32, + #[doc = " \\brief Maximum value supported, inclusive."] + pub max_value: f32, + #[doc = " \\brief Default value."] + pub default_value: f32, + #[doc = " \\brief Step value that alters the filter behaviour in a sensible way."] + pub step: f32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Specification of values supported by the filter."] +pub type VAProcFilterValueRange = _VAProcFilterValueRange; +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcColorProperties { + #[doc = " Chroma sample location.\\c VA_CHROMA_SITING_VERTICAL_XXX | VA_CHROMA_SITING_HORIZONTAL_XXX"] + pub chroma_sample_location: u8, + #[doc = " Color range. \\c VA_SOURCE_RANGE_XXX"] + pub color_range: u8, + #[doc = " Colour primaries.\n\n See ISO/IEC 23001-8 or ITU H.273, section 8.1 and table 2.\n Only used if the color standard in use is \\c VAColorStandardExplicit.\n Below list the typical colour primaries for the reference.\n ---------------------------------------------------------------------------------\n | Value | Primaries | Informative Remark |\n --------------------------------------------------------------------------------\n | 1 |primary x y |Rec.ITU-R BT.709-5 |\n | |green 0.300 0.600 |IEC 61966-2-1(sRGB or sYCC) |\n | |blue 0.150 0.060 | |\n | |red 0.640 0.330 | |\n | |whiteD65 0.3127 0.3290 | |\n ---------------------------------------------------------------------------------\n | 6 |primary x y |Rec.ITU-R BT.601-6 525 |\n | |green 0.310 0.595 | |\n | |blue 0.155 0.070 | |\n | |red 0.630 0.340 | |\n | |whiteD65 0.3127 0.3290 | |\n ---------------------------------------------------------------------------------\n | 9 |primary x y |Rec.ITU-R BT.2020 |\n | |green 0.170 0.797 | |\n | |blue 0.131 0.046 | |\n | |red 0.708 0.292 | |\n | |whiteD65 0.3127 0.3290 | |\n ---------------------------------------------------------------------------------"] + pub colour_primaries: u8, + #[doc = " Transfer characteristics.\n\n See ISO/IEC 23001-8 or ITU H.273, section 8.2 and table 3.\n Only used if the color standard in use is \\c VAColorStandardExplicit.\n Below list the typical transfer characteristics for the reference.\n -----------------------------------------------------------\n | Value | Informative Remark |\n -----------------------------------------------------------\n | 1 |Rec.ITU-R BT.709-5 |\n | |colour gamut system |\n -----------------------------------------------------------\n | 4 |Assumed display gamma 2.2 |\n -----------------------------------------------------------\n | 6 |Rec.ITU-R BT.601-6 525 or 625 |\n -----------------------------------------------------------\n | 8 |Linear transfer characteristics |\n -----------------------------------------------------------\n | 13 |IEC 61966-2-1(sRGB or sYCC) |\n -----------------------------------------------------------\n | 14,15 |Rec.ITU-R BT.2020 |\n -----------------------------------------------------------\n | 16 |SMPTE ST 2084 for 10,12,14 and 16bit system |\n -----------------------------------------------------------"] + pub transfer_characteristics: u8, + #[doc = " Matrix coefficients.\n\n See ISO/IEC 23001-8 or ITU H.273, section 8.3 and table 4.\n Only used if the color standard in use is \\c VAColorStandardExplicit."] + pub matrix_coefficients: u8, + #[doc = " Reserved bytes for future use, must be zero."] + pub reserved: [u8; 3usize], +} +pub type VAProcColorProperties = _VAProcColorProperties; +#[doc = " \\brief Capabilities specification for the High Dynamic Range filter."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterCapHighDynamicRange { + #[doc = " \\brief high dynamic range type."] + pub metadata_type: VAProcHighDynamicRangeMetadataType, + #[doc = " \\brief flag for high dynamic range tone mapping\n\n The flag is the combination of VA_TONE_MAPPING_XXX_TO_XXX.\n It could be VA_TONE_MAPPING_HDR_TO_HDR | VA_TONE_MAPPING_HDR_TO_SDR.\n SDR content to SDR display is always supported by default since it is legacy path."] + pub caps_flag: u16, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u16; 16usize], +} +impl Default for _VAProcFilterCapHighDynamicRange { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Capabilities specification for the High Dynamic Range filter."] +pub type VAProcFilterCapHighDynamicRange = _VAProcFilterCapHighDynamicRange; +#[doc = " \\brief High Dynamic Range Meta Data."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAHdrMetaData { + #[doc = " \\brief high dynamic range metadata type, HDR10 etc."] + pub metadata_type: VAProcHighDynamicRangeMetadataType, + #[doc = " \\brief Pointer to high dynamic range metadata.\n\n The pointer could point to VAHdrMetaDataHDR10 or other HDR meta data."] + pub metadata: *mut ::std::os::raw::c_void, + #[doc = " \\brief Size of high dynamic range metadata."] + pub metadata_size: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub reserved: [u32; 4usize], +} +impl Default for _VAHdrMetaData { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief High Dynamic Range Meta Data."] +pub type VAHdrMetaData = _VAHdrMetaData; +#[doc = " \\brief Video processing pipeline configuration.\n\n This buffer defines a video processing pipeline. The actual filters to\n be applied are provided in the \\c filters field, they can be re-used\n in other processing pipelines.\n\n The target surface is specified by the \\c render_target argument of\n \\c vaBeginPicture(). The general usage model is described as follows:\n - \\c vaBeginPicture(): specify the target surface that receives the\n processed output;\n - \\c vaRenderPicture(): specify a surface to be processed and composed\n into the \\c render_target. Use as many \\c vaRenderPicture() calls as\n necessary surfaces to compose ;\n - \\c vaEndPicture(): tell the driver to start processing the surfaces\n with the requested filters.\n\n If a filter (e.g. noise reduction) needs to be applied with different\n values for multiple surfaces, the application needs to create as many\n filter parameter buffers as necessary. i.e. the filter parameters shall\n not change between two calls to \\c vaRenderPicture().\n\n For composition usage models, the first surface to process will generally\n use an opaque background color, i.e. \\c output_background_color set with\n the most significant byte set to \\c 0xff. For instance, \\c 0xff000000 for\n a black background. Then, subsequent surfaces would use a transparent\n background color."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcPipelineParameterBuffer { + #[doc = " \\brief Source surface ID.\n\n ID of the source surface to process. If subpictures are associated\n with the video surfaces then they shall be rendered to the target\n surface, if the #VA_PROC_PIPELINE_SUBPICTURES pipeline flag is set."] + pub surface: VASurfaceID, + #[doc = " \\brief Region within the source surface to be processed.\n\n Pointer to a #VARectangle defining the region within the source\n surface to be processed. If NULL, \\c surface_region implies the\n whole surface."] + pub surface_region: *const VARectangle, + #[doc = " \\brief Requested input color standard.\n\n Color properties are implicitly converted throughout the processing\n pipeline. The video processor chooses the best moment to apply\n this conversion. The set of supported color standards for input shall\n be queried with vaQueryVideoProcPipelineCaps().\n\n If this is set to VAProcColorStandardExplicit, the color properties\n are specified explicitly in input_color_properties instead."] + pub surface_color_standard: VAProcColorStandardType, + #[doc = " \\brief Region within the output surface.\n\n Pointer to a #VARectangle defining the region within the output\n surface that receives the processed pixels. If NULL, \\c output_region\n implies the whole surface.\n\n Note that any pixels residing outside the specified region will\n be filled in with the \\ref output_background_color."] + pub output_region: *const VARectangle, + #[doc = " \\brief Background color.\n\n Background color used to fill in pixels that reside outside of the\n specified \\ref output_region. The color is specified in ARGB format:\n [31:24] alpha, [23:16] red, [15:8] green, [7:0] blue.\n\n Unless the alpha value is zero or the \\ref output_region represents\n the whole target surface size, implementations shall not render the\n source surface to the target surface directly. Rather, in order to\n maintain the exact semantics of \\ref output_background_color, the\n driver shall use a temporary surface and fill it in with the\n appropriate background color. Next, the driver will blend this\n temporary surface into the target surface."] + pub output_background_color: u32, + #[doc = " \\brief Requested output color standard.\n\n If this is set to VAProcColorStandardExplicit, the color properties\n are specified explicitly in output_color_properties instead."] + pub output_color_standard: VAProcColorStandardType, + #[doc = " \\brief Pipeline filters. See video pipeline flags.\n\n Flags to control the pipeline, like whether to apply subpictures\n or not, notify the driver that it can opt for power optimizations,\n should this be needed."] + pub pipeline_flags: u32, + #[doc = " \\brief Extra filter flags. See vaPutSurface() flags.\n\n Filter flags are used as a fast path, wherever possible, to use\n vaPutSurface() flags instead of explicit filter parameter buffers.\n\n Allowed filter flags API-wise. Use vaQueryVideoProcPipelineCaps()\n to check for implementation details:\n - Bob-deinterlacing: \\c VA_FRAME_PICTURE, \\c VA_TOP_FIELD,\n \\c VA_BOTTOM_FIELD. Note that any deinterlacing filter\n (#VAProcFilterDeinterlacing) will override those flags.\n - Color space conversion: \\c VA_SRC_BT601, \\c VA_SRC_BT709,\n \\c VA_SRC_SMPTE_240.\n - Scaling: \\c VA_FILTER_SCALING_DEFAULT, \\c VA_FILTER_SCALING_FAST,\n \\c VA_FILTER_SCALING_HQ, \\c VA_FILTER_SCALING_NL_ANAMORPHIC.\n - Interpolation Method: \\c VA_FILTER_INTERPOLATION_DEFAULT,\n \\c VA_FILTER_INTERPOLATION_NEAREST_NEIGHBOR,\n \\c VA_FILTER_INTERPOLATION_BILINEAR, \\c VA_FILTER_INTERPOLATION_ADVANCED."] + pub filter_flags: u32, + #[doc = " \\brief Array of filters to apply to the surface.\n\n The list of filters shall be ordered in the same way the driver expects\n them. i.e. as was returned from vaQueryVideoProcFilters().\n Otherwise, a #VA_STATUS_ERROR_INVALID_FILTER_CHAIN is returned\n from vaRenderPicture() with this buffer.\n\n #VA_STATUS_ERROR_UNSUPPORTED_FILTER is returned if the list\n contains an unsupported filter.\n"] + pub filters: *mut VABufferID, + #[doc = " \\brief Actual number of filters."] + pub num_filters: u32, + #[doc = " \\brief Array of forward reference frames (past frames)."] + pub forward_references: *mut VASurfaceID, + #[doc = " \\brief Number of forward reference frames that were supplied."] + pub num_forward_references: u32, + #[doc = " \\brief Array of backward reference frames (future frames)."] + pub backward_references: *mut VASurfaceID, + #[doc = " \\brief Number of backward reference frames that were supplied."] + pub num_backward_references: u32, + #[doc = " \\brief Rotation state. See rotation angles.\n\n The rotation angle is clockwise. There is no specific rotation\n center for this operation. Rather, The source \\ref surface is\n first rotated by the specified angle and then scaled to fit the\n \\ref output_region.\n\n This means that the top-left hand corner (0,0) of the output\n (rotated) surface is expressed as follows:\n - \\ref VA_ROTATION_NONE: (0,0) is the top left corner of the\n source surface -- no rotation is performed ;\n - \\ref VA_ROTATION_90: (0,0) is the bottom-left corner of the\n source surface ;\n - \\ref VA_ROTATION_180: (0,0) is the bottom-right corner of the\n source surface -- the surface is flipped around the X axis ;\n - \\ref VA_ROTATION_270: (0,0) is the top-right corner of the\n source surface.\n\n Check VAProcPipelineCaps::rotation_flags first prior to\n defining a specific rotation angle. Otherwise, the hardware can\n perfectly ignore this variable if it does not support any\n rotation."] + pub rotation_state: u32, + #[doc = " \\brief blending state. See \"Video blending state definition\".\n\n If \\ref blend_state is NULL, then default operation mode depends\n on the source \\ref surface format:\n - RGB: per-pixel alpha blending ;\n - YUV: no blending, i.e override the underlying pixels.\n\n Otherwise, \\ref blend_state is a pointer to a #VABlendState\n structure that shall be live until vaEndPicture().\n\n Implementation note: the driver is responsible for checking the\n blend state flags against the actual source \\ref surface format.\n e.g. premultiplied alpha blending is only applicable to RGB\n surfaces, and luma keying is only applicable to YUV surfaces.\n If a mismatch occurs, then #VA_STATUS_ERROR_INVALID_BLEND_STATE\n is returned."] + pub blend_state: *const VABlendState, + #[doc = " \\brief mirroring state. See \"Mirroring directions\".\n\n Mirroring of an image can be performed either along the\n horizontal or vertical axis. It is assumed that the rotation\n operation is always performed before the mirroring operation."] + pub mirror_state: u32, + #[doc = " \\brief Array of additional output surfaces."] + pub additional_outputs: *mut VASurfaceID, + #[doc = " \\brief Number of additional output surfaces."] + pub num_additional_outputs: u32, + #[doc = " \\brief Flag to indicate the input surface flag\n\n bit0~3: Surface sample type\n - 0000: Progressive --> VA_FRAME_PICTURE\n - 0001: Single Top Field --> VA_TOP_FIELD\n - 0010: Single Bottom Field --> VA_BOTTOM_FIELD\n - 0100: Interleaved Top Field First --> VA_TOP_FIELD_FIRST\n - 1000: Interleaved Bottom Field First --> VA_BOTTOM_FIELD_FIRST\n\n For interlaced scaling, examples as follow:\n - 1. Interleaved to Interleaved (Suppose input is top field first)\n -- set input_surface_flag as VA_TOP_FIELD_FIRST\n -- set output_surface_flag as VA_TOP_FIELD_FIRST\n - 2. Interleaved to Field (Suppose input is top field first)\n An interleaved frame need to be passed twice.\n First cycle to get the first field:\n -- set input_surface_flag as VA_TOP_FIELD_FIRST\n -- set output_surface_flag as VA_TOP_FIELD\n Second cycle to get the second field:\n -- set input_surface_flag as VA_TOP_FIELD_FIRST\n -- set output_surface_flag as VA_BOTTOM_FIELD\n - 3. Field to Interleaved (Suppose first field is top field)\n -- create two surfaces, one for top field, the other for bottom field\n -- set surface with the first field surface id\n -- set backward_reference with the second field surface id\n -- set input_surface_flag as VA_TOP_FIELD\n -- set output_surface_flag as VA_TOP_FIELD_FIRST\n - 4. Field to Field:\n -- set flag according to each frame.\n\n bit31: Surface encryption\n - 0: non-protected\n - 1: protected\n\n bit4~30 for future"] + pub input_surface_flag: u32, + #[doc = " \\brief Flag to indicate the output surface flag\n\n bit0~3: Surface sample type\n - 0000: Progressive --> VA_FRAME_PICTURE\n - 0001: Top Field --> VA_TOP_FIELD\n - 0010: Bottom Field --> VA_BOTTOM_FIELD\n - 0100: Top Field First --> VA_TOP_FIELD_FIRST\n - 1000: Bottom Field First --> VA_BOTTOM_FIELD_FIRST\n\n bit31: Surface encryption\n - 0: non-protected\n - 1: protected\n\n bit4~30 for future"] + pub output_surface_flag: u32, + #[doc = " \\brief Input Color Properties. See \"VAProcColorProperties\"."] + pub input_color_properties: VAProcColorProperties, + #[doc = " \\brief Output Color Properties. See \"VAProcColorProperties\"."] + pub output_color_properties: VAProcColorProperties, + #[doc = " \\brief Processing mode. See \"VAProcMode\"."] + pub processing_mode: VAProcMode, + #[doc = " \\brief Output High Dynamic Metadata.\n\n If output_metadata is NULL, then output default to SDR."] + pub output_hdr_metadata: *mut VAHdrMetaData, + #[cfg(any(target_arch = "x86_64", all(target_pointer_width = "64", not(windows))))] + pub va_reserved: [u32; 16usize], + #[cfg(not(any(target_arch = "x86_64", all(target_pointer_width = "64", not(windows)))))] + pub va_reserved: [u32; 19usize], +} +impl Default for _VAProcPipelineParameterBuffer { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Video processing pipeline configuration.\n\n This buffer defines a video processing pipeline. The actual filters to\n be applied are provided in the \\c filters field, they can be re-used\n in other processing pipelines.\n\n The target surface is specified by the \\c render_target argument of\n \\c vaBeginPicture(). The general usage model is described as follows:\n - \\c vaBeginPicture(): specify the target surface that receives the\n processed output;\n - \\c vaRenderPicture(): specify a surface to be processed and composed\n into the \\c render_target. Use as many \\c vaRenderPicture() calls as\n necessary surfaces to compose ;\n - \\c vaEndPicture(): tell the driver to start processing the surfaces\n with the requested filters.\n\n If a filter (e.g. noise reduction) needs to be applied with different\n values for multiple surfaces, the application needs to create as many\n filter parameter buffers as necessary. i.e. the filter parameters shall\n not change between two calls to \\c vaRenderPicture().\n\n For composition usage models, the first surface to process will generally\n use an opaque background color, i.e. \\c output_background_color set with\n the most significant byte set to \\c 0xff. For instance, \\c 0xff000000 for\n a black background. Then, subsequent surfaces would use a transparent\n background color."] +pub type VAProcPipelineParameterBuffer = _VAProcPipelineParameterBuffer; +#[doc = " \\brief Filter parameter buffer base.\n\n This is a helper structure used by driver implementations only.\n Users are not supposed to allocate filter parameter buffers of this\n type."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterParameterBufferBase { + #[doc = " \\brief Filter type."] + pub type_: VAProcFilterType, +} +impl Default for _VAProcFilterParameterBufferBase { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Filter parameter buffer base.\n\n This is a helper structure used by driver implementations only.\n Users are not supposed to allocate filter parameter buffers of this\n type."] +pub type VAProcFilterParameterBufferBase = _VAProcFilterParameterBufferBase; +#[doc = " \\brief Default filter parametrization.\n\n Unless there is a filter-specific parameter buffer,\n #VAProcFilterParameterBuffer is the default type to use."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct _VAProcFilterParameterBuffer { + #[doc = " \\brief Filter type."] + pub type_: VAProcFilterType, + #[doc = " \\brief Value."] + pub value: f32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAProcFilterParameterBuffer { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Default filter parametrization.\n\n Unless there is a filter-specific parameter buffer,\n #VAProcFilterParameterBuffer is the default type to use."] +pub type VAProcFilterParameterBuffer = _VAProcFilterParameterBuffer; +#[doc = " \\brief Deinterlacing filter parametrization."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterParameterBufferDeinterlacing { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilterDeinterlacing."] + pub type_: VAProcFilterType, + #[doc = " \\brief Deinterlacing algorithm."] + pub algorithm: VAProcDeinterlacingType, + #[doc = " \\brief Deinterlacing flags."] + pub flags: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAProcFilterParameterBufferDeinterlacing { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Deinterlacing filter parametrization."] +pub type VAProcFilterParameterBufferDeinterlacing = _VAProcFilterParameterBufferDeinterlacing; +#[doc = " \\brief Color balance filter parametrization.\n\n This buffer defines color balance attributes. A VA buffer can hold\n several color balance attributes by creating a VA buffer of desired\n number of elements. This can be achieved by the following pseudo-code:\n\n \\code\n enum { kHue, kSaturation, kBrightness, kContrast };\n\n // Initial color balance parameters\n static const VAProcFilterParameterBufferColorBalance colorBalanceParams[4] =\n {\n [kHue] =\n { VAProcFilterColorBalance, VAProcColorBalanceHue, 0.5 },\n [kSaturation] =\n { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 },\n [kBrightness] =\n { VAProcFilterColorBalance, VAProcColorBalanceBrightness, 0.5 },\n [kSaturation] =\n { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 }\n };\n\n // Create buffer\n VABufferID colorBalanceBuffer;\n vaCreateBuffer(va_dpy, vpp_ctx,\n VAProcFilterParameterBufferType, sizeof(*pColorBalanceParam), 4,\n colorBalanceParams,\n &colorBalanceBuffer\n );\n\n VAProcFilterParameterBufferColorBalance *pColorBalanceParam;\n vaMapBuffer(va_dpy, colorBalanceBuffer, &pColorBalanceParam);\n {\n // Change brightness only\n pColorBalanceBuffer[kBrightness].value = 0.75;\n }\n vaUnmapBuffer(va_dpy, colorBalanceBuffer);\n \\endcode"] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct _VAProcFilterParameterBufferColorBalance { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilterColorBalance."] + pub type_: VAProcFilterType, + #[doc = " \\brief Color balance attribute."] + pub attrib: VAProcColorBalanceType, + #[doc = " \\brief Color balance value.\n\n Special case for automatically adjusted attributes. e.g.\n #VAProcColorBalanceAutoSaturation,\n #VAProcColorBalanceAutoBrightness,\n #VAProcColorBalanceAutoContrast.\n - If \\ref value is \\c 1.0 +/- \\c FLT_EPSILON, the attribute is\n automatically adjusted and overrides any other attribute of\n the same type that would have been set explicitly;\n - If \\ref value is \\c 0.0 +/- \\c FLT_EPSILON, the attribute is\n disabled and other attribute of the same type is used instead."] + pub value: f32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAProcFilterParameterBufferColorBalance { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Color balance filter parametrization.\n\n This buffer defines color balance attributes. A VA buffer can hold\n several color balance attributes by creating a VA buffer of desired\n number of elements. This can be achieved by the following pseudo-code:\n\n \\code\n enum { kHue, kSaturation, kBrightness, kContrast };\n\n // Initial color balance parameters\n static const VAProcFilterParameterBufferColorBalance colorBalanceParams[4] =\n {\n [kHue] =\n { VAProcFilterColorBalance, VAProcColorBalanceHue, 0.5 },\n [kSaturation] =\n { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 },\n [kBrightness] =\n { VAProcFilterColorBalance, VAProcColorBalanceBrightness, 0.5 },\n [kSaturation] =\n { VAProcFilterColorBalance, VAProcColorBalanceSaturation, 0.5 }\n };\n\n // Create buffer\n VABufferID colorBalanceBuffer;\n vaCreateBuffer(va_dpy, vpp_ctx,\n VAProcFilterParameterBufferType, sizeof(*pColorBalanceParam), 4,\n colorBalanceParams,\n &colorBalanceBuffer\n );\n\n VAProcFilterParameterBufferColorBalance *pColorBalanceParam;\n vaMapBuffer(va_dpy, colorBalanceBuffer, &pColorBalanceParam);\n {\n // Change brightness only\n pColorBalanceBuffer[kBrightness].value = 0.75;\n }\n vaUnmapBuffer(va_dpy, colorBalanceBuffer);\n \\endcode"] +pub type VAProcFilterParameterBufferColorBalance = _VAProcFilterParameterBufferColorBalance; +#[doc = " \\brief Total color correction filter parametrization."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct _VAProcFilterParameterBufferTotalColorCorrection { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilterTotalColorCorrection."] + pub type_: VAProcFilterType, + #[doc = " \\brief Color to correct."] + pub attrib: VAProcTotalColorCorrectionType, + #[doc = " \\brief Color correction value."] + pub value: f32, +} +impl Default for _VAProcFilterParameterBufferTotalColorCorrection { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Total color correction filter parametrization."] +pub type VAProcFilterParameterBufferTotalColorCorrection = _VAProcFilterParameterBufferTotalColorCorrection; +#[doc = " \\brief Human Vision System(HVS) Noise reduction filter parametrization."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterParameterBufferHVSNoiseReduction { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilterHVSNoiseReduction."] + pub type_: VAProcFilterType, + #[doc = " \\brief QP for encoding, used for HVS Denoise"] + pub qp: u16, + #[doc = " \\brief QP to Noise Reduction Strength Mode, used for Human Vision System Based Noise Reduction.\n Controls Noise Reduction strength of conservative and aggressive mode.\n It is an integer from [0-16].\n Value 0 means completely turn off Noise Reduction;\n Value 16 means the most aggressive mode of Noise Reduction;\n Value 10 is the default value."] + pub strength: u16, + #[doc = " \\brief HVS Denoise Mode which controls denoise method.\n It is a value of VA_PROC_HVS_DENOISE_xxx.\n Please see the definition of VA_PROC_HVS_DENOISE_xxx."] + pub mode: u16, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u16; 15usize], +} +impl Default for _VAProcFilterParameterBufferHVSNoiseReduction { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Human Vision System(HVS) Noise reduction filter parametrization."] +pub type VAProcFilterParameterBufferHVSNoiseReduction = _VAProcFilterParameterBufferHVSNoiseReduction; +#[doc = " \\brief High Dynamic Range(HDR) Tone Mapping filter parametrization."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterParameterBufferHDRToneMapping { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilterHighDynamicRangeToneMapping."] + pub type_: VAProcFilterType, + #[doc = " \\brief High Dynamic Range metadata, could be HDR10 etc.\n\n This metadata is mainly for the input surface. Given that dynamic metadata is changing\n on frame-by-frame or scene-by-scene basis for HDR10 plus, differentiate the metadata\n for the input and output."] + pub data: VAHdrMetaData, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 16usize], +} +impl Default for _VAProcFilterParameterBufferHDRToneMapping { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief High Dynamic Range(HDR) Tone Mapping filter parametrization."] +pub type VAProcFilterParameterBufferHDRToneMapping = _VAProcFilterParameterBufferHDRToneMapping; +#[doc = " \\brief 3DLUT filter parametrization.\n\n 3DLUT (Three Dimensional Look Up Table) is often used when converting an image or a video frame\n from one color representation to another, for example, when converting log and gamma encodings,\n changing the color space, applying a color correction, changing the dynamic range, gamut mapping etc.\n\n This buffer defines 3DLUT attributes and memory layout. The typical 3DLUT has fixed number(lut_size)\n per dimension and memory layout is 3 dimensional array as 3dlut[stride_0][stride_1][stride_2] (lut_size\n shall be smaller than stride_0/1/2).\n\n API user should query hardware capability by using the VAProcFilterCap3DLUT to get the 3DLUT attributes\n which hardware supports, and use these attributes. For example, if the user queries hardware, the API user\n could get caps with 3dlut[33][33][64] (lut_size = 33, lut_stride[0/1/2] = 33/33/64). API user shall not\n use the attributes which hardware can not support.\n\n 3DLUT is usually used to transform input RGB/YUV values in one color space to output RGB values in another\n color space. Based on 1) the format and color space of VPP input and output and 2) 3DLUT memory layout and\n channel mapping, driver will enable some color space conversion implicitly if needed. For example, the input of\n VPP is P010 format in BT2020 color space, the output of VPP is NV12 in BT709 color space and the 3DLUT channel\n mapping is VA_3DLUT_CHANNEL_RGB_RGB, driver could build the data pipeline as P010(BT2020)->RGB(BT2020)\n ->3DULT(BT709)->NV12(BT709). Please note, the limitation of 3DLUT filter color space is that the color space of\n 3DLUT filter input data needs to be same as the input data of VPP; the color space of 3DLUT filter output data\n needs to be same as the output data of VPP; format does not have such limitation."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterParameterBuffer3DLUT { + #[doc = " \\brief Filter type. Shall be set to #VAProcFilter3DLUT."] + pub type_: VAProcFilterType, + #[doc = " \\brief lut_surface contains 3DLUT data in the 3DLUT memory layout, must be linear"] + pub lut_surface: VASurfaceID, + #[doc = " \\brief lut_size is the number of valid points on every dimension of the three dimensional look up table.\n The size of LUT (lut_size) shall be same among every dimension of the three dimensional look up table.\n The size of LUT (lut_size) shall be smaller than lut_stride[0/1/2]."] + pub lut_size: u16, + #[doc = " \\brief lut_stride are the number of points on every dimension of the three dimensional look up table.\n Three dimension can has 3 different stride, lut3d[lut_stride[0]][lut_stride[1]][lut_stride[2]].\n But the valid point shall start from 0, the range of valid point is [0, lut_size-1] for every dimension."] + pub lut_stride: [u16; 3usize], + #[doc = " \\brief bit_depth is the number of bits for every channel R, G or B (or Y, U, V)"] + pub bit_depth: u16, + #[doc = " \\brief num_channel is the number of channels"] + pub num_channel: u16, + #[doc = " \\brief channel_mapping defines the mapping of input and output channels, could be one of VA_3DLUT_CHANNEL_XXX"] + pub channel_mapping: u32, + #[doc = " \\brief reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 16usize], +} +impl Default for _VAProcFilterParameterBuffer3DLUT { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief 3DLUT filter parametrization.\n\n 3DLUT (Three Dimensional Look Up Table) is often used when converting an image or a video frame\n from one color representation to another, for example, when converting log and gamma encodings,\n changing the color space, applying a color correction, changing the dynamic range, gamut mapping etc.\n\n This buffer defines 3DLUT attributes and memory layout. The typical 3DLUT has fixed number(lut_size)\n per dimension and memory layout is 3 dimensional array as 3dlut[stride_0][stride_1][stride_2] (lut_size\n shall be smaller than stride_0/1/2).\n\n API user should query hardware capability by using the VAProcFilterCap3DLUT to get the 3DLUT attributes\n which hardware supports, and use these attributes. For example, if the user queries hardware, the API user\n could get caps with 3dlut[33][33][64] (lut_size = 33, lut_stride[0/1/2] = 33/33/64). API user shall not\n use the attributes which hardware can not support.\n\n 3DLUT is usually used to transform input RGB/YUV values in one color space to output RGB values in another\n color space. Based on 1) the format and color space of VPP input and output and 2) 3DLUT memory layout and\n channel mapping, driver will enable some color space conversion implicitly if needed. For example, the input of\n VPP is P010 format in BT2020 color space, the output of VPP is NV12 in BT709 color space and the 3DLUT channel\n mapping is VA_3DLUT_CHANNEL_RGB_RGB, driver could build the data pipeline as P010(BT2020)->RGB(BT2020)\n ->3DULT(BT709)->NV12(BT709). Please note, the limitation of 3DLUT filter color space is that the color space of\n 3DLUT filter input data needs to be same as the input data of VPP; the color space of 3DLUT filter output data\n needs to be same as the output data of VPP; format does not have such limitation."] +pub type VAProcFilterParameterBuffer3DLUT = _VAProcFilterParameterBuffer3DLUT; +#[doc = " \\brief Capabilities specification for the 3DLUT filter."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterCap3DLUT { + #[doc = " \\brief lut_size is the number of valid points on every dimension of the three dimensional look up table."] + pub lut_size: u16, + #[doc = " \\brief lut_stride are the number of points on every dimension of the three dimensional look up table. lut3d[lut_stride[0]][lut_stride[1]][lut_stride[2]]"] + pub lut_stride: [u16; 3usize], + #[doc = " \\brief bit_depth is the number of bits for every channel R, G or B (or Y, U, V)"] + pub bit_depth: u16, + #[doc = " \\brief num_channel is the number of channels"] + pub num_channel: u16, + #[doc = " \\brief channel_mapping defines the mapping of channels, could be some combination of VA_3DLUT_CHANNEL_XXX"] + pub channel_mapping: u32, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 16usize], +} +#[doc = " \\brief Capabilities specification for the 3DLUT filter."] +pub type VAProcFilterCap3DLUT = _VAProcFilterCap3DLUT; +#[doc = " \\brief Default filter cap specification (single range value).\n\n Unless there is a filter-specific cap structure, #VAProcFilterCap is the\n default type to use for output caps from vaQueryVideoProcFilterCaps()."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq)] +pub struct _VAProcFilterCap { + #[doc = " \\brief Range of supported values for the filter."] + pub range: VAProcFilterValueRange, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +#[doc = " \\brief Default filter cap specification (single range value).\n\n Unless there is a filter-specific cap structure, #VAProcFilterCap is the\n default type to use for output caps from vaQueryVideoProcFilterCaps()."] +pub type VAProcFilterCap = _VAProcFilterCap; +#[doc = " \\brief Capabilities specification for the deinterlacing filter."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct _VAProcFilterCapDeinterlacing { + #[doc = " \\brief Deinterlacing algorithm."] + pub type_: VAProcDeinterlacingType, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAProcFilterCapDeinterlacing { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Capabilities specification for the deinterlacing filter."] +pub type VAProcFilterCapDeinterlacing = _VAProcFilterCapDeinterlacing; +#[doc = " \\brief Capabilities specification for the color balance filter."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct _VAProcFilterCapColorBalance { + #[doc = " \\brief Color balance operation."] + pub type_: VAProcColorBalanceType, + #[doc = " \\brief Range of supported values for the specified operation."] + pub range: VAProcFilterValueRange, + #[doc = " \\brief Reserved bytes for future use, must be zero"] + pub va_reserved: [u32; 4usize], +} +impl Default for _VAProcFilterCapColorBalance { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Capabilities specification for the color balance filter."] +pub type VAProcFilterCapColorBalance = _VAProcFilterCapColorBalance; +#[doc = " \\brief Capabilities specification for the Total Color Correction filter."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct _VAProcFilterCapTotalColorCorrection { + #[doc = " \\brief Color to correct."] + pub type_: VAProcTotalColorCorrectionType, + #[doc = " \\brief Range of supported values for the specified color."] + pub range: VAProcFilterValueRange, +} +impl Default for _VAProcFilterCapTotalColorCorrection { + fn default() -> Self { + let mut s = ::std::mem::MaybeUninit::::uninit(); + unsafe { + ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + s.assume_init() + } + } +} +#[doc = " \\brief Capabilities specification for the Total Color Correction filter."] +pub type VAProcFilterCapTotalColorCorrection = _VAProcFilterCapTotalColorCorrection; +#[doc = " ProtectedSessions and Contexts\n\n According to #VAContextID, Context represents a \"virtual\" video decode,\n encode or video processing pipeline. Surfaces are render targets for a given\n context. The data in the surfaces are not accessible to the client except if\n derived image is supported and the internal data format of the surface is\n implementation specific. Application can create a video decode, encode or\n processing context which represents a \"virtualized\" hardware device.\n\n Since Protected Session does not virtualize any HW device or build any\n pipeline but rather accessorize existing virtualized HW device or pipeline\n to operate in protected mode so we decided to create separate function.\n Beside this, a virtualized HW device or pipeline could own several protected\n sessions and operate in those protected modes without ever re-creating\n virtualization of HW device or re-building HW pipeline (an unique protected\n environment multiplexing capability in Intel HW).\n\n The returned protected_session represents a notion of Host and TEE clients\n while representing protection status in GPU and Display.\n\n Both contexts and protected sessions are identified by unique IDs and its\n implementation specific internals are kept opaque to the clients"] +pub type VAProtectedSessionID = VAGenericID; +pub mod _bindgen_ty_1 { + #[doc = " \\brief DRM authentication type."] + pub type Type = ::std::os::raw::c_uint; + #[doc = " \\brief Disconnected."] + pub const VA_DRM_AUTH_NONE: Type = 0; + #[doc = " \\brief Connected. Authenticated with DRI1 protocol.\n\n @deprecated\n This is a deprecated authentication type. All DRI-based drivers have\n been migrated to use the DRI2 protocol. Newly written drivers shall\n use DRI2 protocol only, or a custom authentication means. e.g. opt\n for authenticating on the VA driver side, instead of libva side."] + pub const VA_DRM_AUTH_DRI1: Type = 1; + #[doc = " \\brief Connected. Authenticated with DRI2 protocol.\n\n This is only useful to VA/X11 drivers. The libva-x11 library provides\n a helper function VA_DRI2Authenticate() for authenticating the\n connection. However, DRI2 conformant drivers don't need to call that\n function since authentication happens on the libva side, implicitly."] + pub const VA_DRM_AUTH_DRI2: Type = 2; + #[doc = " \\brief Connected. Authenticated with some alternate raw protocol.\n\n This authentication mode is mainly used in non-VA/X11 drivers.\n Authentication happens through some alternative method, at the\n discretion of the VA driver implementation."] + pub const VA_DRM_AUTH_CUSTOM: Type = 3; +} +#[doc = " \\brief External buffer descriptor for a DRM PRIME surface.\n\n For export, call vaExportSurfaceHandle() with mem_type set to\n VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and pass a pointer to an\n instance of this structure to fill.\n If VA_EXPORT_SURFACE_SEPARATE_LAYERS is specified on export, each\n layer will contain exactly one plane. For example, an NV12\n surface will be exported as two layers, one of DRM_FORMAT_R8 and\n one of DRM_FORMAT_GR88.\n If VA_EXPORT_SURFACE_COMPOSED_LAYERS is specified on export,\n there will be exactly one layer.\n\n For import, call vaCreateSurfaces() with the MemoryType attribute\n set to VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and the\n ExternalBufferDescriptor attribute set to point to an array of\n num_surfaces instances of this structure.\n The number of planes which need to be provided for a given layer\n is dependent on both the format and the format modifier used for\n the objects containing it. For example, the format DRM_FORMAT_RGBA\n normally requires one plane, but with the format modifier\n I915_FORMAT_MOD_Y_TILED_CCS it requires two planes - the first\n being the main data plane and the second containing the color\n control surface.\n Note that a given driver may only support a subset of possible\n representations of a particular format. For example, it may only\n support NV12 surfaces when they are contained within a single DRM\n object, and therefore fail to create such surfaces if the two\n planes are in different DRM objects.\n Note that backend driver will retrieve the resource represent by fd,\n and a valid surface ID is generated. Backend driver will not close\n the file descriptor. Application should handle the release of the fd.\n releasing the fd will not impact the existence of the surface."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIMESurfaceDescriptor { + #[doc = " Pixel format fourcc of the whole surface (VA_FOURCC_*)."] + pub fourcc: u32, + #[doc = " Width of the surface in pixels."] + pub width: u32, + #[doc = " Height of the surface in pixels."] + pub height: u32, + #[doc = " Number of distinct DRM objects making up the surface."] + pub num_objects: u32, + pub objects: [_VADRMPRIMESurfaceDescriptor__bindgen_ty_1; 4usize], + #[doc = " Number of layers making up the surface."] + pub num_layers: u32, + pub layers: [_VADRMPRIMESurfaceDescriptor__bindgen_ty_2; 4usize], +} +#[doc = " Description of each object."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIMESurfaceDescriptor__bindgen_ty_1 { + #[doc = " DRM PRIME file descriptor for this object."] + pub fd: ::std::os::raw::c_int, + #[doc = " Total size of this object (may include regions which are\n not part of the surface)."] + pub size: u32, + #[doc = " Format modifier applied to this object."] + pub drm_format_modifier: u64, +} +#[doc = " Description of each layer in the surface."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIMESurfaceDescriptor__bindgen_ty_2 { + #[doc = " DRM format fourcc of this layer (DRM_FOURCC_*)."] + pub drm_format: u32, + #[doc = " Number of planes in this layer."] + pub num_planes: u32, + #[doc = " Index in the objects array of the object containing each\n plane."] + pub object_index: [u32; 4usize], + #[doc = " Offset within the object of each plane."] + pub offset: [u32; 4usize], + #[doc = " Pitch of each plane."] + pub pitch: [u32; 4usize], +} +#[doc = " \\brief External buffer descriptor for a DRM PRIME surface.\n\n For export, call vaExportSurfaceHandle() with mem_type set to\n VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and pass a pointer to an\n instance of this structure to fill.\n If VA_EXPORT_SURFACE_SEPARATE_LAYERS is specified on export, each\n layer will contain exactly one plane. For example, an NV12\n surface will be exported as two layers, one of DRM_FORMAT_R8 and\n one of DRM_FORMAT_GR88.\n If VA_EXPORT_SURFACE_COMPOSED_LAYERS is specified on export,\n there will be exactly one layer.\n\n For import, call vaCreateSurfaces() with the MemoryType attribute\n set to VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 and the\n ExternalBufferDescriptor attribute set to point to an array of\n num_surfaces instances of this structure.\n The number of planes which need to be provided for a given layer\n is dependent on both the format and the format modifier used for\n the objects containing it. For example, the format DRM_FORMAT_RGBA\n normally requires one plane, but with the format modifier\n I915_FORMAT_MOD_Y_TILED_CCS it requires two planes - the first\n being the main data plane and the second containing the color\n control surface.\n Note that a given driver may only support a subset of possible\n representations of a particular format. For example, it may only\n support NV12 surfaces when they are contained within a single DRM\n object, and therefore fail to create such surfaces if the two\n planes are in different DRM objects.\n Note that backend driver will retrieve the resource represent by fd,\n and a valid surface ID is generated. Backend driver will not close\n the file descriptor. Application should handle the release of the fd.\n releasing the fd will not impact the existence of the surface."] +pub type VADRMPRIMESurfaceDescriptor = _VADRMPRIMESurfaceDescriptor; +#[doc = " \\brief External buffer descriptor for a DRM PRIME surface with flags\n\n This structure is an extention for VADRMPRIMESurfaceDescriptor,\n it has the same behavior as if used with VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2.\n\n The field \"flags\" is added, see \"Surface external buffer descriptor flags\".\n To use this structure, use VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_3 instead."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIME3SurfaceDescriptor { + #[doc = " Pixel format fourcc of the whole surface (VA_FOURCC_*)."] + pub fourcc: u32, + #[doc = " Width of the surface in pixels."] + pub width: u32, + #[doc = " Height of the surface in pixels."] + pub height: u32, + #[doc = " Number of distinct DRM objects making up the surface."] + pub num_objects: u32, + pub objects: [_VADRMPRIME3SurfaceDescriptor__bindgen_ty_1; 4usize], + #[doc = " Number of layers making up the surface."] + pub num_layers: u32, + pub layers: [_VADRMPRIME3SurfaceDescriptor__bindgen_ty_2; 4usize], + #[doc = " \\brief flags. See \"Surface external buffer descriptor flags\"."] + pub flags: u32, + #[doc = " reserved bytes, must be zero"] + pub reserved: [u32; 7usize], +} +#[doc = " Description of each object."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIME3SurfaceDescriptor__bindgen_ty_1 { + #[doc = " DRM PRIME file descriptor for this object."] + pub fd: ::std::os::raw::c_int, + #[doc = " Total size of this object (may include regions which are\n not part of the surface)."] + pub size: u32, + #[doc = " Format modifier applied to this object."] + pub drm_format_modifier: u64, +} +#[doc = " Description of each layer in the surface."] +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub struct _VADRMPRIME3SurfaceDescriptor__bindgen_ty_2 { + #[doc = " DRM format fourcc of this layer (DRM_FOURCC_*)."] + pub drm_format: u32, + #[doc = " Number of planes in this layer."] + pub num_planes: u32, + #[doc = " Index in the objects array of the object containing each\n plane."] + pub object_index: [u32; 4usize], + #[doc = " Offset within the object of each plane."] + pub offset: [u32; 4usize], + #[doc = " Pitch of each plane."] + pub pitch: [u32; 4usize], +} +#[doc = " \\brief External buffer descriptor for a DRM PRIME surface with flags\n\n This structure is an extention for VADRMPRIMESurfaceDescriptor,\n it has the same behavior as if used with VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2.\n\n The field \"flags\" is added, see \"Surface external buffer descriptor flags\".\n To use this structure, use VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_3 instead."] +pub type VADRMPRIME3SurfaceDescriptor = _VADRMPRIME3SurfaceDescriptor; +pub struct Va { + __library: ::libloading::Library, + pub vaErrorStr: + Result *const ::std::os::raw::c_char, ::libloading::Error>, + pub vaSetErrorCallback: Result< + unsafe extern "C" fn( + dpy: VADisplay, + callback: VAMessageCallback, + user_context: *mut ::std::os::raw::c_void, + ) -> VAMessageCallback, + ::libloading::Error, + >, + pub vaSetInfoCallback: Result< + unsafe extern "C" fn( + dpy: VADisplay, + callback: VAMessageCallback, + user_context: *mut ::std::os::raw::c_void, + ) -> VAMessageCallback, + ::libloading::Error, + >, + pub vaDisplayIsValid: Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaSetDriverName: Result< + unsafe extern "C" fn(dpy: VADisplay, driver_name: *mut ::std::os::raw::c_char) -> VAStatus, + ::libloading::Error, + >, + pub vaInitialize: Result< + unsafe extern "C" fn( + dpy: VADisplay, + major_version: *mut ::std::os::raw::c_int, + minor_version: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaTerminate: Result VAStatus, ::libloading::Error>, + pub vaQueryVendorString: + Result *const ::std::os::raw::c_char, ::libloading::Error>, + pub vaGetLibFunc: Result< + unsafe extern "C" fn(dpy: VADisplay, func: *const ::std::os::raw::c_char) -> VAPrivFunc, + ::libloading::Error, + >, + pub vaMaxNumProfiles: Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaMaxNumEntrypoints: Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaMaxNumConfigAttributes: + Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaQueryConfigProfiles: Result< + unsafe extern "C" fn( + dpy: VADisplay, + profile_list: *mut VAProfile::Type, + num_profiles: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQueryConfigEntrypoints: Result< + unsafe extern "C" fn( + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint_list: *mut VAEntrypoint::Type, + num_entrypoints: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaGetConfigAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint: VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateConfig: Result< + unsafe extern "C" fn( + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint: VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: ::std::os::raw::c_int, + config_id: *mut VAConfigID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroyConfig: + Result VAStatus, ::libloading::Error>, + pub vaQueryConfigAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + config_id: VAConfigID, + profile: *mut VAProfile::Type, + entrypoint: *mut VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQuerySurfaceAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + config: VAConfigID, + attrib_list: *mut VASurfaceAttrib, + num_attribs: *mut ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateSurfaces: Result< + unsafe extern "C" fn( + dpy: VADisplay, + format: ::std::os::raw::c_uint, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_uint, + attrib_list: *mut VASurfaceAttrib, + num_attribs: ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroySurfaces: Result< + unsafe extern "C" fn( + dpy: VADisplay, + surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateContext: Result< + unsafe extern "C" fn( + dpy: VADisplay, + config_id: VAConfigID, + picture_width: ::std::os::raw::c_int, + picture_height: ::std::os::raw::c_int, + flag: ::std::os::raw::c_int, + render_targets: *mut VASurfaceID, + num_render_targets: ::std::os::raw::c_int, + context: *mut VAContextID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroyContext: + Result VAStatus, ::libloading::Error>, + pub vaCreateMFContext: + Result VAStatus, ::libloading::Error>, + pub vaMFAddContext: Result< + unsafe extern "C" fn(dpy: VADisplay, mf_context: VAMFContextID, context: VAContextID) -> VAStatus, + ::libloading::Error, + >, + pub vaMFReleaseContext: Result< + unsafe extern "C" fn(dpy: VADisplay, mf_context: VAMFContextID, context: VAContextID) -> VAStatus, + ::libloading::Error, + >, + pub vaQueryProcessingRate: Result< + unsafe extern "C" fn( + dpy: VADisplay, + config: VAConfigID, + proc_buf: *mut VAProcessingRateParameter, + processing_rate: *mut ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateBuffer: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + type_: VABufferType::Type, + size: ::std::os::raw::c_uint, + num_elements: ::std::os::raw::c_uint, + data: *mut ::std::os::raw::c_void, + buf_id: *mut VABufferID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateBuffer2: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + type_: VABufferType::Type, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + unit_size: *mut ::std::os::raw::c_uint, + pitch: *mut ::std::os::raw::c_uint, + buf_id: *mut VABufferID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaBufferSetNumElements: Result< + unsafe extern "C" fn(dpy: VADisplay, buf_id: VABufferID, num_elements: ::std::os::raw::c_uint) -> VAStatus, + ::libloading::Error, + >, + pub vaMapBuffer: Result< + unsafe extern "C" fn(dpy: VADisplay, buf_id: VABufferID, pbuf: *mut *mut ::std::os::raw::c_void) -> VAStatus, + ::libloading::Error, + >, + pub vaMapBuffer2: Result< + unsafe extern "C" fn( + dpy: VADisplay, + buf_id: VABufferID, + pbuf: *mut *mut ::std::os::raw::c_void, + flags: u32, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaUnmapBuffer: + Result VAStatus, ::libloading::Error>, + pub vaDestroyBuffer: + Result VAStatus, ::libloading::Error>, + pub vaAcquireBufferHandle: Result< + unsafe extern "C" fn(dpy: VADisplay, buf_id: VABufferID, buf_info: *mut VABufferInfo) -> VAStatus, + ::libloading::Error, + >, + pub vaReleaseBufferHandle: + Result VAStatus, ::libloading::Error>, + pub vaExportSurfaceHandle: Result< + unsafe extern "C" fn( + dpy: VADisplay, + surface_id: VASurfaceID, + mem_type: u32, + flags: u32, + descriptor: *mut ::std::os::raw::c_void, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaBeginPicture: Result< + unsafe extern "C" fn(dpy: VADisplay, context: VAContextID, render_target: VASurfaceID) -> VAStatus, + ::libloading::Error, + >, + pub vaRenderPicture: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + buffers: *mut VABufferID, + num_buffers: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaEndPicture: + Result VAStatus, ::libloading::Error>, + pub vaMFSubmit: Result< + unsafe extern "C" fn( + dpy: VADisplay, + mf_context: VAMFContextID, + contexts: *mut VAContextID, + num_contexts: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaSyncSurface: + Result VAStatus, ::libloading::Error>, + pub vaSyncSurface2: Result< + unsafe extern "C" fn(dpy: VADisplay, surface: VASurfaceID, timeout_ns: u64) -> VAStatus, + ::libloading::Error, + >, + pub vaQuerySurfaceStatus: Result< + unsafe extern "C" fn( + dpy: VADisplay, + render_target: VASurfaceID, + status: *mut VASurfaceStatus::Type, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQuerySurfaceError: Result< + unsafe extern "C" fn( + dpy: VADisplay, + surface: VASurfaceID, + error_status: VAStatus, + error_info: *mut *mut ::std::os::raw::c_void, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaSyncBuffer: Result< + unsafe extern "C" fn(dpy: VADisplay, buf_id: VABufferID, timeout_ns: u64) -> VAStatus, + ::libloading::Error, + >, + pub vaMaxNumImageFormats: + Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaQueryImageFormats: Result< + unsafe extern "C" fn( + dpy: VADisplay, + format_list: *mut VAImageFormat, + num_formats: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateImage: Result< + unsafe extern "C" fn( + dpy: VADisplay, + format: *mut VAImageFormat, + width: ::std::os::raw::c_int, + height: ::std::os::raw::c_int, + image: *mut VAImage, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroyImage: Result VAStatus, ::libloading::Error>, + pub vaSetImagePalette: Result< + unsafe extern "C" fn(dpy: VADisplay, image: VAImageID, palette: *mut ::std::os::raw::c_uchar) -> VAStatus, + ::libloading::Error, + >, + pub vaGetImage: Result< + unsafe extern "C" fn( + dpy: VADisplay, + surface: VASurfaceID, + x: ::std::os::raw::c_int, + y: ::std::os::raw::c_int, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + image: VAImageID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaPutImage: Result< + unsafe extern "C" fn( + dpy: VADisplay, + surface: VASurfaceID, + image: VAImageID, + src_x: ::std::os::raw::c_int, + src_y: ::std::os::raw::c_int, + src_width: ::std::os::raw::c_uint, + src_height: ::std::os::raw::c_uint, + dest_x: ::std::os::raw::c_int, + dest_y: ::std::os::raw::c_int, + dest_width: ::std::os::raw::c_uint, + dest_height: ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDeriveImage: Result< + unsafe extern "C" fn(dpy: VADisplay, surface: VASurfaceID, image: *mut VAImage) -> VAStatus, + ::libloading::Error, + >, + pub vaMaxNumSubpictureFormats: + Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaQuerySubpictureFormats: Result< + unsafe extern "C" fn( + dpy: VADisplay, + format_list: *mut VAImageFormat, + flags: *mut ::std::os::raw::c_uint, + num_formats: *mut ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateSubpicture: Result< + unsafe extern "C" fn(dpy: VADisplay, image: VAImageID, subpicture: *mut VASubpictureID) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroySubpicture: + Result VAStatus, ::libloading::Error>, + pub vaSetSubpictureImage: Result< + unsafe extern "C" fn(dpy: VADisplay, subpicture: VASubpictureID, image: VAImageID) -> VAStatus, + ::libloading::Error, + >, + pub vaSetSubpictureChromakey: Result< + unsafe extern "C" fn( + dpy: VADisplay, + subpicture: VASubpictureID, + chromakey_min: ::std::os::raw::c_uint, + chromakey_max: ::std::os::raw::c_uint, + chromakey_mask: ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaSetSubpictureGlobalAlpha: Result< + unsafe extern "C" fn(dpy: VADisplay, subpicture: VASubpictureID, global_alpha: f32) -> VAStatus, + ::libloading::Error, + >, + pub vaAssociateSubpicture: Result< + unsafe extern "C" fn( + dpy: VADisplay, + subpicture: VASubpictureID, + target_surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + src_x: i16, + src_y: i16, + src_width: u16, + src_height: u16, + dest_x: i16, + dest_y: i16, + dest_width: u16, + dest_height: u16, + flags: u32, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDeassociateSubpicture: Result< + unsafe extern "C" fn( + dpy: VADisplay, + subpicture: VASubpictureID, + target_surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaMaxNumDisplayAttributes: + Result ::std::os::raw::c_int, ::libloading::Error>, + pub vaQueryDisplayAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: *mut ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaGetDisplayAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaSetDisplayAttributes: Result< + unsafe extern "C" fn( + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: ::std::os::raw::c_int, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCopy: Result< + unsafe extern "C" fn( + dpy: VADisplay, + dst: *mut VACopyObject, + src: *mut VACopyObject, + option: VACopyOption, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQueryVideoProcFilters: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + filters: *mut VAProcFilterType, + num_filters: *mut ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQueryVideoProcFilterCaps: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + type_: VAProcFilterType, + filter_caps: *mut ::std::os::raw::c_void, + num_filter_caps: *mut ::std::os::raw::c_uint, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaQueryVideoProcPipelineCaps: Result< + unsafe extern "C" fn( + dpy: VADisplay, + context: VAContextID, + filters: *mut VABufferID, + num_filters: ::std::os::raw::c_uint, + pipeline_caps: *mut VAProcPipelineCaps, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaCreateProtectedSession: Result< + unsafe extern "C" fn( + dpy: VADisplay, + config_id: VAConfigID, + protected_session: *mut VAProtectedSessionID, + ) -> VAStatus, + ::libloading::Error, + >, + pub vaDestroyProtectedSession: Result< + unsafe extern "C" fn(dpy: VADisplay, protected_session: VAProtectedSessionID) -> VAStatus, + ::libloading::Error, + >, + pub vaAttachProtectedSession: Result< + unsafe extern "C" fn(dpy: VADisplay, id: VAGenericID, protected_session: VAProtectedSessionID) -> VAStatus, + ::libloading::Error, + >, + pub vaDetachProtectedSession: + Result VAStatus, ::libloading::Error>, + pub vaProtectedSessionExecute: Result< + unsafe extern "C" fn(dpy: VADisplay, protected_session: VAProtectedSessionID, buf_id: VABufferID) -> VAStatus, + ::libloading::Error, + >, + pub vaGetDisplayDRM: Result VADisplay, ::libloading::Error>, +} +impl Va { + pub unsafe fn new

(path: P) -> Result + where + P: ::libloading::AsFilename, + { + let library = ::libloading::Library::new(path)?; + Self::from_library(library) + } + pub unsafe fn from_library(library: L) -> Result + where + L: Into<::libloading::Library>, + { + let __library = library.into(); + let vaErrorStr = __library.get(b"vaErrorStr\0").map(|sym| *sym); + let vaSetErrorCallback = __library.get(b"vaSetErrorCallback\0").map(|sym| *sym); + let vaSetInfoCallback = __library.get(b"vaSetInfoCallback\0").map(|sym| *sym); + let vaDisplayIsValid = __library.get(b"vaDisplayIsValid\0").map(|sym| *sym); + let vaSetDriverName = __library.get(b"vaSetDriverName\0").map(|sym| *sym); + let vaInitialize = __library.get(b"vaInitialize\0").map(|sym| *sym); + let vaTerminate = __library.get(b"vaTerminate\0").map(|sym| *sym); + let vaQueryVendorString = __library.get(b"vaQueryVendorString\0").map(|sym| *sym); + let vaGetLibFunc = __library.get(b"vaGetLibFunc\0").map(|sym| *sym); + let vaMaxNumProfiles = __library.get(b"vaMaxNumProfiles\0").map(|sym| *sym); + let vaMaxNumEntrypoints = __library.get(b"vaMaxNumEntrypoints\0").map(|sym| *sym); + let vaMaxNumConfigAttributes = __library.get(b"vaMaxNumConfigAttributes\0").map(|sym| *sym); + let vaQueryConfigProfiles = __library.get(b"vaQueryConfigProfiles\0").map(|sym| *sym); + let vaQueryConfigEntrypoints = __library.get(b"vaQueryConfigEntrypoints\0").map(|sym| *sym); + let vaGetConfigAttributes = __library.get(b"vaGetConfigAttributes\0").map(|sym| *sym); + let vaCreateConfig = __library.get(b"vaCreateConfig\0").map(|sym| *sym); + let vaDestroyConfig = __library.get(b"vaDestroyConfig\0").map(|sym| *sym); + let vaQueryConfigAttributes = __library.get(b"vaQueryConfigAttributes\0").map(|sym| *sym); + let vaQuerySurfaceAttributes = __library.get(b"vaQuerySurfaceAttributes\0").map(|sym| *sym); + let vaCreateSurfaces = __library.get(b"vaCreateSurfaces\0").map(|sym| *sym); + let vaDestroySurfaces = __library.get(b"vaDestroySurfaces\0").map(|sym| *sym); + let vaCreateContext = __library.get(b"vaCreateContext\0").map(|sym| *sym); + let vaDestroyContext = __library.get(b"vaDestroyContext\0").map(|sym| *sym); + let vaCreateMFContext = __library.get(b"vaCreateMFContext\0").map(|sym| *sym); + let vaMFAddContext = __library.get(b"vaMFAddContext\0").map(|sym| *sym); + let vaMFReleaseContext = __library.get(b"vaMFReleaseContext\0").map(|sym| *sym); + let vaQueryProcessingRate = __library.get(b"vaQueryProcessingRate\0").map(|sym| *sym); + let vaCreateBuffer = __library.get(b"vaCreateBuffer\0").map(|sym| *sym); + let vaCreateBuffer2 = __library.get(b"vaCreateBuffer2\0").map(|sym| *sym); + let vaBufferSetNumElements = __library.get(b"vaBufferSetNumElements\0").map(|sym| *sym); + let vaMapBuffer = __library.get(b"vaMapBuffer\0").map(|sym| *sym); + let vaMapBuffer2 = __library.get(b"vaMapBuffer2\0").map(|sym| *sym); + let vaUnmapBuffer = __library.get(b"vaUnmapBuffer\0").map(|sym| *sym); + let vaDestroyBuffer = __library.get(b"vaDestroyBuffer\0").map(|sym| *sym); + let vaAcquireBufferHandle = __library.get(b"vaAcquireBufferHandle\0").map(|sym| *sym); + let vaReleaseBufferHandle = __library.get(b"vaReleaseBufferHandle\0").map(|sym| *sym); + let vaExportSurfaceHandle = __library.get(b"vaExportSurfaceHandle\0").map(|sym| *sym); + let vaBeginPicture = __library.get(b"vaBeginPicture\0").map(|sym| *sym); + let vaRenderPicture = __library.get(b"vaRenderPicture\0").map(|sym| *sym); + let vaEndPicture = __library.get(b"vaEndPicture\0").map(|sym| *sym); + let vaMFSubmit = __library.get(b"vaMFSubmit\0").map(|sym| *sym); + let vaSyncSurface = __library.get(b"vaSyncSurface\0").map(|sym| *sym); + let vaSyncSurface2 = __library.get(b"vaSyncSurface2\0").map(|sym| *sym); + let vaQuerySurfaceStatus = __library.get(b"vaQuerySurfaceStatus\0").map(|sym| *sym); + let vaQuerySurfaceError = __library.get(b"vaQuerySurfaceError\0").map(|sym| *sym); + let vaSyncBuffer = __library.get(b"vaSyncBuffer\0").map(|sym| *sym); + let vaMaxNumImageFormats = __library.get(b"vaMaxNumImageFormats\0").map(|sym| *sym); + let vaQueryImageFormats = __library.get(b"vaQueryImageFormats\0").map(|sym| *sym); + let vaCreateImage = __library.get(b"vaCreateImage\0").map(|sym| *sym); + let vaDestroyImage = __library.get(b"vaDestroyImage\0").map(|sym| *sym); + let vaSetImagePalette = __library.get(b"vaSetImagePalette\0").map(|sym| *sym); + let vaGetImage = __library.get(b"vaGetImage\0").map(|sym| *sym); + let vaPutImage = __library.get(b"vaPutImage\0").map(|sym| *sym); + let vaDeriveImage = __library.get(b"vaDeriveImage\0").map(|sym| *sym); + let vaMaxNumSubpictureFormats = __library.get(b"vaMaxNumSubpictureFormats\0").map(|sym| *sym); + let vaQuerySubpictureFormats = __library.get(b"vaQuerySubpictureFormats\0").map(|sym| *sym); + let vaCreateSubpicture = __library.get(b"vaCreateSubpicture\0").map(|sym| *sym); + let vaDestroySubpicture = __library.get(b"vaDestroySubpicture\0").map(|sym| *sym); + let vaSetSubpictureImage = __library.get(b"vaSetSubpictureImage\0").map(|sym| *sym); + let vaSetSubpictureChromakey = __library.get(b"vaSetSubpictureChromakey\0").map(|sym| *sym); + let vaSetSubpictureGlobalAlpha = __library.get(b"vaSetSubpictureGlobalAlpha\0").map(|sym| *sym); + let vaAssociateSubpicture = __library.get(b"vaAssociateSubpicture\0").map(|sym| *sym); + let vaDeassociateSubpicture = __library.get(b"vaDeassociateSubpicture\0").map(|sym| *sym); + let vaMaxNumDisplayAttributes = __library.get(b"vaMaxNumDisplayAttributes\0").map(|sym| *sym); + let vaQueryDisplayAttributes = __library.get(b"vaQueryDisplayAttributes\0").map(|sym| *sym); + let vaGetDisplayAttributes = __library.get(b"vaGetDisplayAttributes\0").map(|sym| *sym); + let vaSetDisplayAttributes = __library.get(b"vaSetDisplayAttributes\0").map(|sym| *sym); + let vaCopy = __library.get(b"vaCopy\0").map(|sym| *sym); + let vaQueryVideoProcFilters = __library.get(b"vaQueryVideoProcFilters\0").map(|sym| *sym); + let vaQueryVideoProcFilterCaps = __library.get(b"vaQueryVideoProcFilterCaps\0").map(|sym| *sym); + let vaQueryVideoProcPipelineCaps = __library.get(b"vaQueryVideoProcPipelineCaps\0").map(|sym| *sym); + let vaCreateProtectedSession = __library.get(b"vaCreateProtectedSession\0").map(|sym| *sym); + let vaDestroyProtectedSession = __library.get(b"vaDestroyProtectedSession\0").map(|sym| *sym); + let vaAttachProtectedSession = __library.get(b"vaAttachProtectedSession\0").map(|sym| *sym); + let vaDetachProtectedSession = __library.get(b"vaDetachProtectedSession\0").map(|sym| *sym); + let vaProtectedSessionExecute = __library.get(b"vaProtectedSessionExecute\0").map(|sym| *sym); + let vaGetDisplayDRM = __library.get(b"vaGetDisplayDRM\0").map(|sym| *sym); + Ok(Va { + __library, + vaErrorStr, + vaSetErrorCallback, + vaSetInfoCallback, + vaDisplayIsValid, + vaSetDriverName, + vaInitialize, + vaTerminate, + vaQueryVendorString, + vaGetLibFunc, + vaMaxNumProfiles, + vaMaxNumEntrypoints, + vaMaxNumConfigAttributes, + vaQueryConfigProfiles, + vaQueryConfigEntrypoints, + vaGetConfigAttributes, + vaCreateConfig, + vaDestroyConfig, + vaQueryConfigAttributes, + vaQuerySurfaceAttributes, + vaCreateSurfaces, + vaDestroySurfaces, + vaCreateContext, + vaDestroyContext, + vaCreateMFContext, + vaMFAddContext, + vaMFReleaseContext, + vaQueryProcessingRate, + vaCreateBuffer, + vaCreateBuffer2, + vaBufferSetNumElements, + vaMapBuffer, + vaMapBuffer2, + vaUnmapBuffer, + vaDestroyBuffer, + vaAcquireBufferHandle, + vaReleaseBufferHandle, + vaExportSurfaceHandle, + vaBeginPicture, + vaRenderPicture, + vaEndPicture, + vaMFSubmit, + vaSyncSurface, + vaSyncSurface2, + vaQuerySurfaceStatus, + vaQuerySurfaceError, + vaSyncBuffer, + vaMaxNumImageFormats, + vaQueryImageFormats, + vaCreateImage, + vaDestroyImage, + vaSetImagePalette, + vaGetImage, + vaPutImage, + vaDeriveImage, + vaMaxNumSubpictureFormats, + vaQuerySubpictureFormats, + vaCreateSubpicture, + vaDestroySubpicture, + vaSetSubpictureImage, + vaSetSubpictureChromakey, + vaSetSubpictureGlobalAlpha, + vaAssociateSubpicture, + vaDeassociateSubpicture, + vaMaxNumDisplayAttributes, + vaQueryDisplayAttributes, + vaGetDisplayAttributes, + vaSetDisplayAttributes, + vaCopy, + vaQueryVideoProcFilters, + vaQueryVideoProcFilterCaps, + vaQueryVideoProcPipelineCaps, + vaCreateProtectedSession, + vaDestroyProtectedSession, + vaAttachProtectedSession, + vaDetachProtectedSession, + vaProtectedSessionExecute, + vaGetDisplayDRM, + }) + } + #[doc = " Returns a short english description of error_status"] + pub unsafe fn vaErrorStr(&self, error_status: VAStatus) -> *const ::std::os::raw::c_char { + (self.vaErrorStr.as_ref().expect("Expected function, got error."))(error_status) + } + #[doc = " Set the callback for error messages, or NULL for no logging.\n Returns the previous one, or NULL if it was disabled."] + pub unsafe fn vaSetErrorCallback( + &self, + dpy: VADisplay, + callback: VAMessageCallback, + user_context: *mut ::std::os::raw::c_void, + ) -> VAMessageCallback { + (self.vaSetErrorCallback.as_ref().expect("Expected function, got error."))(dpy, callback, user_context) + } + #[doc = " Set the callback for info messages, or NULL for no logging.\n Returns the previous one, or NULL if it was disabled."] + pub unsafe fn vaSetInfoCallback( + &self, + dpy: VADisplay, + callback: VAMessageCallback, + user_context: *mut ::std::os::raw::c_void, + ) -> VAMessageCallback { + (self.vaSetInfoCallback.as_ref().expect("Expected function, got error."))(dpy, callback, user_context) + } + pub unsafe fn vaDisplayIsValid(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self.vaDisplayIsValid.as_ref().expect("Expected function, got error."))(dpy) + } + #[doc = " Set the override driver name instead of queried driver driver."] + pub unsafe fn vaSetDriverName(&self, dpy: VADisplay, driver_name: *mut ::std::os::raw::c_char) -> VAStatus { + (self.vaSetDriverName.as_ref().expect("Expected function, got error."))(dpy, driver_name) + } + #[doc = " Initialize the library"] + pub unsafe fn vaInitialize( + &self, + dpy: VADisplay, + major_version: *mut ::std::os::raw::c_int, + minor_version: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self.vaInitialize.as_ref().expect("Expected function, got error."))(dpy, major_version, minor_version) + } + #[doc = " After this call, all library internal resources will be cleaned up"] + pub unsafe fn vaTerminate(&self, dpy: VADisplay) -> VAStatus { + (self.vaTerminate.as_ref().expect("Expected function, got error."))(dpy) + } + #[doc = " vaQueryVendorString returns a pointer to a zero-terminated string\n describing some aspects of the VA implemenation on a specific\n hardware accelerator. The format of the returned string is vendor\n specific and at the discretion of the implementer.\n e.g. for the Intel GMA500 implementation, an example would be:\n \"Intel GMA500 - 2.0.0.32L.0005\""] + pub unsafe fn vaQueryVendorString(&self, dpy: VADisplay) -> *const ::std::os::raw::c_char { + (self + .vaQueryVendorString + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Return a function pointer given a function name in the library.\n This allows private interfaces into the library"] + pub unsafe fn vaGetLibFunc(&self, dpy: VADisplay, func: *const ::std::os::raw::c_char) -> VAPrivFunc { + (self.vaGetLibFunc.as_ref().expect("Expected function, got error."))(dpy, func) + } + #[doc = " Get maximum number of profiles supported by the implementation"] + pub unsafe fn vaMaxNumProfiles(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self.vaMaxNumProfiles.as_ref().expect("Expected function, got error."))(dpy) + } + #[doc = " Get maximum number of entrypoints supported by the implementation"] + pub unsafe fn vaMaxNumEntrypoints(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self + .vaMaxNumEntrypoints + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Get maximum number of attributs supported by the implementation"] + pub unsafe fn vaMaxNumConfigAttributes(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self + .vaMaxNumConfigAttributes + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Query supported profiles\n The caller must provide a \"profile_list\" array that can hold at\n least vaMaxNumProfile() entries. The actual number of profiles\n returned in \"profile_list\" is returned in \"num_profile\"."] + pub unsafe fn vaQueryConfigProfiles( + &self, + dpy: VADisplay, + profile_list: *mut VAProfile::Type, + num_profiles: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaQueryConfigProfiles + .as_ref() + .expect("Expected function, got error."))(dpy, profile_list, num_profiles) + } + #[doc = " Query supported entrypoints for a given profile\n The caller must provide an \"entrypoint_list\" array that can hold at\n least vaMaxNumEntrypoints() entries. The actual number of entrypoints\n returned in \"entrypoint_list\" is returned in \"num_entrypoints\"."] + pub unsafe fn vaQueryConfigEntrypoints( + &self, + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint_list: *mut VAEntrypoint::Type, + num_entrypoints: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaQueryConfigEntrypoints + .as_ref() + .expect("Expected function, got error."))(dpy, profile, entrypoint_list, num_entrypoints) + } + #[doc = " Get attributes for a given profile/entrypoint pair\n The caller must provide an \"attrib_list\" with all attributes to be\n retrieved. Upon return, the attributes in \"attrib_list\" have been\n updated with their value. Unknown attributes or attributes that are\n not supported for the given profile/entrypoint pair will have their\n value set to VA_ATTRIB_NOT_SUPPORTED"] + pub unsafe fn vaGetConfigAttributes( + &self, + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint: VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaGetConfigAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, profile, entrypoint, attrib_list, num_attribs) + } + #[doc = " Create a configuration for the video decode/encode/processing pipeline\n it passes in the attribute list that specifies the attributes it cares\n about, with the rest taking default values."] + pub unsafe fn vaCreateConfig( + &self, + dpy: VADisplay, + profile: VAProfile::Type, + entrypoint: VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: ::std::os::raw::c_int, + config_id: *mut VAConfigID, + ) -> VAStatus { + (self.vaCreateConfig.as_ref().expect("Expected function, got error."))( + dpy, + profile, + entrypoint, + attrib_list, + num_attribs, + config_id, + ) + } + #[doc = " Free resources associdated with a given config"] + pub unsafe fn vaDestroyConfig(&self, dpy: VADisplay, config_id: VAConfigID) -> VAStatus { + (self.vaDestroyConfig.as_ref().expect("Expected function, got error."))(dpy, config_id) + } + #[doc = " Query all attributes for a given configuration\n The profile of the configuration is returned in \"profile\"\n The entrypoint of the configuration is returned in \"entrypoint\"\n The caller must provide an \"attrib_list\" array that can hold at least\n vaMaxNumConfigAttributes() entries. The actual number of attributes\n returned in \"attrib_list\" is returned in \"num_attribs\""] + pub unsafe fn vaQueryConfigAttributes( + &self, + dpy: VADisplay, + config_id: VAConfigID, + profile: *mut VAProfile::Type, + entrypoint: *mut VAEntrypoint::Type, + attrib_list: *mut VAConfigAttrib, + num_attribs: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaQueryConfigAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, config_id, profile, entrypoint, attrib_list, num_attribs) + } + #[doc = " \\brief Queries surface attributes for the supplied config.\n\n This function queries for all supported attributes for the\n supplied VA \\c config. In particular, if the underlying hardware\n supports the creation of VA surfaces in various formats, then\n this function will enumerate all pixel formats that are supported.\n\n The \\c attrib_list array is allocated by the user and \\c\n num_attribs shall be initialized to the number of allocated\n elements in that array. Upon successful return, the actual number\n of attributes will be overwritten into \\c num_attribs. Otherwise,\n \\c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and \\c num_attribs\n is adjusted to the number of elements that would be returned if\n enough space was available.\n\n Note: it is perfectly valid to pass NULL to the \\c attrib_list\n argument when vaQuerySurfaceAttributes() is used to determine the\n actual number of elements that need to be allocated.\n\n @param[in] dpy the VA display\n @param[in] config the config identifying a codec or a video\n processing pipeline\n @param[out] attrib_list the output array of #VASurfaceAttrib elements\n @param[in,out] num_attribs the number of elements allocated on\n input, the number of elements actually filled in output"] + pub unsafe fn vaQuerySurfaceAttributes( + &self, + dpy: VADisplay, + config: VAConfigID, + attrib_list: *mut VASurfaceAttrib, + num_attribs: *mut ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaQuerySurfaceAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, config, attrib_list, num_attribs) + } + #[doc = " \\brief Creates an array of surfaces\n\n Creates an array of surfaces. The optional list of attributes shall\n be constructed based on what the underlying hardware could expose\n through vaQuerySurfaceAttributes().\n\n @param[in] dpy the VA display\n @param[in] format the desired surface format. See \\c VA_RT_FORMAT_*\n @param[in] width the surface width\n @param[in] height the surface height\n @param[out] surfaces the array of newly created surfaces\n @param[in] num_surfaces the number of surfaces to create\n @param[in] attrib_list the list of (optional) attributes, or \\c NULL\n @param[in] num_attribs the number of attributes supplied in\n \\c attrib_list, or zero"] + pub unsafe fn vaCreateSurfaces( + &self, + dpy: VADisplay, + format: ::std::os::raw::c_uint, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_uint, + attrib_list: *mut VASurfaceAttrib, + num_attribs: ::std::os::raw::c_uint, + ) -> VAStatus { + (self.vaCreateSurfaces.as_ref().expect("Expected function, got error."))( + dpy, + format, + width, + height, + surfaces, + num_surfaces, + attrib_list, + num_attribs, + ) + } + #[doc = " vaDestroySurfaces - Destroy resources associated with surfaces.\n Surfaces can only be destroyed after all contexts using these surfaces have been\n destroyed.\n dpy: display\n surfaces: array of surfaces to destroy\n num_surfaces: number of surfaces in the array to be destroyed."] + pub unsafe fn vaDestroySurfaces( + &self, + dpy: VADisplay, + surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + ) -> VAStatus { + (self.vaDestroySurfaces.as_ref().expect("Expected function, got error."))(dpy, surfaces, num_surfaces) + } + #[doc = " vaCreateContext - Create a context\n dpy: display\n config_id: configuration for the context\n picture_width: coded picture width\n picture_height: coded picture height\n flag: any combination of the following:\n VA_PROGRESSIVE (only progressive frame pictures in the sequence when set)\n render_targets: a hint for render targets (surfaces) tied to the context\n num_render_targets: number of render targets in the above array\n context: created context id upon return"] + pub unsafe fn vaCreateContext( + &self, + dpy: VADisplay, + config_id: VAConfigID, + picture_width: ::std::os::raw::c_int, + picture_height: ::std::os::raw::c_int, + flag: ::std::os::raw::c_int, + render_targets: *mut VASurfaceID, + num_render_targets: ::std::os::raw::c_int, + context: *mut VAContextID, + ) -> VAStatus { + (self.vaCreateContext.as_ref().expect("Expected function, got error."))( + dpy, + config_id, + picture_width, + picture_height, + flag, + render_targets, + num_render_targets, + context, + ) + } + #[doc = " vaDestroyContext - Destroy a context\n dpy: display\n context: context to be destroyed"] + pub unsafe fn vaDestroyContext(&self, dpy: VADisplay, context: VAContextID) -> VAStatus { + (self.vaDestroyContext.as_ref().expect("Expected function, got error."))(dpy, context) + } + #[doc = " vaCreateMFContext - Create a multi-frame context\n interface encapsulating common for all streams memory objects and structures\n required for single GPU task submission from several VAContextID's.\n Allocation: This call only creates an instance, doesn't allocate any additional memory.\n Support identification: Application can identify multi-frame feature support by ability\n to create multi-frame context. If driver supports multi-frame - call successful,\n mf_context != NULL and VAStatus = VA_STATUS_SUCCESS, otherwise if multi-frame processing\n not supported driver returns VA_STATUS_ERROR_UNIMPLEMENTED and mf_context = NULL.\n return values:\n VA_STATUS_SUCCESS - operation successful.\n VA_STATUS_ERROR_UNIMPLEMENTED - no support for multi-frame.\n dpy: display adapter.\n mf_context: Multi-Frame context encapsulating all associated context\n for multi-frame submission."] + pub unsafe fn vaCreateMFContext(&self, dpy: VADisplay, mf_context: *mut VAMFContextID) -> VAStatus { + (self.vaCreateMFContext.as_ref().expect("Expected function, got error."))(dpy, mf_context) + } + #[doc = " vaMFAddContext - Provide ability to associate each context used for\n Multi-Frame submission and common Multi-Frame context.\n Try to add context to understand if it is supported.\n Allocation: this call allocates and/or reallocates all memory objects\n common for all contexts associated with particular Multi-Frame context.\n All memory required for each context(pixel buffers, internal driver\n buffers required for processing) allocated during standard vaCreateContext call for each context.\n Runtime dependency - if current implementation doesn't allow to run different entry points/profile,\n first context added will set entry point/profile for whole Multi-Frame context,\n all other entry points and profiles can be rejected to be added.\n Return values:\n VA_STATUS_SUCCESS - operation successful, context was added.\n VA_STATUS_ERROR_OPERATION_FAILED - something unexpected happened - application have to close\n current mf_context and associated contexts and start working with new ones.\n VA_STATUS_ERROR_INVALID_CONTEXT - ContextID is invalid, means:\n 1 - mf_context is not valid context or\n 2 - driver can't suport different VAEntrypoint or VAProfile simultaneosly\n and current context contradicts with previously added, application can continue with current mf_context\n and other contexts passed this call, rejected context can continue work in stand-alone\n mode or other mf_context.\n VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT - particular context being added was created with with\n unsupported VAEntrypoint. Application can continue with current mf_context\n and other contexts passed this call, rejected context can continue work in stand-alone\n mode.\n VA_STATUS_ERROR_UNSUPPORTED_PROFILE - Current context with Particular VAEntrypoint is supported\n but VAProfile is not supported. Application can continue with current mf_context\n and other contexts passed this call, rejected context can continue work in stand-alone\n mode.\n dpy: display adapter.\n context: context being associated with Multi-Frame context.\n mf_context: - multi-frame context used to associate contexts for multi-frame submission."] + pub unsafe fn vaMFAddContext(&self, dpy: VADisplay, mf_context: VAMFContextID, context: VAContextID) -> VAStatus { + (self.vaMFAddContext.as_ref().expect("Expected function, got error."))(dpy, mf_context, context) + } + #[doc = " vaMFReleaseContext - Removes context from multi-frame and\n association with multi-frame context.\n After association removed vaEndPicture will submit tasks, but not vaMFSubmit.\n Return values:\n VA_STATUS_SUCCESS - operation successful, context was removed.\n VA_STATUS_ERROR_OPERATION_FAILED - something unexpected happened.\n application need to destroy this VAMFContextID and all assotiated VAContextID\n dpy: display\n mf_context: VAMFContextID where context is added\n context: VAContextID to be added"] + pub unsafe fn vaMFReleaseContext( + &self, + dpy: VADisplay, + mf_context: VAMFContextID, + context: VAContextID, + ) -> VAStatus { + (self.vaMFReleaseContext.as_ref().expect("Expected function, got error."))(dpy, mf_context, context) + } + #[doc = " \\brief Queries processing rate for the supplied config.\n\n This function queries the processing rate based on parameters in\n \\c proc_buf for the given \\c config. Upon successful return, the processing\n rate value will be stored in \\c processing_rate. Processing rate is\n specified as the number of macroblocks/CTU per second.\n\n If NULL is passed to the \\c proc_buf, the default processing rate for the\n given configuration will be returned.\n\n @param[in] dpy the VA display\n @param[in] config the config identifying a codec or a video\n processing pipeline\n @param[in] proc_buf the buffer that contains the parameters for\neither the encode or decode processing rate\n @param[out] processing_rate processing rate in number of macroblocks per\nsecond constrained by parameters specified in proc_buf\n"] + pub unsafe fn vaQueryProcessingRate( + &self, + dpy: VADisplay, + config: VAConfigID, + proc_buf: *mut VAProcessingRateParameter, + processing_rate: *mut ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaQueryProcessingRate + .as_ref() + .expect("Expected function, got error."))(dpy, config, proc_buf, processing_rate) + } + #[doc = " Creates a buffer for \"num_elements\" elements of \"size\" bytes and\n initalize with \"data\".\n if \"data\" is null, then the contents of the buffer data store\n are undefined.\n Basically there are two ways to get buffer data to the server side. One is\n to call vaCreateBuffer() with a non-null \"data\", which results the data being\n copied to the data store on the server side. A different method that\n eliminates this copy is to pass null as \"data\" when calling vaCreateBuffer(),\n and then use vaMapBuffer() to map the data store from the server side to the\n client address space for access.\n The user must call vaDestroyBuffer() to destroy a buffer.\n Note: image buffers are created by the library, not the client. Please see\n vaCreateImage on how image buffers are managed."] + pub unsafe fn vaCreateBuffer( + &self, + dpy: VADisplay, + context: VAContextID, + type_: VABufferType::Type, + size: ::std::os::raw::c_uint, + num_elements: ::std::os::raw::c_uint, + data: *mut ::std::os::raw::c_void, + buf_id: *mut VABufferID, + ) -> VAStatus { + (self.vaCreateBuffer.as_ref().expect("Expected function, got error."))( + dpy, + context, + type_, + size, + num_elements, + data, + buf_id, + ) + } + #[doc = " Create a buffer for given width & height get unit_size, pitch, buf_id for 2D buffer\n for permb qp buffer, it will return unit_size for one MB or LCU and the pitch for alignments\n can call vaMapBuffer with this Buffer ID to get virtual address.\n e.g. AVC 1080P encode, 1920x1088, the size in MB is 120x68,but inside driver,\n maybe it should align with 256, and one byte present one Qp.so, call the function.\n then get unit_size = 1, pitch = 256. call vaMapBuffer to get the virtual address (pBuf).\n then read write the memory like 2D. the size is 256x68, application can only use 120x68\n pBuf + 256 is the start of next line.\n different driver implementation maybe return different unit_size and pitch"] + pub unsafe fn vaCreateBuffer2( + &self, + dpy: VADisplay, + context: VAContextID, + type_: VABufferType::Type, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + unit_size: *mut ::std::os::raw::c_uint, + pitch: *mut ::std::os::raw::c_uint, + buf_id: *mut VABufferID, + ) -> VAStatus { + (self.vaCreateBuffer2.as_ref().expect("Expected function, got error."))( + dpy, context, type_, width, height, unit_size, pitch, buf_id, + ) + } + #[doc = " Convey to the server how many valid elements are in the buffer.\n e.g. if multiple slice parameters are being held in a single buffer,\n this will communicate to the server the number of slice parameters\n that are valid in the buffer."] + pub unsafe fn vaBufferSetNumElements( + &self, + dpy: VADisplay, + buf_id: VABufferID, + num_elements: ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaBufferSetNumElements + .as_ref() + .expect("Expected function, got error."))(dpy, buf_id, num_elements) + } + #[doc = " Map data store of the buffer into the client's address space\n vaCreateBuffer() needs to be called with \"data\" set to NULL before\n calling vaMapBuffer()\n\n if buffer type is VAEncCodedBufferType, pbuf points to link-list of\n VACodedBufferSegment, and the list is terminated if \"next\" is NULL"] + pub unsafe fn vaMapBuffer( + &self, + dpy: VADisplay, + buf_id: VABufferID, + pbuf: *mut *mut ::std::os::raw::c_void, + ) -> VAStatus { + (self.vaMapBuffer.as_ref().expect("Expected function, got error."))(dpy, buf_id, pbuf) + } + pub unsafe fn vaMapBuffer2( + &self, + dpy: VADisplay, + buf_id: VABufferID, + pbuf: *mut *mut ::std::os::raw::c_void, + flags: u32, + ) -> VAStatus { + (self.vaMapBuffer2.as_ref().expect("Expected function, got error."))(dpy, buf_id, pbuf, flags) + } + #[doc = " After client making changes to a mapped data store, it needs to\n \"Unmap\" it to let the server know that the data is ready to be\n consumed by the server"] + pub unsafe fn vaUnmapBuffer(&self, dpy: VADisplay, buf_id: VABufferID) -> VAStatus { + (self.vaUnmapBuffer.as_ref().expect("Expected function, got error."))(dpy, buf_id) + } + #[doc = " After this call, the buffer is deleted and this buffer_id is no longer valid\n\n A buffer can be re-used and sent to the server by another Begin/Render/End\n sequence if vaDestroyBuffer() is not called with this buffer.\n\n Note re-using a shared buffer (e.g. a slice data buffer) between the host and the\n hardware accelerator can result in performance dropping."] + pub unsafe fn vaDestroyBuffer(&self, dpy: VADisplay, buffer_id: VABufferID) -> VAStatus { + (self.vaDestroyBuffer.as_ref().expect("Expected function, got error."))(dpy, buffer_id) + } + #[doc = " \\brief Acquires buffer handle for external API usage\n\n Locks the VA buffer object \\ref buf_id for external API usage like\n EGL or OpenCL (OCL). This function is a synchronization point. This\n means that any pending operation is guaranteed to be completed\n prior to returning from the function.\n\n If the referenced VA buffer object is the backing store of a VA\n surface, then this function acts as if vaSyncSurface() on the\n parent surface was called first.\n\n The \\ref VABufferInfo argument shall be zero'ed on input. On\n successful output, the data structure is filled in with all the\n necessary buffer level implementation details like handle, type,\n memory type and memory size.\n\n Note: the external API implementation, or the application, can\n express the memory types it is interested in by filling in the \\ref\n mem_type field accordingly. On successful output, the memory type\n that fits best the request and that was used is updated in the \\ref\n VABufferInfo data structure. If none of the supplied memory types\n is supported, then a \\ref VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE\n error is returned.\n\n The \\ref VABufferInfo data is valid until vaReleaseBufferHandle()\n is called. Besides, no additional operation is allowed on any of\n the buffer parent object until vaReleaseBufferHandle() is called.\n e.g. decoding into a VA surface backed with the supplied VA buffer\n object \\ref buf_id would fail with a \\ref VA_STATUS_ERROR_SURFACE_BUSY\n error.\n\n Possible errors:\n - \\ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation\n does not support this interface\n - \\ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied\n - \\ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied\n - \\ref VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE: the implementation\n does not support exporting buffers of the specified type\n - \\ref VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE: none of the requested\n memory types in \\ref VABufferInfo.mem_type was supported\n\n @param[in] dpy the VA display\n @param[in] buf_id the VA buffer\n @param[in,out] buf_info the associated VA buffer information\n @return VA_STATUS_SUCCESS if successful"] + pub unsafe fn vaAcquireBufferHandle( + &self, + dpy: VADisplay, + buf_id: VABufferID, + buf_info: *mut VABufferInfo, + ) -> VAStatus { + (self + .vaAcquireBufferHandle + .as_ref() + .expect("Expected function, got error."))(dpy, buf_id, buf_info) + } + #[doc = " \\brief Releases buffer after usage from external API\n\n Unlocks the VA buffer object \\ref buf_id from external API usage like\n EGL or OpenCL (OCL). This function is a synchronization point. This\n means that any pending operation is guaranteed to be completed\n prior to returning from the function.\n\n The \\ref VABufferInfo argument shall point to the original data\n structure that was obtained from vaAcquireBufferHandle(), unaltered.\n This is necessary so that the VA driver implementation could\n deallocate any resources that were needed.\n\n In any case, returning from this function invalidates any contents\n in \\ref VABufferInfo. i.e. the underlyng buffer handle is no longer\n valid. Therefore, VA driver implementations are free to reset this\n data structure to safe defaults.\n\n Possible errors:\n - \\ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation\n does not support this interface\n - \\ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied\n - \\ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied\n - \\ref VA_STATUS_ERROR_UNSUPPORTED_BUFFERTYPE: the implementation\n does not support exporting buffers of the specified type\n\n @param[in] dpy the VA display\n @param[in] buf_id the VA buffer\n @return VA_STATUS_SUCCESS if successful"] + pub unsafe fn vaReleaseBufferHandle(&self, dpy: VADisplay, buf_id: VABufferID) -> VAStatus { + (self + .vaReleaseBufferHandle + .as_ref() + .expect("Expected function, got error."))(dpy, buf_id) + } + #[doc = " \\brief Export a handle to a surface for use with an external API\n\n The exported handles are owned by the caller, and the caller is\n responsible for freeing them when no longer needed (e.g. by closing\n DRM PRIME file descriptors).\n\n This does not perform any synchronisation. If the contents of the\n surface will be read, vaSyncSurface() must be called before doing so.\n If the contents of the surface are written, then all operations must\n be completed externally before using the surface again by via VA-API\n functions.\n\n @param[in] dpy VA display.\n @param[in] surface_id Surface to export.\n @param[in] mem_type Memory type to export to.\n @param[in] flags Combination of flags to apply\n (VA_EXPORT_SURFACE_*).\n @param[out] descriptor Pointer to the descriptor structure to fill\n with the handle details. The type of this structure depends on\n the value of mem_type.\n\n @return Status code:\n - VA_STATUS_SUCCESS: Success.\n - VA_STATUS_ERROR_INVALID_DISPLAY: The display is not valid.\n - VA_STATUS_ERROR_UNIMPLEMENTED: The driver does not implement\n this interface.\n - VA_STATUS_ERROR_INVALID_SURFACE: The surface is not valid, or\n the surface is not exportable in the specified way.\n - VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE: The driver does not\n support exporting surfaces to the specified memory type."] + pub unsafe fn vaExportSurfaceHandle( + &self, + dpy: VADisplay, + surface_id: VASurfaceID, + mem_type: u32, + flags: u32, + descriptor: *mut ::std::os::raw::c_void, + ) -> VAStatus { + (self + .vaExportSurfaceHandle + .as_ref() + .expect("Expected function, got error."))(dpy, surface_id, mem_type, flags, descriptor) + } + #[doc = " Get ready for a video pipeline\n - decode a picture to a target surface\n - encode a picture from a target surface\n - process a picture to a target surface"] + pub unsafe fn vaBeginPicture(&self, dpy: VADisplay, context: VAContextID, render_target: VASurfaceID) -> VAStatus { + (self.vaBeginPicture.as_ref().expect("Expected function, got error."))(dpy, context, render_target) + } + #[doc = " Send video decode, encode or processing buffers to the server."] + pub unsafe fn vaRenderPicture( + &self, + dpy: VADisplay, + context: VAContextID, + buffers: *mut VABufferID, + num_buffers: ::std::os::raw::c_int, + ) -> VAStatus { + (self.vaRenderPicture.as_ref().expect("Expected function, got error."))(dpy, context, buffers, num_buffers) + } + #[doc = " Make the end of rendering for a picture.\n The server should start processing all pending operations for this\n surface. This call is non-blocking. The client can start another\n Begin/Render/End sequence on a different render target.\n if VAContextID used in this function previously successfully passed\n vaMFAddContext call, real processing will be started during vaMFSubmit"] + pub unsafe fn vaEndPicture(&self, dpy: VADisplay, context: VAContextID) -> VAStatus { + (self.vaEndPicture.as_ref().expect("Expected function, got error."))(dpy, context) + } + #[doc = " Make the end of rendering for a pictures in contexts passed with submission.\n The server should start processing all pending operations for contexts.\n All contexts passed should be associated through vaMFAddContext\n and call sequence Begin/Render/End performed.\n This call is non-blocking. The client can start another\n Begin/Render/End/vaMFSubmit sequence on a different render targets.\n Return values:\n VA_STATUS_SUCCESS - operation successful, context was removed.\n VA_STATUS_ERROR_INVALID_CONTEXT - mf_context or one of contexts are invalid\n due to mf_context not created or one of contexts not assotiated with mf_context\n through vaAddContext.\n VA_STATUS_ERROR_INVALID_PARAMETER - one of context has not submitted it's frame\n through vaBeginPicture vaRenderPicture vaEndPicture call sequence.\n dpy: display\n mf_context: Multi-Frame context\n contexts: list of contexts submitting their tasks for multi-frame operation.\n num_contexts: number of passed contexts."] + pub unsafe fn vaMFSubmit( + &self, + dpy: VADisplay, + mf_context: VAMFContextID, + contexts: *mut VAContextID, + num_contexts: ::std::os::raw::c_int, + ) -> VAStatus { + (self.vaMFSubmit.as_ref().expect("Expected function, got error."))(dpy, mf_context, contexts, num_contexts) + } + #[doc = " This function blocks until all pending operations on the render target\n have been completed. Upon return it is safe to use the render target for a\n different picture."] + pub unsafe fn vaSyncSurface(&self, dpy: VADisplay, render_target: VASurfaceID) -> VAStatus { + (self.vaSyncSurface.as_ref().expect("Expected function, got error."))(dpy, render_target) + } + #[doc = " \\brief Synchronizes pending operations associated with the supplied surface.\n\n This function blocks during specified timeout (in nanoseconds) until\n all pending operations on the render target have been completed.\n If timeout is zero, the function returns immediately.\n\n Possible errors:\n - \\ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation\n does not support this interface\n - \\ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied\n - \\ref VA_STATUS_ERROR_INVALID_SURFACE: an invalid surface was supplied\n - \\ref VA_STATUS_ERROR_TIMEDOUT: synchronization is still in progress,\n client should call the function again to complete synchronization\n\n @param[in] dpy the VA display\n @param[in] surface the surface for which synchronization is performed\n @param[in] timeout_ns the timeout in nanoseconds\n"] + pub unsafe fn vaSyncSurface2(&self, dpy: VADisplay, surface: VASurfaceID, timeout_ns: u64) -> VAStatus { + (self.vaSyncSurface2.as_ref().expect("Expected function, got error."))(dpy, surface, timeout_ns) + } + #[doc = " Find out any pending ops on the render target"] + pub unsafe fn vaQuerySurfaceStatus( + &self, + dpy: VADisplay, + render_target: VASurfaceID, + status: *mut VASurfaceStatus::Type, + ) -> VAStatus { + (self + .vaQuerySurfaceStatus + .as_ref() + .expect("Expected function, got error."))(dpy, render_target, status) + } + #[doc = " After the application gets VA_STATUS_ERROR_DECODING_ERROR after calling vaSyncSurface(),\n it can call vaQuerySurfaceError to find out further details on the particular error.\n VA_STATUS_ERROR_DECODING_ERROR should be passed in as \"error_status\".\n\n After the applications get VA_STATUS_HW_BUSY or VA_STATUS_SUCCESSFULL from vaSyncSurface(),\n it still can call vaQuerySurfaceError to find out further details to know if has real hw reset\n happened on this surface since umd and kmd could recover the context from reset with success in sometimes.\n VA_STATUS_HW_BUSY or VA_STATUS_SUCCESSFULL also could be passed in as \"error_status\".\n\n Upon the return, error_info will point to an array of _VASurfaceDecodeMBErrors structure,\n which is allocated and filled by libVA with detailed information on the VADecodeErrorType.\n The array is terminated if \"status==-1\" is detected."] + pub unsafe fn vaQuerySurfaceError( + &self, + dpy: VADisplay, + surface: VASurfaceID, + error_status: VAStatus, + error_info: *mut *mut ::std::os::raw::c_void, + ) -> VAStatus { + (self + .vaQuerySurfaceError + .as_ref() + .expect("Expected function, got error."))(dpy, surface, error_status, error_info) + } + #[doc = " \\brief Synchronizes pending operations associated with the supplied buffer.\n\n This function blocks during specified timeout (in nanoseconds) until\n all pending operations on the supplied buffer have been completed.\n If timeout is zero, the function returns immediately.\n\n Possible errors:\n - \\ref VA_STATUS_ERROR_UNIMPLEMENTED: the VA driver implementation\n does not support this interface\n - \\ref VA_STATUS_ERROR_INVALID_DISPLAY: an invalid display was supplied\n - \\ref VA_STATUS_ERROR_INVALID_BUFFER: an invalid buffer was supplied\n - \\ref VA_STATUS_ERROR_TIMEDOUT: synchronization is still in progress,\n client should call the function again to complete synchronization\n\n @param[in] dpy the VA display\n @param[in] buf_id the buffer for which synchronization is performed\n @param[in] timeout_ns the timeout in nanoseconds\n"] + pub unsafe fn vaSyncBuffer(&self, dpy: VADisplay, buf_id: VABufferID, timeout_ns: u64) -> VAStatus { + (self.vaSyncBuffer.as_ref().expect("Expected function, got error."))(dpy, buf_id, timeout_ns) + } + #[doc = " Get maximum number of image formats supported by the implementation"] + pub unsafe fn vaMaxNumImageFormats(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self + .vaMaxNumImageFormats + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Query supported image formats\n The caller must provide a \"format_list\" array that can hold at\n least vaMaxNumImageFormats() entries. The actual number of formats\n returned in \"format_list\" is returned in \"num_formats\"."] + pub unsafe fn vaQueryImageFormats( + &self, + dpy: VADisplay, + format_list: *mut VAImageFormat, + num_formats: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaQueryImageFormats + .as_ref() + .expect("Expected function, got error."))(dpy, format_list, num_formats) + } + #[doc = " Create a VAImage structure\n The width and height fields returned in the VAImage structure may get\n enlarged for some YUV formats. Upon return from this function,\n image->buf has been created and proper storage allocated by the library.\n The client can access the image through the Map/Unmap calls."] + pub unsafe fn vaCreateImage( + &self, + dpy: VADisplay, + format: *mut VAImageFormat, + width: ::std::os::raw::c_int, + height: ::std::os::raw::c_int, + image: *mut VAImage, + ) -> VAStatus { + (self.vaCreateImage.as_ref().expect("Expected function, got error."))(dpy, format, width, height, image) + } + #[doc = " Should call DestroyImage before destroying the surface it is bound to"] + pub unsafe fn vaDestroyImage(&self, dpy: VADisplay, image: VAImageID) -> VAStatus { + (self.vaDestroyImage.as_ref().expect("Expected function, got error."))(dpy, image) + } + pub unsafe fn vaSetImagePalette( + &self, + dpy: VADisplay, + image: VAImageID, + palette: *mut ::std::os::raw::c_uchar, + ) -> VAStatus { + (self.vaSetImagePalette.as_ref().expect("Expected function, got error."))(dpy, image, palette) + } + #[doc = " Retrive surface data into a VAImage\n Image must be in a format supported by the implementation"] + pub unsafe fn vaGetImage( + &self, + dpy: VADisplay, + surface: VASurfaceID, + x: ::std::os::raw::c_int, + y: ::std::os::raw::c_int, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + image: VAImageID, + ) -> VAStatus { + (self.vaGetImage.as_ref().expect("Expected function, got error."))(dpy, surface, x, y, width, height, image) + } + #[doc = " Copy data from a VAImage to a surface\n Image must be in a format supported by the implementation\n Returns a VA_STATUS_ERROR_SURFACE_BUSY if the surface\n shouldn't be rendered into when this is called"] + pub unsafe fn vaPutImage( + &self, + dpy: VADisplay, + surface: VASurfaceID, + image: VAImageID, + src_x: ::std::os::raw::c_int, + src_y: ::std::os::raw::c_int, + src_width: ::std::os::raw::c_uint, + src_height: ::std::os::raw::c_uint, + dest_x: ::std::os::raw::c_int, + dest_y: ::std::os::raw::c_int, + dest_width: ::std::os::raw::c_uint, + dest_height: ::std::os::raw::c_uint, + ) -> VAStatus { + (self.vaPutImage.as_ref().expect("Expected function, got error."))( + dpy, + surface, + image, + src_x, + src_y, + src_width, + src_height, + dest_x, + dest_y, + dest_width, + dest_height, + ) + } + #[doc = " Derive an VAImage from an existing surface.\n This interface will derive a VAImage and corresponding image buffer from\n an existing VA Surface. The image buffer can then be mapped/unmapped for\n direct CPU access. This operation is only possible on implementations with\n direct rendering capabilities and internal surface formats that can be\n represented with a VAImage. When the operation is not possible this interface\n will return VA_STATUS_ERROR_OPERATION_FAILED. Clients should then fall back\n to using vaCreateImage + vaPutImage to accomplish the same task in an\n indirect manner.\n\n Implementations should only return success when the resulting image buffer\n would be useable with vaMap/Unmap.\n\n When directly accessing a surface special care must be taken to insure\n proper synchronization with the graphics hardware. Clients should call\n vaQuerySurfaceStatus to insure that a surface is not the target of concurrent\n rendering or currently being displayed by an overlay.\n\n Additionally nothing about the contents of a surface should be assumed\n following a vaPutSurface. Implementations are free to modify the surface for\n scaling or subpicture blending within a call to vaPutImage.\n\n Calls to vaPutImage or vaGetImage using the same surface from which the image\n has been derived will return VA_STATUS_ERROR_SURFACE_BUSY. vaPutImage or\n vaGetImage with other surfaces is supported.\n\n An image created with vaDeriveImage should be freed with vaDestroyImage. The\n image and image buffer structures will be destroyed; however, the underlying\n surface will remain unchanged until freed with vaDestroySurfaces."] + pub unsafe fn vaDeriveImage(&self, dpy: VADisplay, surface: VASurfaceID, image: *mut VAImage) -> VAStatus { + (self.vaDeriveImage.as_ref().expect("Expected function, got error."))(dpy, surface, image) + } + #[doc = " Get maximum number of subpicture formats supported by the implementation"] + pub unsafe fn vaMaxNumSubpictureFormats(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self + .vaMaxNumSubpictureFormats + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Query supported subpicture formats\n The caller must provide a \"format_list\" array that can hold at\n least vaMaxNumSubpictureFormats() entries. The flags arrary holds the flag\n for each format to indicate additional capabilities for that format. The actual\n number of formats returned in \"format_list\" is returned in \"num_formats\".\n flags: returned value to indicate addtional capabilities\n VA_SUBPICTURE_CHROMA_KEYING - supports chroma-keying\n VA_SUBPICTURE_GLOBAL_ALPHA - supports global alpha\n VA_SUBPICTURE_DESTINATION_IS_SCREEN_COORD - supports unscaled screen relative subpictures for On Screen Display"] + pub unsafe fn vaQuerySubpictureFormats( + &self, + dpy: VADisplay, + format_list: *mut VAImageFormat, + flags: *mut ::std::os::raw::c_uint, + num_formats: *mut ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaQuerySubpictureFormats + .as_ref() + .expect("Expected function, got error."))(dpy, format_list, flags, num_formats) + } + #[doc = " Subpictures are created with an image associated."] + pub unsafe fn vaCreateSubpicture( + &self, + dpy: VADisplay, + image: VAImageID, + subpicture: *mut VASubpictureID, + ) -> VAStatus { + (self.vaCreateSubpicture.as_ref().expect("Expected function, got error."))(dpy, image, subpicture) + } + #[doc = " Destroy the subpicture before destroying the image it is assocated to"] + pub unsafe fn vaDestroySubpicture(&self, dpy: VADisplay, subpicture: VASubpictureID) -> VAStatus { + (self + .vaDestroySubpicture + .as_ref() + .expect("Expected function, got error."))(dpy, subpicture) + } + #[doc = " Bind an image to the subpicture. This image will now be associated with\n the subpicture instead of the one at creation."] + pub unsafe fn vaSetSubpictureImage( + &self, + dpy: VADisplay, + subpicture: VASubpictureID, + image: VAImageID, + ) -> VAStatus { + (self + .vaSetSubpictureImage + .as_ref() + .expect("Expected function, got error."))(dpy, subpicture, image) + } + #[doc = " If chromakey is enabled, then the area where the source value falls within\n the chromakey [min, max] range is transparent\n The chromakey component format is the following:\n For RGB: [0:7] Red [8:15] Blue [16:23] Green\n For YUV: [0:7] V [8:15] U [16:23] Y\n The chromakey mask can be used to mask out certain components for chromakey\n comparision"] + pub unsafe fn vaSetSubpictureChromakey( + &self, + dpy: VADisplay, + subpicture: VASubpictureID, + chromakey_min: ::std::os::raw::c_uint, + chromakey_max: ::std::os::raw::c_uint, + chromakey_mask: ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaSetSubpictureChromakey + .as_ref() + .expect("Expected function, got error."))(dpy, subpicture, chromakey_min, chromakey_max, chromakey_mask) + } + #[doc = " Global alpha value is between 0 and 1. A value of 1 means fully opaque and\n a value of 0 means fully transparent. If per-pixel alpha is also specified then\n the overall alpha is per-pixel alpha multiplied by the global alpha"] + pub unsafe fn vaSetSubpictureGlobalAlpha( + &self, + dpy: VADisplay, + subpicture: VASubpictureID, + global_alpha: f32, + ) -> VAStatus { + (self + .vaSetSubpictureGlobalAlpha + .as_ref() + .expect("Expected function, got error."))(dpy, subpicture, global_alpha) + } + #[doc = " vaAssociateSubpicture associates the subpicture with target_surfaces.\n It defines the region mapping between the subpicture and the target\n surfaces through source and destination rectangles (with the same width and height).\n Both will be displayed at the next call to vaPutSurface. Additional\n associations before the call to vaPutSurface simply overrides the association."] + pub unsafe fn vaAssociateSubpicture( + &self, + dpy: VADisplay, + subpicture: VASubpictureID, + target_surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + src_x: i16, + src_y: i16, + src_width: u16, + src_height: u16, + dest_x: i16, + dest_y: i16, + dest_width: u16, + dest_height: u16, + flags: u32, + ) -> VAStatus { + (self + .vaAssociateSubpicture + .as_ref() + .expect("Expected function, got error."))( + dpy, + subpicture, + target_surfaces, + num_surfaces, + src_x, + src_y, + src_width, + src_height, + dest_x, + dest_y, + dest_width, + dest_height, + flags, + ) + } + #[doc = " vaDeassociateSubpicture removes the association of the subpicture with target_surfaces."] + pub unsafe fn vaDeassociateSubpicture( + &self, + dpy: VADisplay, + subpicture: VASubpictureID, + target_surfaces: *mut VASurfaceID, + num_surfaces: ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaDeassociateSubpicture + .as_ref() + .expect("Expected function, got error."))(dpy, subpicture, target_surfaces, num_surfaces) + } + #[doc = " Get maximum number of display attributs supported by the implementation"] + pub unsafe fn vaMaxNumDisplayAttributes(&self, dpy: VADisplay) -> ::std::os::raw::c_int { + (self + .vaMaxNumDisplayAttributes + .as_ref() + .expect("Expected function, got error."))(dpy) + } + #[doc = " Query display attributes\n The caller must provide a \"attr_list\" array that can hold at\n least vaMaxNumDisplayAttributes() entries. The actual number of attributes\n returned in \"attr_list\" is returned in \"num_attributes\"."] + pub unsafe fn vaQueryDisplayAttributes( + &self, + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: *mut ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaQueryDisplayAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, attr_list, num_attributes) + } + #[doc = " Get display attributes\n This function returns the current attribute values in \"attr_list\".\n Only attributes returned with VA_DISPLAY_ATTRIB_GETTABLE set in the \"flags\" field\n from vaQueryDisplayAttributes() can have their values retrieved."] + pub unsafe fn vaGetDisplayAttributes( + &self, + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaGetDisplayAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, attr_list, num_attributes) + } + #[doc = " Set display attributes\n Only attributes returned with VA_DISPLAY_ATTRIB_SETTABLE set in the \"flags\" field\n from vaQueryDisplayAttributes() can be set. If the attribute is not settable or\n the value is out of range, the function returns VA_STATUS_ERROR_ATTR_NOT_SUPPORTED"] + pub unsafe fn vaSetDisplayAttributes( + &self, + dpy: VADisplay, + attr_list: *mut VADisplayAttribute, + num_attributes: ::std::os::raw::c_int, + ) -> VAStatus { + (self + .vaSetDisplayAttributes + .as_ref() + .expect("Expected function, got error."))(dpy, attr_list, num_attributes) + } + #[doc = " \\brief Copies an object.\n\n Copies specified object (surface or buffer). If non-blocking copy\n is requested (VA_COPY_NONBLOCK), then need vaSyncBuffer or vaSyncSurface/vaSyncSurface2\n to sync the destination object.\n\n @param[in] dpy the VA display\n @param[in] dst Destination object to copy to\n @param[in] src Source object to copy from\n @param[in] option VA copy option\n @return VA_STATUS_SUCCESS if successful"] + pub unsafe fn vaCopy( + &self, + dpy: VADisplay, + dst: *mut VACopyObject, + src: *mut VACopyObject, + option: VACopyOption, + ) -> VAStatus { + (self.vaCopy.as_ref().expect("Expected function, got error."))(dpy, dst, src, option) + } + #[doc = " \\brief Queries video processing filters.\n\n This function returns the list of video processing filters supported\n by the driver. The \\c filters array is allocated by the user and\n \\c num_filters shall be initialized to the number of allocated\n elements in that array. Upon successful return, the actual number\n of filters will be overwritten into \\c num_filters. Otherwise,\n \\c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and \\c num_filters\n is adjusted to the number of elements that would be returned if enough\n space was available.\n\n The list of video processing filters supported by the driver shall\n be ordered in the way they can be iteratively applied. This is needed\n for both correctness, i.e. some filters would not mean anything if\n applied at the beginning of the pipeline; but also for performance\n since some filters can be applied in a single pass (e.g. noise\n reduction + deinterlacing).\n\n @param[in] dpy the VA display\n @param[in] context the video processing context\n @param[out] filters the output array of #VAProcFilterType elements\n @param[in,out] num_filters the number of elements allocated on input,\n the number of elements actually filled in on output"] + pub unsafe fn vaQueryVideoProcFilters( + &self, + dpy: VADisplay, + context: VAContextID, + filters: *mut VAProcFilterType, + num_filters: *mut ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaQueryVideoProcFilters + .as_ref() + .expect("Expected function, got error."))(dpy, context, filters, num_filters) + } + #[doc = " \\brief Queries video filter capabilities.\n\n This function returns the list of capabilities supported by the driver\n for a specific video filter. The \\c filter_caps array is allocated by\n the user and \\c num_filter_caps shall be initialized to the number\n of allocated elements in that array. Upon successful return, the\n actual number of filters will be overwritten into \\c num_filter_caps.\n Otherwise, \\c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned and\n \\c num_filter_caps is adjusted to the number of elements that would be\n returned if enough space was available.\n\n @param[in] dpy the VA display\n @param[in] context the video processing context\n @param[in] type the video filter type\n @param[out] filter_caps the output array of #VAProcFilterCap elements\n @param[in,out] num_filter_caps the number of elements allocated on input,\n the number of elements actually filled in output"] + pub unsafe fn vaQueryVideoProcFilterCaps( + &self, + dpy: VADisplay, + context: VAContextID, + type_: VAProcFilterType, + filter_caps: *mut ::std::os::raw::c_void, + num_filter_caps: *mut ::std::os::raw::c_uint, + ) -> VAStatus { + (self + .vaQueryVideoProcFilterCaps + .as_ref() + .expect("Expected function, got error."))(dpy, context, type_, filter_caps, num_filter_caps) + } + #[doc = " \\brief Queries video processing pipeline capabilities.\n\n This function returns the video processing pipeline capabilities. The\n \\c filters array defines the video processing pipeline and is an array\n of buffers holding filter parameters.\n\n Note: the #VAProcPipelineCaps structure contains user-provided arrays.\n If non-NULL, the corresponding \\c num_* fields shall be filled in on\n input with the number of elements allocated. Upon successful return,\n the actual number of elements will be overwritten into the \\c num_*\n fields. Otherwise, \\c VA_STATUS_ERROR_MAX_NUM_EXCEEDED is returned\n and \\c num_* fields are adjusted to the number of elements that would\n be returned if enough space was available.\n\n @param[in] dpy the VA display\n @param[in] context the video processing context\n @param[in] filters the array of VA buffers defining the video\n processing pipeline\n @param[in] num_filters the number of elements in filters\n @param[in,out] pipeline_caps the video processing pipeline capabilities"] + pub unsafe fn vaQueryVideoProcPipelineCaps( + &self, + dpy: VADisplay, + context: VAContextID, + filters: *mut VABufferID, + num_filters: ::std::os::raw::c_uint, + pipeline_caps: *mut VAProcPipelineCaps, + ) -> VAStatus { + (self + .vaQueryVideoProcPipelineCaps + .as_ref() + .expect("Expected function, got error."))(dpy, context, filters, num_filters, pipeline_caps) + } + #[doc = " \\brief Create a protected session\n\n Create a protected session\n\n @param[in] dpy the VA display\n @param[in] config_id configuration for the protected session\n @param[out] protected_session created protected session id upon return"] + pub unsafe fn vaCreateProtectedSession( + &self, + dpy: VADisplay, + config_id: VAConfigID, + protected_session: *mut VAProtectedSessionID, + ) -> VAStatus { + (self + .vaCreateProtectedSession + .as_ref() + .expect("Expected function, got error."))(dpy, config_id, protected_session) + } + #[doc = " \\brief Destroy a protected session\n\n Destroy a protected session\n\n @param[in] dpy the VA display\n @param[in] protected_session protected session to be destroyed"] + pub unsafe fn vaDestroyProtectedSession( + &self, + dpy: VADisplay, + protected_session: VAProtectedSessionID, + ) -> VAStatus { + (self + .vaDestroyProtectedSession + .as_ref() + .expect("Expected function, got error."))(dpy, protected_session) + } + #[doc = " \\brief Attach a protected content session to VA context\n\n Attach a protected content session to the context to enable\n decryption/protection\n\n @param[in] dpy the VA display\n @param[in] id the VA decode/encode/vp context\n @param[in] protected_session the protected session to attach"] + pub unsafe fn vaAttachProtectedSession( + &self, + dpy: VADisplay, + id: VAGenericID, + protected_session: VAProtectedSessionID, + ) -> VAStatus { + (self + .vaAttachProtectedSession + .as_ref() + .expect("Expected function, got error."))(dpy, id, protected_session) + } + #[doc = " \\brief Detach the protected content session from the VA context\n\n Detach protected content session of the context to disable\n decryption/protection\n\n @param[in] dpy the VA display\n @param[in] id TEE client id to be detached"] + pub unsafe fn vaDetachProtectedSession(&self, dpy: VADisplay, id: VAGenericID) -> VAStatus { + (self + .vaDetachProtectedSession + .as_ref() + .expect("Expected function, got error."))(dpy, id) + } + #[doc = " \\brief Execute provides a general mechanism for TEE client tasks execution.\n\n vaProtectedSessionExecute provides a mechanism for TEE clients to execute\n specific tasks. The implementation may differ between IHVs.\n This is a synchronous API.\n\n @param[in] dpy the VA display\n @param[in] protected_session the protected session\n @param[in,out] buf_id the VA buffer"] + pub unsafe fn vaProtectedSessionExecute( + &self, + dpy: VADisplay, + protected_session: VAProtectedSessionID, + buf_id: VABufferID, + ) -> VAStatus { + (self + .vaProtectedSessionExecute + .as_ref() + .expect("Expected function, got error."))(dpy, protected_session, buf_id) + } + #[doc = " \\brief Returns a VA display derived from the specified DRM connection.\n\n This function returns a (possibly cached) VA display from the\n specified DRM connection @fd.\n\n @param[in] fd the DRM connection descriptor\n @return the VA display"] + pub unsafe fn vaGetDisplayDRM(&self, fd: ::std::os::raw::c_int) -> VADisplay { + (self.vaGetDisplayDRM.as_ref().expect("Expected function, got error."))(fd) + } +} diff --git a/rs/moq-vaapi/src/bitstream_utils.rs b/rs/moq-vaapi/src/bitstream_utils.rs new file mode 100644 index 00000000000..ca4ebdc4a0f --- /dev/null +++ b/rs/moq-vaapi/src/bitstream_utils.rs @@ -0,0 +1,545 @@ +// 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; + +/// 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() + } +} + +#[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`] + /// and returns the number of trailing bits in the last byte. + pub fn flush(&mut self) -> BitWriterResult { + let mut num_trailing_bits = 0; + if self.nth_bit != 0 { + self.out.write_all(&[self.curr_byte])?; + num_trailing_bits = 8 - self.nth_bit; + self.nth_bit = 0; + self.curr_byte = 0; + } + + self.out.flush()?; + Ok(num_trailing_bits) + } + + /// 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() { + tracing::error!("Unable to flush bits {e:?}"); + } + } +} diff --git a/rs/moq-vaapi/src/buffer.rs b/rs/moq-vaapi/src/buffer.rs new file mode 100644 index 00000000000..58f6258c9f4 --- /dev/null +++ b/rs/moq-vaapi/src/buffer.rs @@ -0,0 +1,466 @@ +// 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 enc_misc; +mod h264; +mod hevc; +mod proc_pipeline; + +pub use enc_misc::*; +pub use h264::*; +pub use hevc::*; +pub use proc_pipeline::*; + +use std::rc::Rc; + +use tracing::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 */ + let nb_elements = match type_ { + BufferType::SliceParameter(SliceParameter::H264(ref mut params)) => params.inner_mut().len(), + _ => 1, + }; + + let (ptr, size) = match type_ { + BufferType::PictureParameter(ref mut picture_param) => match picture_param { + 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()), + ), + }, + + BufferType::SliceParameter(ref mut slice_param) => match slice_param { + 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()), + ), + }, + + BufferType::IQMatrix(ref mut iq_matrix) => match iq_matrix { + 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::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()), + ), + }, + + 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()), + ), + }, + + 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()), + ), + }, + + 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()), + ), + }, + BufferType::ProcPipelineParameter(ref mut proc_pipeline_param) => ( + proc_pipeline_param.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(proc_pipeline_param.inner_mut()), + ), + BufferType::EncPackedHeaderParameter(ref mut wrapper) => ( + wrapper.inner_mut() as *mut _ as *mut std::ffi::c_void, + std::mem::size_of_val(wrapper.inner_mut()), + ), + + BufferType::EncPackedHeaderData(ref data) => (data.as_ptr() as *mut std::ffi::c_void, data.len()), + }; + + // 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::va().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::va().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 H264, HEVC. + PictureParameter(PictureParameter), + /// Abstraction over `VASliceParameterBufferType`. Needed for H264, HEVC. + SliceParameter(SliceParameter), + /// Abstraction over `VAIQMatrixBufferType`. Needed for H264, HEVC. + IQMatrix(IQMatrix), + /// Abstraction over `VASliceDataBufferType`. Needed for H264, HEVC. + SliceData(Vec), + /// Abstraction over `VAEncSequenceParameterBufferType`. Needed for H264, HEVC. + EncSequenceParameter(EncSequenceParameter), + /// Abstraction over `VAEncPictureParameterBufferType`. Needed for H264, HEVC. + EncPictureParameter(EncPictureParameter), + /// Abstraction over `VAEncSliceParameterBufferType`. Needed for H264, HEVC. + EncSliceParameter(EncSliceParameter), + /// Abstraction over `VAEncMacroblockMapBufferType`. Needed for H264. + EncMacroblockParameterBuffer(EncMacroblockParameterBuffer), + /// Abstraction over `VAEncCodedBufferType`. Needed for H264, HEVC. + EncCodedBuffer(usize), + /// Abstraction over `VAEncMiscParameterBuffer`. + EncMiscParameter(EncMiscParameter), + /// Abstraction over `VAProcPipelineParameterBuffer`. + ProcPipelineParameter(proc_pipeline::ProcPipelineParameterBuffer), + /// Abstraction over `VAEncPackedHeaderParameterBufferType`. + EncPackedHeaderParameter(EncPackedHeaderParameter), + /// Abstraction over `VAEncPackedHeaderDataBufferType`. + EncPackedHeaderData(Vec), +} + +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::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, + + BufferType::ProcPipelineParameter(_) => bindings::VABufferType::VAProcPipelineParameterBufferType, + + BufferType::EncPackedHeaderParameter(_) => bindings::VABufferType::VAEncPackedHeaderParameterBufferType, + + BufferType::EncPackedHeaderData(_) => bindings::VABufferType::VAEncPackedHeaderDataBufferType, + } + } +} + +/// Abstraction over the `PictureParameterBuffer` types we support. +pub enum PictureParameter { + /// Wrapper over VAPictureParameterBufferH264. + H264(h264::PictureParameterBufferH264), + /// Wrapper over VAPictureParameterBufferHEVC + HEVC(hevc::PictureParameterBufferHEVC), + /// Wrapper over VAPictureParameterBufferHEVCRext + HEVCRext(hevc::PictureParameterBufferHEVCRext), + /// Wrapper over VAPictureParameterBufferHEVCScc + HEVCScc(hevc::PictureParameterBufferHEVCScc), +} + +/// Abstraction over the `SliceParameterBuffer` types we support +pub enum SliceParameter { + /// Wrapper over VASliceParameterBufferH264 + H264(h264::SliceParameterBufferH264), + /// Wrapper over VASliceParameterBufferHEVC + HEVC(hevc::SliceParameterBufferHEVC), + /// Wrapper over VASliceParameterBufferHEVCRext + HEVCRext(hevc::SliceParameterBufferHEVCRext), +} + +/// Abstraction over the `IQMatrixBuffer` types we support. +pub enum IQMatrix { + /// 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 the `EncPictureParameter` types we support. +pub enum EncPictureParameter { + /// Abstraction over `VAEncPictureParameterBufferH264` + H264(h264::EncPictureParameterBufferH264), + /// Abstraction over `VAEncPictureParameterBufferHEVC` + HEVC(hevc::EncPictureParameterBufferHEVC), +} + +/// Abstraction over the `EncSliceParameter` types we support. +pub enum EncSliceParameter { + /// Abstraction over `VAEncSliceParameterBufferH264` + H264(h264::EncSliceParameterBufferH264), + /// Abstraction over `VAEncSliceParameterBufferHEVC` + HEVC(hevc::EncSliceParameterBufferHEVC), +} + +/// 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::va().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::va().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), +} + +/// Abstraction over the `VAEncPackedHeaderType` enum values we support. +#[repr(u32)] +pub enum EncPackedHeaderType { + /// Sequence header + Sequence = bindings::VAEncPackedHeaderType::VAEncPackedHeaderSequence, + /// Picture header + Picture = bindings::VAEncPackedHeaderType::VAEncPackedHeaderPicture, + /// Slice header + Slice = bindings::VAEncPackedHeaderType::VAEncPackedHeaderSlice, + /// Raw data + RawData = bindings::VAEncPackedHeaderType::VAEncPackedHeaderRawData, +} + +/// Abstraction over `EncPackedHeaderParameterBuffer` types we support +pub struct EncPackedHeaderParameter(Box); + +impl EncPackedHeaderParameter { + /// Creates a new `EncPackedHeaderParameter` from the given `VAEncPackedHeaderParameterBuffer`. + pub fn new(type_: EncPackedHeaderType, length_in_bits: u32, has_emulation: bool) -> Self { + Self(Box::new(bindings::VAEncPackedHeaderParameterBuffer { + type_: type_ as _, + bit_length: length_in_bits, + has_emulation_bytes: has_emulation as u8, + ..Default::default() + })) + } + + /// Returns a mutable reference to the inner `VAEncPackedHeaderParameterBuffer`. + pub fn inner_mut(&mut self) -> &mut bindings::VAEncPackedHeaderParameterBuffer { + &mut self.0 + } +} diff --git a/rs/moq-vaapi/src/buffer/enc_misc.rs b/rs/moq-vaapi/src/buffer/enc_misc.rs new file mode 100644 index 00000000000..f05ebf883ad --- /dev/null +++ b/rs/moq-vaapi/src/buffer/enc_misc.rs @@ -0,0 +1,304 @@ +// 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 { + // libva expects `(denominator << 16) | numerator`, and we set framerate denominator to 1. + let framerate = (1 << 16) | (framerate & 0xFFFF); + + 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/rs/moq-vaapi/src/buffer/h264.rs b/rs/moq-vaapi/src/buffer/h264.rs new file mode 100644 index 00000000000..9585e9f73b2 --- /dev/null +++ b/rs/moq-vaapi/src/buffer/h264.rs @@ -0,0 +1,791 @@ +// 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 + 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 + 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 + 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 + 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 + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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/rs/moq-vaapi/src/buffer/hevc.rs b/rs/moq-vaapi/src/buffer/hevc.rs new file mode 100644 index 00000000000..72e3e997d5a --- /dev/null +++ b/rs/moq-vaapi/src/buffer/hevc.rs @@ -0,0 +1,1123 @@ +// 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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/rs/moq-vaapi/src/buffer/proc_pipeline.rs b/rs/moq-vaapi/src/buffer/proc_pipeline.rs new file mode 100644 index 00000000000..3418e97ee64 --- /dev/null +++ b/rs/moq-vaapi/src/buffer/proc_pipeline.rs @@ -0,0 +1,183 @@ +// 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. + +//! Wrappers around `VAProcPipeline` types. + +use crate::bindings; +use std::{marker::PhantomData, ptr}; + +/// Wrapper over the `VABlendState` ffi type. +pub struct BlendState(bindings::VABlendState); + +impl BlendState { + /// Creates the bindgen field + pub fn new(flags: u32, global_alpha: f32, min_luma: f32, max_luma: f32) -> Self { + Self(bindings::VABlendState { + flags, + global_alpha, + min_luma, + max_luma, + }) + } +} + +/// Wrapper over the `VAProcColorProperties` ffi type. +pub struct ProcColorProperties(bindings::VAProcColorProperties); + +impl ProcColorProperties { + /// Creates the bindgen field + pub fn new( + chroma_sample_location: u8, + color_range: u8, + colour_primaries: u8, + transfer_characteristics: u8, + matrix_coefficients: u8, + ) -> Self { + Self(bindings::VAProcColorProperties { + chroma_sample_location, + color_range, + colour_primaries, + transfer_characteristics, + matrix_coefficients, + reserved: Default::default(), + }) + } +} + +impl Default for ProcColorProperties { + fn default() -> Self { + Self::new(0, 0, 0, 0, 0) + } +} + +/// Wrapper over the `VAHdrMetaData` ffi type. +pub struct HdrMetaData(bindings::VAHdrMetaData); + +impl<'a> HdrMetaData { + /// Creates the bindgen field + pub fn new(metadata_type: u32, metadata: Option<&'a [u8]>, metadata_size: u32) -> Self { + Self(bindings::VAHdrMetaData { + metadata_type: metadata_type as _, + metadata: metadata.map_or(ptr::null_mut(), |f| f.as_ptr() as *mut _), + metadata_size, + reserved: Default::default(), + }) + } +} + +/// Wrapper over the `VAProcPipelineParameterBuffer` FFI type. +pub struct ProcPipelineParameterBuffer { + c_params: Box, + + // Fields that own the data for the pointers in `c_params`. + surface_region: Option>, + output_region: Option>, + filters: Option>, + forward_references: Option>, + backward_references: Option>, + blend_state: Option>, + additional_outputs: Option>, + output_hdr_metadata: Option>, +} + +impl ProcPipelineParameterBuffer { + /// Creates the wrapper. + pub fn new( + surface: bindings::VASurfaceID, + surface_region: Option, + surface_color_standard: u8, + output_region: Option, + output_background_color: u32, + output_color_standard: u8, + pipeline_flags: u32, + filter_flags: u32, + filters: Option>, + forward_references: Option>, + backward_references: Option>, + rotation_state: u32, + blend_state: Option>, + mirror_state: u32, + additional_outputs: Option>, + input_surface_flag: u32, + output_surface_flag: u32, + input_color_properties: ProcColorProperties, + output_color_properties: ProcColorProperties, + processing_mode: u32, + output_hdr_metadata: Option>, + ) -> Self { + let mut slf = Self { + // SAFETY: The VA-API structures are C-compatible so zeroing is safe. + c_params: Box::new(unsafe { std::mem::zeroed() }), + surface_region: surface_region.map(Box::new), + output_region: output_region.map(Box::new), + filters, + forward_references, + backward_references, + blend_state, + additional_outputs, + output_hdr_metadata, + }; + + slf.c_params = Box::new(bindings::VAProcPipelineParameterBuffer { + surface, + surface_region: slf + .surface_region + .as_deref() + .map_or(ptr::null_mut(), |r| r as *const _ as *mut _), + surface_color_standard: surface_color_standard as _, + output_region: slf + .output_region + .as_deref() + .map_or(ptr::null_mut(), |r| r as *const _ as *mut _), + output_background_color, + output_color_standard: output_color_standard as _, + pipeline_flags, + filter_flags, + filters: slf.filters.as_deref().map_or(ptr::null_mut(), |f| f.as_ptr() as *mut _), + num_filters: slf.filters.as_ref().map_or(0, |f| f.len() as u32), + forward_references: slf + .forward_references + .as_deref() + .map_or(ptr::null_mut(), |r| r.as_ptr() as *mut _), + num_forward_references: slf.forward_references.as_ref().map_or(0, |f| f.len() as u32), + backward_references: slf + .backward_references + .as_deref() + .map_or(ptr::null_mut(), |r| r.as_ptr() as *mut _), + num_backward_references: slf.backward_references.as_ref().map_or(0, |b| b.len() as u32), + rotation_state, + blend_state: slf + .blend_state + .as_deref() + .map_or(ptr::null(), |b| b.as_ptr() as *const bindings::VABlendState), + mirror_state, + additional_outputs: slf + .additional_outputs + .as_deref() + .map_or(ptr::null_mut(), |a| a.as_ptr() as *mut _), + num_additional_outputs: slf.additional_outputs.as_ref().map_or(0, |a| a.len() as u32), + input_surface_flag, + output_surface_flag, + input_color_properties: input_color_properties.0, + output_color_properties: output_color_properties.0, + processing_mode, + output_hdr_metadata: slf + .output_hdr_metadata + .as_deref() + .map_or(ptr::null_mut(), |o| o.as_ptr() as *mut bindings::VAHdrMetaData), + va_reserved: Default::default(), + }); + + slf + } + + pub(crate) fn inner_mut(&mut self) -> &mut bindings::VAProcPipelineParameterBuffer { + self.c_params.as_mut() + } + + /// Returns the inner FFI type. Useful for testing purposes. + pub fn inner(&self) -> &bindings::VAProcPipelineParameterBuffer { + self.c_params.as_ref() + } +} diff --git a/rs/moq-vaapi/src/codec.rs b/rs/moq-vaapi/src/codec.rs new file mode 100644 index 00000000000..ee0d8126766 --- /dev/null +++ b/rs/moq-vaapi/src/codec.rs @@ -0,0 +1,13 @@ +// Vendored from discord/cros-codecs (BSD-3-Clause): H.264, and the H.265 +// parser and DPB. +pub mod h264; +pub mod h265; + +/// A video coding format. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Codec { + /// H.264 (AVC). + H264, + /// H.265 (HEVC). + H265, +} diff --git a/rs/moq-vaapi/src/codec/h264.rs b/rs/moq-vaapi/src/codec/h264.rs new file mode 100644 index 00000000000..fc13025efdf --- /dev/null +++ b/rs/moq-vaapi/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/rs/moq-vaapi/src/codec/h264/dpb.rs b/rs/moq-vaapi/src/codec/h264/dpb.rs new file mode 100644 index 00000000000..a76e6de847a --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/dpb.rs @@ -0,0 +1,1239 @@ +// 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 tracing::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 { + tracing::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); + + tracing::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); + + tracing::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 { + tracing::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); + + tracing::debug!("MMCO op 1 for pic_num_x {}", pic_num_x); + tracing::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> { + tracing::debug!("MMCO op 2 for long_term_pic_num {}", marking.long_term_pic_num); + + tracing::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); + + tracing::debug!("MMCO op 3 for pic_num_x {}", pic_num_x); + tracing::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; + + tracing::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 { + tracing::debug!( + "MMCO op 4, max_long_term_frame_idx: {:?}", + marking.max_long_term_frame_idx + ); + + tracing::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 { + tracing::debug!("MMCO op 5, marking all pictures in the DPB as unused for reference"); + tracing::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; + + tracing::debug!("MMCO op 6, long_term_frame_idx: {}", long_term_frame_idx); + tracing::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/rs/moq-vaapi/src/codec/h264/nalu.rs b/rs/moq-vaapi/src/codec/h264/nalu.rs new file mode 100644 index 00000000000..88997bdc9e5 --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/nalu.rs @@ -0,0 +1,119 @@ +// 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; + +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/rs/moq-vaapi/src/codec/h264/nalu_writer.rs b/rs/moq-vaapi/src/codec/h264/nalu_writer.rs new file mode 100644 index 00000000000..418f182c276 --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/nalu_writer.rs @@ -0,0 +1,198 @@ +// 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() { + tracing::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()?; + let _num_bytes = self.0.inner_mut().write_header(idc, _type)?; + // self.0.bits_written += num_bytes * 8; + Ok(()) + } + + /// Returns `true` if next bits will be aligned to 8 + pub fn aligned(&self) -> bool { + !self.0.has_data_pending() + } + + /// Returns the number of trailing bits in the last byte. + pub fn flush(&mut self) -> NaluWriterResult { + Ok(self.0.flush()?) + } +} diff --git a/rs/moq-vaapi/src/codec/h264/parser.rs b/rs/moq-vaapi/src/codec/h264/parser.rs new file mode 100644 index 00000000000..53007d6fca1 --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/parser.rs @@ -0,0 +1,2673 @@ +// 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. + +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 frame_num(mut self, value: u16) -> Self { + self.0.frame_num = 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, PartialEq, Eq)] +#[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 + } + + /// Labels the stream's color space in the VUI. + /// + /// `video_format` goes out as 5 (unspecified), the value a decoder infers + /// when the field is absent, so this only adds the range and the color + /// description. + pub fn video_signal_type( + mut self, + full_range: bool, + colour_primaries: u8, + transfer_characteristics: u8, + matrix_coefficients: u8, + ) -> Self { + self = self.vui_parameters_present(); + self.0.vui_parameters.video_signal_type_present_flag = true; + self.0.vui_parameters.video_format = 5; + self.0.vui_parameters.video_full_range_flag = full_range; + self.0.vui_parameters.colour_description_present_flag = true; + self.0.vui_parameters.colour_primaries = colour_primaries; + self.0.vui_parameters.transfer_characteristics = transfer_characteristics; + self.0.vui_parameters.matrix_coefficients = matrix_coefficients; + self + } + + pub fn bitstream_restrictions_present(mut self) -> Self { + if self.0.vui_parameters.bitstream_restriction_flag { + return self; + } + self = self.vui_parameters_present(); + // important to set these before setting the restriction flag as max_num_order_frames + // only produces the default values we need when that flag is false + self.0.vui_parameters.max_num_reorder_frames = self.0.max_num_order_frames(); + self.0.vui_parameters.max_dec_frame_buffering = self.0.vui_parameters.max_num_reorder_frames; + self.0.vui_parameters.bitstream_restriction_flag = true; + // Set all restrictions to the defaults + self.0.vui_parameters.motion_vectors_over_pic_boundaries_flag = true; + self.0.vui_parameters.max_bytes_per_pic_denom = 2; + self.0.vui_parameters.max_bits_per_mb_denom = 1; + self.0.vui_parameters.log2_max_mv_length_horizontal = 16; + self.0.vui_parameters.log2_max_mv_length_vertical = 16; + self + } + + pub fn max_num_reorder_frames(mut self, value: u32) -> Self { + self = self.bitstream_restrictions_present(); + self.0.vui_parameters.max_num_reorder_frames = value; + self + } + + pub fn max_dec_frame_buffering(mut self, value: u32) -> Self { + self = self.bitstream_restrictions_present(); + self.0.vui_parameters.max_dec_frame_buffering = value; + 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 entropy_coding_mode_flag(mut self, value: bool) -> Self { + self.0.entropy_coding_mode_flag = value; + self + } + + pub fn transform_8x8_mode_flag(mut self, value: bool) -> Self { + self.0.transform_8x8_mode_flag = value; + self + } + + 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 + } +} diff --git a/rs/moq-vaapi/src/codec/h264/picture.rs b/rs/moq-vaapi/src/codec/h264/picture.rs new file mode 100644 index 00000000000..5e808ae31ad --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/picture.rs @@ -0,0 +1,423 @@ +// 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 tracing::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) { + tracing::debug!("Set reference of {:#?} to {:?}", self, reference); + self.reference = reference; + + if apply_to_other_field { + if let Some(other_field) = self.other_field() { + tracing::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/rs/moq-vaapi/src/codec/h264/synthesizer.rs b/rs/moq-vaapi/src/codec/h264/synthesizer.rs new file mode 100644 index 00000000000..90b41093cbb --- /dev/null +++ b/rs/moq-vaapi/src/codec/h264/synthesizer.rs @@ -0,0 +1,704 @@ +// 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::SliceHeader; +use crate::codec::h264::parser::SliceType; +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; +use crate::encode::IsReference; + +mod private { + pub trait NaluStruct {} +} + +impl private::NaluStruct for Sps {} + +impl private::NaluStruct for Pps {} + +impl private::NaluStruct for SliceHeader {} + +#[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(()) + } +} + +pub type NumTrailingBits = u8; + +impl<'n, W: Write> Synthesizer<'n, SliceHeader, W> { + pub fn synthesize( + header: &'n SliceHeader, + sps: &'n Sps, + pps: &'n Pps, + is_idr: bool, + is_ref: IsReference, + writer: W, + ep_enabled: bool, + ) -> SynthesizerResult { + let mut s = Self { + writer: NaluWriter::::new(writer, ep_enabled), + nalu: header, + }; + + let ref_idc = if is_idr { + 3 + } else if is_ref == IsReference::LongTerm { + 2 + } else if is_ref == IsReference::ShortTerm { + 1 + } else { + 0 + }; + let nalu_type = if is_idr { NaluType::SliceIdr } else { NaluType::Slice }; + s.writer.write_header(ref_idc, nalu_type as u8)?; + s.slice_header_data(sps, pps, is_idr, is_ref)?; + let num_trailing_bits = s.writer.flush()?; + Ok(num_trailing_bits) + } + + fn slice_header_data(&mut self, sps: &Sps, pps: &Pps, is_idr: bool, is_ref: IsReference) -> SynthesizerResult<()> { + let hdr = self.nalu; + + self.ue(hdr.first_mb_in_slice)?; + self.ue(hdr.slice_type as u32)?; + self.ue(hdr.pic_parameter_set_id)?; + + if sps.separate_colour_plane_flag { + self.u(2, hdr.colour_plane_id)?; + } + + let frame_num_bits = sps.log2_max_frame_num_minus4 as usize + 4; + self.u(frame_num_bits, hdr.frame_num)?; + + if !sps.frame_mbs_only_flag { + self.u(1, hdr.field_pic_flag as u32)?; + if hdr.field_pic_flag { + self.u(1, hdr.bottom_field_flag as u32)?; + } + } + + if is_idr { + self.ue(hdr.idr_pic_id)?; + } + + if sps.pic_order_cnt_type == 0 { + let pic_order_cnt_lsb_bits = sps.log2_max_pic_order_cnt_lsb_minus4 as usize + 4; + self.u(pic_order_cnt_lsb_bits, hdr.pic_order_cnt_lsb)?; + if pps.bottom_field_pic_order_in_frame_present_flag && !hdr.field_pic_flag { + self.se(hdr.delta_pic_order_cnt_bottom)?; + } + } + + if sps.pic_order_cnt_type == 1 && !sps.delta_pic_order_always_zero_flag { + self.se(hdr.delta_pic_order_cnt[0])?; + if pps.bottom_field_pic_order_in_frame_present_flag && !hdr.field_pic_flag { + self.se(hdr.delta_pic_order_cnt[1])?; + } + } + + if pps.redundant_pic_cnt_present_flag { + self.ue(hdr.redundant_pic_cnt)?; + } + + if hdr.slice_type == SliceType::B { + self.u(1, hdr.direct_spatial_mv_pred_flag as u32)?; + } + + if hdr.slice_type == SliceType::P || hdr.slice_type == SliceType::Sp || hdr.slice_type == SliceType::B { + self.u(1, hdr.num_ref_idx_active_override_flag as u32)?; + if hdr.num_ref_idx_active_override_flag { + self.ue(hdr.num_ref_idx_l0_active_minus1)?; + if hdr.slice_type == SliceType::B { + self.ue(hdr.num_ref_idx_l1_active_minus1)?; + } + } + } + + self.ref_pic_list_modification(hdr)?; + + if (pps.weighted_pred_flag && (hdr.slice_type == SliceType::P || hdr.slice_type == SliceType::Sp)) + || (pps.weighted_bipred_idc == 1 && hdr.slice_type == SliceType::B) + { + self.pred_weight_table(hdr, sps)?; + } + + if is_ref != IsReference::No { + self.dec_ref_pic_marking(hdr, is_idr)?; + } + + if pps.entropy_coding_mode_flag && hdr.slice_type != SliceType::I && hdr.slice_type != SliceType::Si { + self.ue(hdr.cabac_init_idc)?; + } + + self.se(hdr.slice_qp_delta)?; + + if hdr.slice_type == SliceType::Sp || hdr.slice_type == SliceType::Si { + if hdr.slice_type == SliceType::Sp { + self.u(1, hdr.sp_for_switch_flag as u32)?; + } + self.se(hdr.slice_qs_delta)?; + } + + if pps.deblocking_filter_control_present_flag { + self.ue(hdr.disable_deblocking_filter_idc)?; + if hdr.disable_deblocking_filter_idc != 1 { + self.se(hdr.slice_alpha_c0_offset_div2)?; + self.se(hdr.slice_beta_offset_div2)?; + } + } + + if pps.num_slice_groups_minus1 > 0 { + // Slice groups are not supported, this should have been caught earlier + return Err(SynthesizerError::Unsupported); + } + + Ok(()) + } + + fn ref_pic_list_modification(&mut self, hdr: &SliceHeader) -> SynthesizerResult<()> { + let slice_type_mod5 = hdr.slice_type as u8 % 5; + + if slice_type_mod5 != 2 && slice_type_mod5 != 4 { + self.u(1, hdr.ref_pic_list_modification_flag_l0 as u32)?; + if hdr.ref_pic_list_modification_flag_l0 { + for modification in &hdr.ref_pic_list_modification_l0 { + self.ue(modification.modification_of_pic_nums_idc)?; + if modification.modification_of_pic_nums_idc == 0 || modification.modification_of_pic_nums_idc == 1 + { + self.ue(modification.abs_diff_pic_num_minus1)?; + } else if modification.modification_of_pic_nums_idc == 2 { + self.ue(modification.long_term_pic_num)?; + } + } + self.ue(3u32)?; + } + } + + if slice_type_mod5 == 1 { + self.u(1, hdr.ref_pic_list_modification_flag_l1 as u32)?; + if hdr.ref_pic_list_modification_flag_l1 { + for modification in &hdr.ref_pic_list_modification_l1 { + self.ue(modification.modification_of_pic_nums_idc)?; + if modification.modification_of_pic_nums_idc == 0 || modification.modification_of_pic_nums_idc == 1 + { + self.ue(modification.abs_diff_pic_num_minus1)?; + } else if modification.modification_of_pic_nums_idc == 2 { + self.ue(modification.long_term_pic_num)?; + } + } + self.ue(3u32)?; + } + } + + Ok(()) + } + + fn pred_weight_table(&mut self, hdr: &SliceHeader, sps: &Sps) -> SynthesizerResult<()> { + let pwt = &hdr.pred_weight_table; + let chroma_array_type = sps.chroma_array_type(); + + self.ue(pwt.luma_log2_weight_denom)?; + if chroma_array_type != 0 { + self.ue(pwt.chroma_log2_weight_denom)?; + } + + let num_ref_idx_l0 = (hdr.num_ref_idx_l0_active_minus1 + 1) as usize; + for i in 0..num_ref_idx_l0 { + let luma_weight_l0_flag = pwt.luma_weight_l0[i] != (1 << pwt.luma_log2_weight_denom); + self.u(1, luma_weight_l0_flag as u32)?; + if luma_weight_l0_flag { + self.se(pwt.luma_weight_l0[i])?; + self.se(pwt.luma_offset_l0[i])?; + } + + if chroma_array_type != 0 { + let default_weight = 1 << pwt.chroma_log2_weight_denom; + let chroma_weight_l0_flag = pwt.chroma_weight_l0[i][0] != default_weight + || pwt.chroma_weight_l0[i][1] != default_weight + || pwt.chroma_offset_l0[i][0] != 0 + || pwt.chroma_offset_l0[i][1] != 0; + self.u(1, chroma_weight_l0_flag as u32)?; + if chroma_weight_l0_flag { + for j in 0..2 { + self.se(pwt.chroma_weight_l0[i][j])?; + self.se(pwt.chroma_offset_l0[i][j])?; + } + } + } + } + + if hdr.slice_type as u8 % 5 == 1 { + let num_ref_idx_l1 = (hdr.num_ref_idx_l1_active_minus1 + 1) as usize; + for i in 0..num_ref_idx_l1 { + let luma_weight_l1_flag = pwt.luma_weight_l1[i] != (1 << pwt.luma_log2_weight_denom) as i16; + self.u(1, luma_weight_l1_flag as u32)?; + if luma_weight_l1_flag { + self.se(pwt.luma_weight_l1[i])?; + self.se(pwt.luma_offset_l1[i])?; + } + + if chroma_array_type != 0 { + let default_weight = (1 << pwt.chroma_log2_weight_denom) as i16; + let chroma_weight_l1_flag = pwt.chroma_weight_l1[i][0] != default_weight + || pwt.chroma_weight_l1[i][1] != default_weight + || pwt.chroma_offset_l1[i][0] != 0 + || pwt.chroma_offset_l1[i][1] != 0; + self.u(1, chroma_weight_l1_flag as u32)?; + if chroma_weight_l1_flag { + for j in 0..2 { + self.se(pwt.chroma_weight_l1[i][j])?; + self.se(pwt.chroma_offset_l1[i][j])?; + } + } + } + } + } + + Ok(()) + } + + fn dec_ref_pic_marking(&mut self, hdr: &SliceHeader, is_idr: bool) -> SynthesizerResult<()> { + let rpm = &hdr.dec_ref_pic_marking; + + if is_idr { + self.u(1, rpm.no_output_of_prior_pics_flag as u32)?; + self.u(1, rpm.long_term_reference_flag as u32)?; + } else { + self.u(1, rpm.adaptive_ref_pic_marking_mode_flag as u32)?; + if rpm.adaptive_ref_pic_marking_mode_flag { + for marking in &rpm.inner { + self.ue(marking.memory_management_control_operation)?; + if marking.memory_management_control_operation == 1 + || marking.memory_management_control_operation == 3 + { + self.ue(marking.difference_of_pic_nums_minus1)?; + } + if marking.memory_management_control_operation == 2 { + self.ue(marking.long_term_pic_num)?; + } + if marking.memory_management_control_operation == 3 + || marking.memory_management_control_operation == 6 + { + self.ue(marking.long_term_frame_idx)?; + } + if marking.memory_management_control_operation == 4 { + self.ue(marking.max_long_term_frame_idx.to_value_plus1())?; + } + } + self.ue(0u32)?; + } + } + + Ok(()) + } +} diff --git a/rs/moq-vaapi/src/codec/h265.rs b/rs/moq-vaapi/src/codec/h265.rs new file mode 100644 index 00000000000..44f3f8a8d34 --- /dev/null +++ b/rs/moq-vaapi/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/rs/moq-vaapi/src/codec/h265/dpb.rs b/rs/moq-vaapi/src/codec/h265/dpb.rs new file mode 100644 index 00000000000..d680e4ddff3 --- /dev/null +++ b/rs/moq-vaapi/src/codec/h265/dpb.rs @@ -0,0 +1,271 @@ +// 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); + + tracing::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); + + tracing::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); + + tracing::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> { + tracing::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 highest_tid = sps.max_sub_layers_minus1; + let max_dec_pic_buffering = usize::from(sps.max_dec_pic_buffering_minus1[usize::from(highest_tid)]) + 1; + + self.output_overdue(sps) || self.entries().len() >= max_dec_pic_buffering + } + + /// Whether more pictures wait for output than the reorder limit allows, or + /// one has waited past the latency limit, SpsMaxLatencyPictures (7-9). + fn output_overdue(&self, sps: &Sps) -> bool { + let highest_tid = usize::from(sps.max_sub_layers_minus1); + let max_num_reorder_pics = sps.max_num_reorder_pics[highest_tid]; + let max_latency_increase_plus1 = sps.max_latency_increase_plus1[highest_tid]; + let max_latency_pictures = i32::from(max_num_reorder_pics) + i32::from(max_latency_increase_plus1) - 1; + + let num_needed_for_output = self.pictures().filter(|pic| pic.needed_for_output).count(); + let pic_over_max_latency = self + .pictures() + .any(|pic| pic.needed_for_output && pic.pic_latency_cnt >= max_latency_pictures); + + num_needed_for_output > max_num_reorder_pics.into() || (max_latency_increase_plus1 != 0 && pic_over_max_latency) + } + + /// 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; + tracing::debug!("Bumping POC {} from the dpb", pic.pic_order_cnt_val); + tracing::trace!("{:#?}", pic); + + if !pic.is_ref() || flush { + let index = self.get_position(&handle.0).unwrap(); + + tracing::debug!( + "Removed POC {} from the dpb: reference: {}, flush: {}", + pic.pic_order_cnt_val, + pic.is_ref(), + flush + ); + tracing::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 { + self.output_overdue(sps) + } + + /// Clears the DPB, dropping all the pictures. + pub fn clear(&mut self) { + tracing::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) { + tracing::debug!("Removing unused pictures from DPB."); + self.entries.retain(|e| { + let pic = e.0.borrow(); + let retain = pic.needed_for_output || pic.is_ref(); + tracing::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(); + tracing::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/rs/moq-vaapi/src/codec/h265/parser.rs b/rs/moq-vaapi/src/codec/h265/parser.rs new file mode 100644 index 00000000000..b4742ed0e9b --- /dev/null +++ b/rs/moq-vaapi/src/codec/h265/parser.rs @@ -0,0 +1,4061 @@ +// 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; +// The most tile columns and rows any level allows (Table A.8), including the +// last of each, which is inferred rather than signalled. +const MAX_TILE_COLUMNS: usize = 20; +const MAX_TILE_ROWS: usize = 22; +// 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; MAX_TILE_COLUMNS], + /// `row_height_minus1[ i ]` plus 1 specifies the height of the i-th tile row + /// in units of CTBs. + pub row_height_minus1: [u32; MAX_TILE_ROWS], + /// 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: Vec, + /// 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 = std::mem::take(&mut 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_profile_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. + 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 { + tracing::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 { + tracing::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; + + tracing::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)?; + if usize::from(pps.num_tile_columns_minus1) >= MAX_TILE_COLUMNS + || usize::from(pps.num_tile_rows_minus1) >= MAX_TILE_ROWS + { + return Err(format!( + "{}x{} tiles, more than any level allows", + u32::from(pps.num_tile_columns_minus1) + 1, + u32::from(pps.num_tile_rows_minus1) + 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 + } + + tracing::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) * (u32::from(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)?; + // One per CTB row or tile, so a 4K picture with wavefronts has + // more than a fixed array would hold. + let num_bits = usize::from(hdr.offset_len_minus1 + 1); + hdr.entry_point_offset_minus1 = (0..hdr.num_entry_point_offsets) + .map(|_| r.read_bits(num_bits)) + .collect::>()?; + } + } + + 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; + + tracing::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) + } +} diff --git a/rs/moq-vaapi/src/codec/h265/picture.rs b/rs/moq-vaapi/src/codec/h265/picture.rs new file mode 100644 index 00000000000..2b86726e1dd --- /dev/null +++ b/rs/moq-vaapi/src/codec/h265/picture.rs @@ -0,0 +1,152 @@ +// 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) { + tracing::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/rs/moq-vaapi/src/color.rs b/rs/moq-vaapi/src/color.rs new file mode 100644 index 00000000000..b8323e949a5 --- /dev/null +++ b/rs/moq-vaapi/src/color.rs @@ -0,0 +1,93 @@ +//! The YUV color space an encoded stream is labelled with. +//! +//! One value serves two jobs that have to agree: the encoder writes it into the +//! SPS video usability information, and the post-processor uses it as the +//! target of every conversion it runs for the encoder. Pixels the encoder +//! converts therefore match their label. Pixels it takes as they are (a CPU +//! upload, a YUV buffer with no color of its own) are labelled, not converted. + +use crate::bindings; + +/// The matrix that maps RGB to Y'CbCr. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Matrix { + /// ITU-R BT.601, the standard-definition matrix. + Bt601, + /// ITU-R BT.709, the high-definition matrix. + Bt709, +} + +/// A YUV color space: the matrix and whether samples use the full 8-bit range. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Color { + /// The RGB to Y'CbCr matrix. + pub matrix: Matrix, + /// Whether luma spans 0..=255 rather than 16..=235. + pub full_range: bool, +} + +impl Color { + /// BT.601 in limited range. + pub const BT601: Self = Self { + matrix: Matrix::Bt601, + full_range: false, + }; + /// BT.709 in limited range. + pub const BT709: Self = Self { + matrix: Matrix::Bt709, + full_range: false, + }; + + /// Returns the conventional space for a stream of `height` lines. + /// + /// Standard definition (576 lines or fewer) is BT.601, anything taller + /// BT.709, both in limited range. That is the guess most players make for + /// an unlabelled stream, though not all of them (ffmpeg's scaler takes + /// BT.601 at every size), which is why the stream is labelled. + pub fn infer(height: u32) -> Self { + match height <= 576 { + true => Self::BT601, + false => Self::BT709, + } + } + + /// Returns the H.264 VUI `(colour_primaries, transfer_characteristics, matrix_coefficients)`. + /// + /// BT.601 goes out as SMPTE 170M primaries and matrix (code point 6) with the + /// BT.709 transfer curve (1), since the two standards differ in primaries + /// and matrix but not in gamma. + pub(crate) fn vui(self) -> (u8, u8, u8) { + match self.matrix { + Matrix::Bt601 => (6, 1, 6), + Matrix::Bt709 => (1, 1, 1), + } + } + + /// Returns the `VAProcColorStandardType` of the matrix. + pub(crate) fn va_standard(self) -> u8 { + (match self.matrix { + Matrix::Bt601 => bindings::_VAProcColorStandardType_VAProcColorStandardBT601, + Matrix::Bt709 => bindings::_VAProcColorStandardType_VAProcColorStandardBT709, + }) as u8 + } + + /// Returns the `VA_SOURCE_RANGE_*` of the range. + pub(crate) fn va_range(self) -> u8 { + (match self.full_range { + true => bindings::VA_SOURCE_RANGE_FULL, + false => bindings::VA_SOURCE_RANGE_REDUCED, + }) as u8 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inference_splits_at_standard_definition() { + assert_eq!(Color::infer(480), Color::BT601); + assert_eq!(Color::infer(576), Color::BT601); + assert_eq!(Color::infer(720), Color::BT709); + } +} diff --git a/rs/moq-vaapi/src/config.rs b/rs/moq-vaapi/src/config.rs new file mode 100644 index 00000000000..edf5b74a13a --- /dev/null +++ b/rs/moq-vaapi/src/config.rs @@ -0,0 +1,131 @@ +// 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::sync::Arc; + +use thiserror::Error; +use tracing::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: Arc, + 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: Arc, + 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::va().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::va().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::va().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::va().vaDestroyConfig(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyConfig failed: {}", status.unwrap_err()); + } + } +} diff --git a/rs/moq-vaapi/src/context.rs b/rs/moq-vaapi/src/context.rs new file mode 100644 index 00000000000..e9638935bef --- /dev/null +++ b/rs/moq-vaapi/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 std::sync::Arc; + +use tracing::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: Arc, + 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: Arc, + 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::va().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) -> &Arc { + &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::va().vaDestroyContext(self.display.handle(), self.id) }); + + if status.is_err() { + error!("vaDestroyContext failed: {}", status.unwrap_err()); + } + } +} diff --git a/rs/moq-vaapi/src/decode.rs b/rs/moq-vaapi/src/decode.rs new file mode 100644 index 00000000000..5549e809720 --- /dev/null +++ b/rs/moq-vaapi/src/decode.rs @@ -0,0 +1,2529 @@ +// 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. +// +// Adapted from discord/cros-codecs (`decoder/stateless/h264.rs` and +// `decoder/stateless/h264/vaapi.rs`), itself BSD-3-Clause / Copyright The +// ChromiumOS Authors. See LICENSE.cros-codecs. + +//! Thin VA-API H.264 and H.265 decoder built on the vendored libva binding. +//! +//! The mirror of [`crate::encode`]. It reuses the backend-agnostic bitstream +//! layers ([`crate::codec::h264`], [`crate::codec::h265`]) from +//! discord/cros-codecs (BSD-3-Clause) for parameter set and slice parsing, +//! reference marking, and DPB bumping, then drives libva directly rather than +//! vendoring cros-codecs's generic multi-backend decoder framework. The +//! per-picture and per-slice VA buffer population is ported from cros-codecs's +//! `decoder/stateless/h264/vaapi.rs` and, in `h265.rs`, from +//! `decoder/stateless/h265.rs` and `decoder/stateless/h265/vaapi.rs`. +//! +//! Feed [`Decoder::decode`] one Annex-B access unit at a time. Its picture is +//! submitted and completed before the call returns, rather than when the next +//! unit's first slice arrives, so the hardware is never left holding a +//! half-submitted picture between calls. +//! +//! H.264 output trails input, and by more than the stream's reorder depth: +//! C.4.5.3 bumps the DPB only when a new picture needs the slot, so the delay +//! follows the sequence's reference and reorder limits. A stream coded with +//! three reference frames trails by three pictures whether or not it uses +//! B-frames. H.265 bumps by the SPS's reorder limit (C.5.2), so a stream with +//! no reordering comes out as it decodes. [`Frame`] therefore carries the +//! timestamp of the access unit it was coded in, and [`Decoder::flush`] is what +//! releases the tail at the end of a stream. +//! +//! Progressive 8-bit 4:2:0 only: a sequence that is interlaced, deeper than 8 +//! bits, or not 4:2:0 is rejected rather than decoded wrongly. That covers every +//! stream this crate's encoder, WebRTC, or a browser's `VideoEncoder` produces. +//! H.265 is the Main profile, with Main 10 and Main Still Picture streams that +//! hold 8-bit samples decoded the same way. Left and top cropping are rejected; +//! right and bottom cropping are supported. + +use std::io::Cursor; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; + +use anyhow::{anyhow, bail, Context as _}; + +use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists}; +use crate::codec::h264::parser::{ + Level, MaxLongTermFrameIdx, Nalu, NaluType, Parser, Pps, Profile, RefPicListModification, Slice, SliceHeader, + SliceType, Sps, +}; +use crate::codec::h264::picture::{Field, IsIdr, PictureData, Reference}; +use crate::codec::Codec; +use crate::pool::{PooledSurface, SurfacePool}; +use crate::{ + bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields, + H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter, + PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib, + VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID, + VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420, + VA_SLICE_DATA_FLAG_ALL, +}; + +mod h265; + +/// Decoder configuration. +#[derive(Clone, Debug)] +pub struct Config { + /// The format to decode, H.264 unless set. + pub codec: Codec, + /// DRM render node to open (e.g. `/dev/dri/renderD128`). + /// + /// `None`, the default, opens the first node whose driver can decode + /// [`codec`](Self::codec). + pub device: Option, +} + +impl Config { + /// Returns an H.264 configuration that opens the first render node whose driver can decode it. + pub fn new() -> Self { + Self { + codec: Codec::H264, + device: None, + } + } +} + +impl Default for Config { + fn default() -> Self { + Self::new() + } +} + +/// One decoded picture, downloaded to client memory as tightly packed NV12. +#[derive(Clone)] +pub struct Frame { + /// Timestamp of the access unit this picture was coded in, as handed to + /// [`Decoder::decode`]. + pub timestamp: u64, + /// Visible width in pixels, i.e. after the SPS cropping rectangle. + pub width: u32, + /// Visible height in pixels. + pub height: u32, + /// NV12 planes with no row padding: `width * height` luma bytes followed by + /// `width * height / 2` interleaved chroma bytes. + pub data: Vec, +} + +/// One decoded picture, left in the surface the hardware wrote it into. +/// +/// The GPU counterpart of [`Frame`]: same picture, same timestamp, but a DRM +/// PRIME descriptor for the surface rather than a copy of its pixels. The +/// descriptor owns the exported file descriptors and the surface travels with +/// it, so both the allocation and libva's handle on it outlive the decoder. +/// +/// The export is NV12 in one object holding both planes, which is what the +/// Intel and AMD drivers produce. Read the modifier off the object before +/// assuming anything about the layout: a decode target is tiled, and the plane +/// pitches carry padding the visible size does not imply. That is also why +/// [`ExportedFrame::download`] goes back through the surface instead of reading +/// the file descriptor as rows. +/// +/// Dropping the frame hands its surface back to the decoder, which decodes a +/// later picture into it. So keep the frame for as long as anything reads the +/// descriptor or an import of it: a GPU consumer holds it until the work that +/// samples it has finished, not merely until that work is submitted. A frame +/// that outlives its decoder, or the sequence it was decoded in, releases its +/// surface to the driver instead. +/// +/// This is [`Send`] and [`Sync`] even though [`Decoder`] is neither: a surface +/// is a display and an id, both of which libva serializes internally, and none +/// of the decoder's `Rc`s come along. +pub struct ExportedFrame { + /// Timestamp of the access unit this picture was coded in, as handed to + /// [`Decoder::decode_exported`]. + pub timestamp: u64, + /// Visible width in pixels, i.e. after the SPS cropping rectangle. + pub width: u32, + /// Visible height in pixels. + pub height: u32, + /// The surface's export: format, modifier, and the offset and pitch of each + /// plane. + pub descriptor: DrmPrimeSurfaceDescriptor, + /// The surface the picture was decoded into, held here so the decoder does + /// not decode into it again until this drops, and so + /// [`ExportedFrame::download`] has something to map. + surface: Arc, +} + +impl ExportedFrame { + /// Exports `surface`, an NV12 picture from somewhere other than the decoder, the way the decoder exports its own. + /// + /// A picture the video processor produced, such as a scaled copy of a + /// captured frame, then reaches its consumer with the same descriptor and + /// the same [`download`](Self::download) fallback as a decoded one, so one + /// consumer handles both. `timestamp` is carried through untouched. + /// + /// # Errors + /// + /// Fails when the surface is not NV12, cannot be synced, or the driver will + /// not export it. + pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result { + let size = surface.size(); + Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size) + } + + /// Exports `surface`, whose picture is the top-left `width` by `height` of it, copying nothing. + /// + /// The frame holds a reference to the surface, so a pool does not hand it + /// out again while the caller holds the descriptor, and + /// [`download`](Self::download) can still map it. + pub(crate) fn export( + surface: Arc, + timestamp: u64, + (width, height): (u32, u32), + ) -> anyhow::Result { + surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?; + let descriptor = surface + .get() + .export_prime() + .map_err(|e| anyhow!("export the surface: {e:?}"))?; + if descriptor.fourcc != VA_FOURCC_NV12 { + anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc); + } + Ok(Self { + timestamp, + width, + height, + descriptor, + surface, + }) + } + + /// Reads this picture back to client memory as tightly packed NV12. + /// + /// The way back for a caller that took a descriptor and then found itself + /// with a consumer that wants bytes. It costs the read [`Decoder::decode`] + /// would have done up front, so prefer that entry point when nothing on the + /// path draws on the GPU. + /// + /// Same layout as [`Frame::data`], with the driver's row padding dropped. + pub fn download(&self) -> anyhow::Result { + read_back(self.surface.get(), self.timestamp, self.width, self.height) + } +} + +impl std::fmt::Debug for ExportedFrame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ExportedFrame") + .field("timestamp", &self.timestamp) + .field("width", &self.width) + .field("height", &self.height) + .field("fourcc", &self.descriptor.fourcc) + .finish() + } +} + +impl std::fmt::Debug for Frame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Frame") + .field("timestamp", &self.timestamp) + .field("width", &self.width) + .field("height", &self.height) + .field("bytes", &self.data.len()) + .finish() + } +} + +/// A VA-API H.264 or H.265 decoder. Built once, fed Annex-B access units, emits NV12. +/// +/// # Examples +/// +/// ```no_run +/// use moq_vaapi::decode::{Config, Decoder}; +/// +/// # fn main() -> anyhow::Result<()> { +/// # let access_units: Vec> = Vec::new(); +/// let mut decoder = Decoder::new(Config::new())?; +/// let mut pictures = Vec::new(); +/// +/// for (index, access_unit) in access_units.iter().enumerate() { +/// pictures.extend(decoder.decode(access_unit, index as u64)?); +/// } +/// +/// // Output trails input, so the tail of the stream only arrives here. +/// pictures.extend(decoder.flush()?); +/// # Ok(()) +/// # } +/// ``` +pub struct Decoder { + inner: Inner, +} + +/// The decoder for each format. They share the VA plumbing: [`Sequence`], +/// [`Handle`], and the read-back and export of a decoded picture. +enum Inner { + H264(H264), + H265(h265::Decoder), +} + +/// The H.264 decoder. +struct H264 { + parser: Parser, + dpb: Dpb, + /// Cached variables from the previous reference picture. + prev_ref_pic_info: PrevReferencePicInfo, + /// Cached variables from the previous picture. + prev_pic_info: PrevPicInfo, + max_long_term_frame_idx: MaxLongTermFrameIdx, + /// VA state for the active sequence, rebuilt when the SPS changes something + /// the config, context, or surface pool depends on. + sequence: Option, + /// Pictures bumped out of the DPB, in output order, awaiting download. + ready: Vec, + /// Drop order: everything above borrows the display. + display: Arc, +} + +impl Decoder { + /// Opens [`Config::device`], or the first render node that decodes + /// [`Config::codec`], and checks that the driver exposes a decode + /// entrypoint for it. + /// + /// The VA config, context, and surface pool are built later, from the first + /// SPS, since their profile and size come from the stream. This still fails + /// early enough for a caller to fall back to another decoder when libva is + /// missing, the node cannot be opened, or the driver does not decode the + /// codec. A named node is never swapped for another. + pub fn new(config: Config) -> anyhow::Result { + let codec = config.codec; + let (device, display) = match config.device { + Some(device) => { + let display = + Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?; + probe(&display, codec)?; + (device, display) + } + None => crate::display::open_first(|display| probe(display, codec)) + .map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?, + }; + + tracing::info!("opened VA-API {codec:?} decoder on {device:?}"); + let inner = match codec { + Codec::H264 => Inner::H264(H264::new(display)), + Codec::H265 => Inner::H265(h265::Decoder::new(display)), + }; + Ok(Self { inner }) + } + + /// Decodes one Annex-B access unit, returning the pictures that came due, in + /// output order. + /// + /// `timestamp` is opaque and travels with the picture coded in this access + /// unit, so it survives DPB reordering. Parameter sets are read from the + /// stream, so an access unit carrying only an SPS and a PPS decodes to no + /// frames. + pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result> { + self.submit(access_unit, timestamp)?; + self.take_frames() + } + + /// Decodes one Annex-B access unit, leaving the pictures that came due on + /// the GPU. + /// + /// The same decode as [`Decoder::decode`], differing only in what the caller + /// gets back: a DRM PRIME descriptor for each picture's surface instead of a + /// copy of its pixels. For a consumer that draws on the GPU that is the + /// whole picture never touching system memory. + /// + /// An exported surface stays out of the recycling pool until the + /// [`ExportedFrame`] drops, since the next picture would otherwise be decoded + /// over pixels the consumer still holds a descriptor for. A consumer that + /// lets each picture go once it has drawn it therefore costs no allocation + /// per picture; one that holds on to pictures costs one surface per picture + /// held. + /// + /// A consumer that turns out to want bytes after all is not stuck: the + /// surface travels with the descriptor, and [`ExportedFrame::download`] reads + /// it back. + pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result> { + self.submit(access_unit, timestamp)?; + self.take_exported() + } + + /// Decodes one access unit, leaving the pictures that came due in the ready + /// queue for whichever of [`Decoder::take_frames`] or + /// [`Decoder::take_exported`] the caller asked for. + fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> { + let nalus = match &mut self.inner { + Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?, + Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?, + }; + + // A decoder cannot tell a truncated unit from a complete one, so a + // caller that hands us the wrong container gets silence. Say so once per + // unit rather than leaving them to wonder where their pictures went. + if nalus == 0 && !access_unit.is_empty() { + tracing::warn!( + "access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first", + access_unit.len() + ); + } + Ok(()) + } + + /// Returns every picture still held in the DPB, in output order. + /// + /// The DPB lets a picture out only when a later one needs it to (C.4.5.3 + /// for H.264, C.5.2 for H.265), so a stream that simply stops leaves its + /// tail sitting there. This releases that tail and empties the DPB, so a + /// second call returns nothing. + /// + /// The parsed parameter sets survive, and nothing here waits for an IDR: a + /// stream picked up part way through decodes against an empty DPB, which + /// gives distorted pictures until its next IDR rather than an error. + pub fn flush(&mut self) -> anyhow::Result> { + self.reset(); + self.take_frames() + } + + /// [`Decoder::flush`] for a caller taking its pictures on the GPU. + pub fn flush_exported(&mut self) -> anyhow::Result> { + self.reset(); + self.take_exported() + } + + /// Moves the DPB to the ready queue and forgets the state the next picture + /// would otherwise be derived against. + fn reset(&mut self) { + match &mut self.inner { + Inner::H264(decoder) => decoder.reset(), + Inner::H265(decoder) => decoder.reset(), + } + } + + /// The pictures bumped out of the DPB, in output order, awaiting download. + fn ready(&mut self) -> &mut Vec { + match &mut self.inner { + Inner::H264(decoder) => &mut decoder.ready, + Inner::H265(decoder) => &mut decoder.ready, + } + } + + /// Downloads every picture waiting in the ready queue. + fn take_frames(&mut self) -> anyhow::Result> { + std::mem::take(self.ready()).iter().map(download).collect() + } + + /// Exports every picture waiting in the ready queue, leaving the pixels + /// where the hardware wrote them. + fn take_exported(&mut self) -> anyhow::Result> { + std::mem::take(self.ready()).iter().map(export).collect() + } + + /// The VA state of the active sequence, for tests that look at its pool. + #[cfg(test)] + fn sequence(&self) -> Option<&Sequence> { + match &self.inner { + Inner::H264(decoder) => decoder.sequence.as_ref(), + Inner::H265(decoder) => decoder.sequence.as_ref(), + } + } +} + +impl H264 { + fn new(display: Arc) -> Self { + Self { + parser: Parser::default(), + dpb: Dpb::default(), + prev_ref_pic_info: PrevReferencePicInfo::default(), + prev_pic_info: PrevPicInfo::default(), + max_long_term_frame_idx: MaxLongTermFrameIdx::default(), + sequence: None, + ready: Vec::new(), + display, + } + } + + /// Decodes one access unit into the ready queue, returning how many NAL units it held. + fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result { + let mut cursor = Cursor::new(access_unit); + let mut current: Option = None; + let mut nalus = 0usize; + + // `Nalu::next` reports the end of the buffer as an error, so a truncated + // unit is indistinguishable from a complete one and simply stops us. + while let Ok(nalu) = Nalu::next(&mut cursor) { + nalus += 1; + match nalu.header.type_ { + NaluType::Sps => { + self.parser.parse_sps(&nalu).map_err(|e| anyhow!("parse SPS: {e}"))?; + } + NaluType::Pps => { + self.parser.parse_pps(&nalu).map_err(|e| anyhow!("parse PPS: {e}"))?; + } + NaluType::Slice + | NaluType::SliceDpa + | NaluType::SliceDpb + | NaluType::SliceDpc + | NaluType::SliceIdr + | NaluType::SliceExt => { + let slice = self + .parser + .parse_slice_header(nalu) + .map_err(|e| anyhow!("parse slice header: {e}"))?; + + let mut picture = match current.take() { + // An access unit normally holds one picture, but nothing + // forces that: `first_mb_in_slice == 0` starts a new one, + // so the picture in flight is done. + Some(picture) if slice.header.first_mb_in_slice == 0 => { + self.finish_picture(picture)?; + self.begin_picture(&slice, timestamp)? + } + Some(picture) => picture, + None => self.begin_picture(&slice, timestamp)?, + }; + + self.decode_slice(&mut picture, &slice)?; + current = Some(picture); + } + other => tracing::trace!("ignoring NAL unit of type {other:?}"), + } + } + + // Finishing here rather than on the next unit's first slice keeps the + // hardware from holding a half-submitted picture between calls. + if let Some(picture) = current.take() { + self.finish_picture(picture)?; + } + + Ok(nalus) + } + + /// Moves the DPB to the ready queue and forgets the order count state the + /// next picture would otherwise be derived against. + fn reset(&mut self) { + self.drain(); + self.prev_ref_pic_info = PrevReferencePicInfo::default(); + self.prev_pic_info = PrevPicInfo::default(); + self.max_long_term_frame_idx = MaxLongTermFrameIdx::default(); + } + + /// Moves everything left in the DPB to the ready queue. + fn drain(&mut self) { + self.ready.extend(self.dpb.drain().into_iter().flatten()); + } + + /// Applies `sps` to the DPB limits, rebuilding the VA config, context, and + /// surface pool if it changes anything they depend on. + fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> { + let info = SequenceInfo::new(sps)?; + // C.4.5.3: the DPB limits follow the active SPS whether or not the VA + // state has to be rebuilt. + let max_dpb_frames = sps.max_dpb_frames(); + 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); + + let format = Format { + codec: Codec::H264, + profile: va_profile(sps)?, + coded: info.coded, + visible: info.visible, + max_dpb_frames: info.max_dpb_frames, + }; + if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) { + return Ok(()); + } + + // Surfaces are about to change shape, so let everything decoded against + // the old sequence out first. Those handles keep their own surfaces (and + // through them the old pool) alive until they are downloaded. + self.drain(); + + self.sequence = Some(Sequence::new(&self.display, format)?); + Ok(()) + } + + /// Starts a picture: computes its order count, updates the DPB's picture + /// numbers, and hands the driver the picture parameters. + fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result { + let pps = Rc::clone( + self.parser + .get_pps(slice.header.pic_parameter_set_id) + .context("slice refers to an unknown PPS")?, + ); + let sps = Rc::clone(&pps.sps); + self.apply_sps(&sps)?; + + if slice.nalu.header.idr_pic_flag { + self.prev_ref_pic_info.frame_num = 0; + } + + let frame_num = u32::from(slice.header.frame_num); + if frame_num != self.prev_ref_pic_info.frame_num + && frame_num != (self.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num() + { + self.handle_frame_num_gap(&sps, frame_num, timestamp)?; + } + + let pic = self.init_current_pic(slice, &sps, timestamp)?; + let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic); + + // `apply_sps` above either kept the sequence or built a new one. + let sequence = self.sequence.as_ref().expect("sequence built by apply_sps"); + let context = Rc::clone(&sequence.context); + let handle = sequence.handle(timestamp)?; + + let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone()); + let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps); + picture.add_buffer(create_buffer(&context, pic_param)?); + picture.add_buffer(create_buffer(&context, build_iq_matrix(&pps))?); + + tracing::trace!("starting picture POC {}", pic.pic_order_cnt); + Ok(CurrentPicture { + pic, + pps, + handle, + picture, + ref_pic_lists, + }) + } + + /// Hands the driver one slice: its parameters, its reference lists, and the + /// slice NAL itself. + fn decode_slice(&mut self, current: &mut CurrentPicture, slice: &Slice) -> anyhow::Result<()> { + // A VA slice parameter carries both of these in 16 bits, so refuse what + // would otherwise be truncated into a plausible wrong offset. Only a + // picture past 65536 macroblocks, which is beyond 8K, gets close. + if slice.header.first_mb_in_slice > u32::from(u16::MAX) { + bail!( + "slice starts at macroblock {}, past what a VA slice parameter addresses", + slice.header.first_mb_in_slice + ); + } + if slice.header.header_bit_size > usize::from(u16::MAX) { + bail!( + "slice header is {} bits long, past what a VA slice parameter addresses", + slice.header.header_bit_size + ); + } + + // A slice may refer to a different PPS than the one that started the + // picture, as long as it names the same SPS. + let pps = Rc::clone( + self.parser + .get_pps(slice.header.pic_parameter_set_id) + .context("slice refers to an unknown PPS")?, + ); + if SequenceInfo::new(&pps.sps)? != SequenceInfo::new(¤t.pps.sps)? { + bail!("invalid stream: the sequence changed between slices of one picture"); + } + current.pps = Rc::clone(&pps); + + let (list0, list1) = self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.ref_pic_lists)?; + let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context; + + let slice_param = build_slice_param(&slice.header, slice.nalu.size, &list0, &list1, &pps.sps, &pps); + current.picture.add_buffer(create_buffer(context, slice_param)?); + current.picture.add_buffer(create_buffer( + context, + BufferType::SliceData(slice.nalu.as_ref().to_vec()), + )?); + + Ok(()) + } + + /// Submits the picture to the hardware, then runs the reference marking and + /// bumping the specification calls for once a picture is decoded. + fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> { + let CurrentPicture { + mut pic, + pps, + handle, + picture, + .. + } = current; + + run(picture)?; + tracing::trace!("decoded picture POC {}", pic.pic_order_cnt); + + if pic.is_ref() { + self.reference_pic_marking(&mut pic, &pps.sps)?; + self.prev_ref_pic_info.fill(&pic); + } + self.prev_pic_info.fill(&pic); + + // C.4.5.3 clause 3: a picture with memory_management_control_operation + // equal to 5 empties the DPB. + if pic.has_mmco_5 { + self.drain(); + } + + // C.4.5.3 clauses 1, 4, 5, and 6. + self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten()); + + // C.4.5.1: a reference picture is bumped until a frame buffer is free, + // then stored. C.4.5.2: a non-reference picture is stored if a buffer is + // free after bumping, and output directly otherwise. + if pic.is_ref() || self.dpb.has_empty_frame_buffer() { + self.dpb + .store_picture(pic.into_rc(), Some(handle)) + .map_err(|e| anyhow!("store picture in DPB: {e}"))?; + } else { + self.ready.push(handle); + } + + Ok(()) + } + + /// Builds the picture for `slice` and makes room for it in the DPB. + fn init_current_pic(&mut self, slice: &Slice, sps: &Sps, timestamp: u64) -> anyhow::Result { + // Progressive only, so a picture is never the second field of a frame. + let mut pic = PictureData::new_from_slice(slice, sps, timestamp, None); + self.compute_pic_order_count(&mut pic, sps)?; + + if matches!(pic.is_idr, IsIdr::Yes { .. }) { + // C.4.5.3 clause 2: an IDR bumps the whole DPB, unless + // no_output_of_prior_pics_flag says to discard it instead (C.4.4). + if pic.ref_pic_marking.no_output_of_prior_pics_flag { + self.dpb.clear(); + } else { + self.drain(); + } + } + + self.dpb + .update_pic_nums(u32::from(slice.header.frame_num), sps.max_frame_num(), &pic); + + Ok(pic) + } + + /// 8.2.5.2: invents the pictures for the frame numbers a lossy stream skipped, + /// so reference marking keeps working. + fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32, timestamp: u64) -> anyhow::Result<()> { + if self.dpb.is_empty() { + return Ok(()); + } + + if !sps.gaps_in_frame_num_value_allowed_flag { + bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures"); + } + tracing::debug!("frame_num gap up to {frame_num}"); + + let max_frame_num = sps.max_frame_num(); + let mut unused = (self.prev_ref_pic_info.frame_num + 1) % max_frame_num; + while unused != frame_num { + let mut pic = PictureData::new_non_existing(unused, timestamp); + self.compute_pic_order_count(&mut pic, sps)?; + + self.dpb.update_pic_nums(unused, max_frame_num, &pic); + self.dpb.sliding_window_marking(&mut pic, sps); + self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten()); + self.dpb + .store_picture(pic.into_rc(), None) + .map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?; + + unused = (unused + 1) % max_frame_num; + } + + Ok(()) + } + + /// 8.2.1: derives the picture order count, which drives output ordering. + fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> { + match pic.pic_order_cnt_type { + // 8.2.1.1 + 0 => { + let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if matches!(pic.is_idr, IsIdr::Yes { .. }) { + (0, 0) + } else if self.prev_ref_pic_info.has_mmco_5 { + if matches!(self.prev_ref_pic_info.field, Field::Bottom) { + (0, 0) + } else { + (0, self.prev_ref_pic_info.top_field_order_cnt) + } + } else { + ( + self.prev_ref_pic_info.pic_order_cnt_msb, + 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 < prev_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) { + pic.bottom_field_order_cnt = if matches!(pic.field, Field::Frame) { + pic.top_field_order_cnt + pic.delta_pic_order_cnt_bottom + } else { + pic.pic_order_cnt_msb + pic.pic_order_cnt_lsb + }; + } + } + + // 8.2.1.2 + 1 => { + if self.prev_pic_info.has_mmco_5 { + self.prev_pic_info.frame_num_offset = 0; + } + + pic.frame_num_offset = if matches!(pic.is_idr, IsIdr::Yes { .. }) { + 0 + } else if self.prev_pic_info.frame_num > pic.frame_num { + self.prev_pic_info.frame_num_offset + sps.max_frame_num() + } else { + 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 { + bail!("invalid num_ref_frames_in_pic_order_cnt_cycle"); + } + + let cycle_len = u32::from(sps.num_ref_frames_in_pic_order_cnt_cycle); + let cycles = (abs_frame_num - 1) / cycle_len; + // The cycle is only summed up to the position this frame sits + // at within it, not all the way round. + let position_in_cycle = (abs_frame_num - 1) % cycle_len; + expected_pic_order_cnt = cycles as i32 * sps.expected_delta_per_pic_order_cnt_cycle; + + for i in 0..=position_in_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; + } + + match 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; + } + Field::Top => { + pic.top_field_order_cnt = expected_pic_order_cnt + pic.delta_pic_order_cnt0; + } + Field::Bottom => { + pic.bottom_field_order_cnt = + expected_pic_order_cnt + sps.offset_for_top_to_bottom_field + pic.delta_pic_order_cnt0; + } + } + } + + // 8.2.1.3 + 2 => { + if self.prev_pic_info.has_mmco_5 { + self.prev_pic_info.frame_num_offset = 0; + } + + pic.frame_num_offset = if matches!(pic.is_idr, IsIdr::Yes { .. }) { + 0 + } else if self.prev_pic_info.frame_num > pic.frame_num { + self.prev_pic_info.frame_num_offset + sps.max_frame_num() + } else { + 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; + } + } + + other => bail!("invalid pic_order_cnt_type {other}"), + } + + pic.pic_order_cnt = match pic.field { + Field::Frame => std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt), + Field::Top => pic.top_field_order_cnt, + Field::Bottom => pic.bottom_field_order_cnt, + }; + + Ok(()) + } + + /// 8.2.5.1: marks the decoded picture as used or unused for reference. + fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> { + 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(()) + } + + /// 8.2.5.4: runs the picture's adaptive memory management control operations. + 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(()) + } + + /// 8.2.4: derives RefPicList0 and RefPicList1 for one slice, from the + /// per-picture lists the DPB built. + fn create_ref_pic_lists<'a>( + &'a self, + pic: &PictureData, + hdr: &SliceHeader, + lists: &ReferencePicLists, + ) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> { + let list0 = match hdr.slice_type { + SliceType::P | SliceType::Sp => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0)?, + SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0)?, + _ => Vec::new(), + }; + + let list1 = match hdr.slice_type { + SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1)?, + _ => Vec::new(), + }; + + Ok((list0, list1)) + } + + /// 8.2.4.3: applies the slice header's reference picture list modifications. + fn modify_ref_pic_list<'a>( + &'a self, + pic: &PictureData, + hdr: &SliceHeader, + list1: bool, + indices: &[usize], + ) -> anyhow::Result> { + let (modify, num_ref_idx_active_minus1, modifications) = if list1 { + ( + hdr.ref_pic_list_modification_flag_l1, + hdr.num_ref_idx_l1_active_minus1, + &hdr.ref_pic_list_modification_l1, + ) + } else { + ( + hdr.ref_pic_list_modification_flag_l0, + hdr.num_ref_idx_l0_active_minus1, + &hdr.ref_pic_list_modification_l0, + ) + }; + + let mut list: DpbPicRefList<'a, Handle> = indices + .iter() + .map(|&i| &self.dpb.entries()[i]) + .take(usize::from(num_ref_idx_active_minus1) + 1) + .collect(); + + if !modify { + return Ok(list); + } + + let mut pic_num_pred = pic.pic_num; + let mut ref_idx = 0; + + for modification in modifications { + match modification.modification_of_pic_nums_idc { + idc @ (0 | 1) => self.short_term_modification( + pic, + &mut list, + num_ref_idx_active_minus1, + hdr.max_pic_num as i32, + idc, + modification, + &mut pic_num_pred, + &mut ref_idx, + )?, + 2 => self.long_term_modification(&mut list, num_ref_idx_active_minus1, modification, &mut ref_idx)?, + 3 => break, + other => bail!("unexpected modification_of_pic_nums_idc {other}"), + } + } + + Ok(list) + } + + /// 8.2.4.3.1: modification for short-term reference pictures. + fn short_term_modification<'a>( + &'a self, + pic: &PictureData, + list: &mut DpbPicRefList<'a, Handle>, + num_ref_idx_active_minus1: u8, + max_pic_num: i32, + idc: u8, + modification: &RefPicListModification, + pic_num_pred: &mut i32, + ref_idx: &mut usize, + ) -> anyhow::Result<()> { + let abs_diff_pic_num = modification.abs_diff_pic_num_minus1 as i32 + 1; + + let pic_num_no_wrap = if idc == 0 { + if *pic_num_pred - abs_diff_pic_num < 0 { + *pic_num_pred - abs_diff_pic_num + max_pic_num + } else { + *pic_num_pred - abs_diff_pic_num + } + } else if *pic_num_pred + abs_diff_pic_num >= max_pic_num { + *pic_num_pred + abs_diff_pic_num - max_pic_num + } else { + *pic_num_pred + abs_diff_pic_num + }; + + *pic_num_pred = pic_num_no_wrap; + + let pic_num = if pic_num_no_wrap > pic.pic_num { + pic_num_no_wrap - max_pic_num + } else { + pic_num_no_wrap + }; + + let entry = self + .dpb + .find_short_term_with_pic_num(pic_num) + .with_context(|| format!("no short-term reference with pic_num {pic_num}"))?; + + Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| { + target.pic_num_f(max_pic_num) != pic_num + }); + + Ok(()) + } + + /// 8.2.4.3.2: modification for long-term reference pictures. + fn long_term_modification<'a>( + &'a self, + list: &mut DpbPicRefList<'a, Handle>, + num_ref_idx_active_minus1: u8, + modification: &RefPicListModification, + ref_idx: &mut usize, + ) -> anyhow::Result<()> { + let long_term_pic_num = modification.long_term_pic_num; + let max_long_term_frame_idx = self.max_long_term_frame_idx; + + let entry = self + .dpb + .find_long_term_with_long_term_pic_num(long_term_pic_num) + .with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?; + + Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| { + target.long_term_pic_num_f(max_long_term_frame_idx) != long_term_pic_num + }); + + Ok(()) + } + + /// The shared tail of 8.2.4.3.1 and 8.2.4.3.2: insert `entry` at `ref_idx`, + /// then shuffle out the duplicate `keep` identifies and re-truncate the list. + fn insert_modification<'a>( + list: &mut DpbPicRefList<'a, Handle>, + entry: &'a DpbEntry, + num_ref_idx_active_minus1: u8, + ref_idx: &mut usize, + keep: impl Fn(&PictureData) -> bool, + ) { + // A modification past the end of the list is a stream error; the spec + // only defines indices within num_ref_idx_lX_active_minus1 + 1. + let at = (*ref_idx).min(list.len()); + list.insert(at, entry); + *ref_idx = at + 1; + + let mut next = *ref_idx; + for current in *ref_idx..=usize::from(num_ref_idx_active_minus1) + 1 { + if current >= list.len() { + break; + } + + if keep(&list[current].pic.borrow()) { + list[next] = list[current]; + next += 1; + } + } + + list.truncate(usize::from(num_ref_idx_active_minus1) + 1); + } +} + +/// The picture currently being assembled, held across the slices that make it up. +struct CurrentPicture { + pic: PictureData, + /// PPS active for the last slice seen. + pps: Rc, + /// Handle to the surface the driver renders into. + handle: Handle, + picture: Picture, + /// Per-picture reference lists, modified per slice. + ref_pic_lists: ReferencePicLists, +} + +/// A decoded picture: the surface holding it plus what the caller needs to read +/// it back. Cloned into the DPB, so the surface is not recycled while it is still +/// a reference or still waiting to be output. +#[derive(Clone)] +struct Handle { + surface: Arc, + timestamp: u64, + width: u32, + height: u32, +} + +impl std::borrow::Borrow> for Handle { + fn borrow(&self) -> &Surface<()> { + self.surface.get() + } +} + +/// The properties of an SPS that the VA config, context, and surface pool are +/// built from. A change in any of them forces them to be rebuilt. +#[derive(Clone, Debug, PartialEq, Eq)] +struct SequenceInfo { + visible: (u32, u32), + coded: (u32, u32), + profile_idc: u8, + bit_depth_luma_minus8: u8, + bit_depth_chroma_minus8: u8, + chroma_format_idc: u8, + frame_mbs_only_flag: bool, + max_dpb_frames: usize, +} + +impl SequenceInfo { + fn new(sps: &Sps) -> anyhow::Result { + if !sps.frame_mbs_only_flag { + bail!("interlaced H.264 is not supported"); + } + if sps.chroma_format_idc != 1 { + bail!( + "only 4:2:0 chroma is supported, got chroma_format_idc {}", + sps.chroma_format_idc + ); + } + if sps.bit_depth_luma_minus8 != 0 || sps.bit_depth_chroma_minus8 != 0 { + bail!( + "only 8-bit samples are supported, got {}-bit luma and {}-bit chroma", + sps.bit_depth_luma_minus8 + 8, + sps.bit_depth_chroma_minus8 + 8 + ); + } + + if sps.frame_cropping_flag && (sps.frame_crop_left_offset != 0 || sps.frame_crop_top_offset != 0) { + bail!("left and top H.264 cropping is not supported"); + } + let (crop_right, crop_bottom) = if sps.frame_cropping_flag { + (sps.frame_crop_right_offset, sps.frame_crop_bottom_offset) + } else { + (0, 0) + }; + let width = crop_right + .checked_mul(2) + .and_then(|crop| sps.width().checked_sub(crop)) + .context("invalid horizontal H.264 crop")?; + let height = crop_bottom + .checked_mul(2) + .and_then(|crop| sps.height().checked_sub(crop)) + .context("invalid vertical H.264 crop")?; + if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 { + bail!("visible size {width}x{height} is not a non-zero even 4:2:0 size"); + } + + Ok(Self { + visible: (width, height), + coded: (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, + frame_mbs_only_flag: sps.frame_mbs_only_flag, + max_dpb_frames: sps.max_dpb_frames(), + }) + } +} + +/// What the VA config, context, and surface pool of a sequence are built for. +/// A change in any of it rebuilds them. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Format { + codec: Codec, + profile: VAProfile::Type, + coded: (u32, u32), + /// The size after cropping, which is what a [`Frame`] reports. + visible: (u32, u32), + /// The most pictures the DPB holds, which bounds what the pool keeps free. + max_dpb_frames: usize, +} + +/// The VA state for one coded video sequence. +struct Sequence { + format: Format, + pool: SurfacePool, + // Drop order: the context must go before the config it was created from. + context: Rc, + _config: VaConfig, +} + +impl Sequence { + fn new(display: &Arc, format: Format) -> anyhow::Result { + let attrs = vec![VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribRTFormat, + value: VA_RT_FORMAT_YUV420, + }]; + let config = display + .create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD) + .map_err(|e| anyhow!("create VA config: {e:?}"))?; + + let (coded_width, coded_height) = format.coded; + let context = display + .create_context::<()>(&config, coded_width, coded_height, None, true) + .map_err(|e| anyhow!("create VA context: {e:?}"))?; + + let (width, height) = format.visible; + tracing::info!( + "VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \ + VA profile {}, DPB {} frames", + format.codec, + format.profile, + format.max_dpb_frames + ); + + // What the decoder itself can need at once: a full DPB plus the picture + // being decoded. Anything free beyond that was let go by a consumer that + // had been holding pictures, and is memory the stream will not ask for + // again. + let capacity = format.max_dpb_frames + 1; + Ok(Self { + pool: SurfacePool::new( + display, + (coded_width, coded_height), + UsageHint::USAGE_HINT_DECODER, + capacity, + ), + format, + context, + _config: config, + }) + } + + /// Returns a surface to decode a picture coded at `timestamp` into. + fn handle(&self, timestamp: u64) -> anyhow::Result { + let (width, height) = self.format.visible; + Ok(Handle { + surface: Arc::new(self.pool.alloc()?), + timestamp, + width, + height, + }) + } +} + +/// Submits a picture with all its buffers added, and waits for it to decode. +/// +/// The wait comes before the surface enters the DPB: it is about to be read as +/// a reference by later pictures, and the caller may never ask for its pixels. +/// Dropping the synced picture frees the VA buffers with it. +fn run(picture: Picture) -> anyhow::Result<()> { + let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?; + let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?; + let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?; + drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?); + Ok(()) +} + +/// Exports a decoded surface as a DRM PRIME descriptor, copying nothing. +fn export(handle: &Handle) -> anyhow::Result { + ExportedFrame::export( + Arc::clone(&handle.surface), + handle.timestamp, + (handle.width, handle.height), + ) +} + +/// Reads a decoded surface back to client memory as tightly packed NV12. +fn download(handle: &Handle) -> anyhow::Result { + read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height) +} + +/// Reads `surface` back to client memory as tightly packed NV12, cropped to +/// `width` by `height`. +/// +/// The one read-back path, shared by the picture a decoder downloads itself and +/// the one a caller took as a descriptor and later wants on the CPU after all. +fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result { + surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?; + + let visible = (width, height); + + // vaDeriveImage exposes the surface's own buffer, so the copy below is the + // only one. Not every driver can derive every surface; fall back to + // vaCreateImage + vaGetImage, which always works but copies inside the driver + // first. + match Image::derive_from(surface, visible) { + Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => { + return pack_nv12(&image, timestamp, width, height); + } + Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"), + Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"), + } + + let format = surface + .display() + .query_image_formats() + .map_err(|e| anyhow!("query image formats: {e:?}"))? + .into_iter() + .find(|format| format.fourcc == VA_FOURCC_NV12) + .context("driver has no NV12 image format")?; + let image = Image::create_from(surface, format, surface.size(), visible) + .map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?; + + pack_nv12(&image, timestamp, width, height) +} + +/// Copies a mapped NV12 image into a tightly packed buffer, dropping the row +/// padding the driver's pitch may carry. +fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result { + let va_image = image.image(); + let src: &[u8] = image.as_ref(); + let (width, height) = (frame_width as usize, frame_height as usize); + let chroma_rows = height / 2; + + let mut data = vec![0u8; width * (height + chroma_rows)]; + let (luma, chroma) = data.split_at_mut(width * height); + copy_plane( + luma, + src, + va_image.offsets[0] as usize, + va_image.pitches[0] as usize, + width, + height, + )?; + copy_plane( + chroma, + src, + va_image.offsets[1] as usize, + va_image.pitches[1] as usize, + width, + chroma_rows, + )?; + + Ok(Frame { + timestamp, + width: frame_width, + height: frame_height, + data, + }) +} + +/// Copies `rows` rows of `width` bytes out of a strided plane. +fn copy_plane( + dst: &mut [u8], + src: &[u8], + offset: usize, + pitch: usize, + width: usize, + rows: usize, +) -> anyhow::Result<()> { + if rows == 0 { + return Ok(()); + } + let end = offset + pitch * (rows - 1) + width; + if pitch < width || src.len() < end { + bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes"); + } + + for row in 0..rows { + let from = offset + row * pitch; + dst[row * width..][..width].copy_from_slice(&src[from..from + width]); + } + + Ok(()) +} + +/// Checks that `display`'s driver can decode `codec`, which is what [`Decoder::new`] needs of a render node. +/// +/// # Errors +/// +/// Fails unless the driver offers `VAEntrypointVLD` for a Constrained +/// Baseline, Main, or High profile (H.264) or for the Main profile (H.265), +/// or when it cannot be asked. +pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> { + let profiles = display + .query_config_profiles() + .map_err(|e| anyhow!("query VA profiles: {e:?}"))?; + + let supported = profiles + .into_iter() + .filter(|profile| match codec { + Codec::H264 => matches!( + *profile, + VAProfile::VAProfileH264ConstrainedBaseline + | VAProfile::VAProfileH264Main + | VAProfile::VAProfileH264High + ), + Codec::H265 => *profile == VAProfile::VAProfileHEVCMain, + }) + .any(|profile| { + display + .query_config_entrypoints(profile) + .is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD)) + }); + + if !supported { + bail!("driver exposes no {codec:?} decode entrypoint"); + } + + Ok(()) +} + +/// Maps the SPS profile onto the VA profile to open the config with. +fn va_profile(sps: &Sps) -> anyhow::Result { + let profile = Profile::try_from(sps.profile_idc).map_err(|e| anyhow!("{e}"))?; + + Ok(match profile { + // VA-API has no plain Baseline profile, and the picture parameter buffer + // has no way to describe the FMO and ASO tools that are all that separate + // it from Constrained Baseline (num_slice_groups_minus1 is pinned to 0 + // below), so both map here. A stream that really uses them decodes wrong + // rather than not at all, which no encoder in this decade emits. + Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline, + Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main, + // The bit depth and chroma format are checked separately, so a High10 or + // High422 SPS only reaches here when its samples are 8-bit 4:2:0. + Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High, + }) +} + +fn create_buffer(context: &Rc, buffer: BufferType) -> anyhow::Result { + context + .create_buffer(buffer) + .map_err(|e| anyhow!("create VA buffer: {e:?}")) +} + +/// Cached variables from the previous reference picture, needed by 8.2.1. +#[derive(Debug)] +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: 0, + has_mmco_5: false, + top_field_order_cnt: 0, + pic_order_cnt_msb: 0, + pic_order_cnt_lsb: 0, + field: Field::Frame, + } + } +} + +impl PrevReferencePicInfo { + 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; + } +} + +/// Cached variables from the previous picture, needed by 8.2.1. +#[derive(Debug, Default)] +struct PrevPicInfo { + frame_num: u32, + frame_num_offset: u32, + has_mmco_5: bool, +} + +impl PrevPicInfo { + 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; + } +} + +/// The surface a DPB entry decoded into, or `VA_INVALID_ID` for the non-existing +/// pictures invented for a frame_num gap. +fn va_surface_id(handle: &Option) -> bindings::VASurfaceID { + match handle { + Some(handle) => handle.surface.id(), + None => VA_INVALID_ID, + } +} + +/// Ported from cros-codecs `fill_va_h264_pic` (BSD-3-Clause). Progressive only, +/// so the field cases collapse to the frame one. +fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 { + let mut flags = 0; + let frame_idx = match pic.reference() { + Reference::LongTerm => { + flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE; + pic.long_term_frame_idx + } + Reference::ShortTerm => { + flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE; + pic.frame_num + } + Reference::None => pic.frame_num, + }; + + PictureH264::new( + surface_id, + frame_idx, + flags, + pic.top_field_order_cnt, + pic.bottom_field_order_cnt, + ) +} + +/// Builds the picture used to fill the array slots there is no reference for. +fn build_invalid_va_h264_pic() -> PictureH264 { + PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0) +} + +/// Ported from cros-codecs `build_iq_matrix` (BSD-3-Clause). VA-API wants the +/// scaling lists in raster order, the PPS carries them zig-zag. +fn build_iq_matrix(pps: &Pps) -> BufferType { + const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + #[rustfmt::skip] + 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, + ]; + + let mut scaling_list4x4 = [[0u8; 16]; 6]; + for (list, src) in scaling_list4x4.iter_mut().zip(pps.scaling_lists_4x4.iter()) { + for (i, &value) in src.iter().enumerate() { + list[ZIGZAG_4X4[i]] = value; + } + } + + let mut scaling_list8x8 = [[0u8; 64]; 2]; + for (list, src) in scaling_list8x8.iter_mut().zip(pps.scaling_lists_8x8.iter()) { + for (i, &value) in src.iter().enumerate() { + list[ZIGZAG_8X8[i]] = value; + } + } + + BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new( + scaling_list4x4, + scaling_list8x8, + ))) +} + +/// Ported from cros-codecs `build_pic_param` (BSD-3-Clause). +fn build_pic_param( + hdr: &SliceHeader, + pic: &PictureData, + surface_id: bindings::VASurfaceID, + dpb: &Dpb, + sps: &Sps, + pps: &Pps, +) -> BufferType { + let curr_pic = fill_va_h264_pic(pic, surface_id); + + let short_term = dpb + .short_term_refs_iter() + .filter(|entry| !entry.pic.borrow().nonexisting); + let mut refs: Vec = short_term + .chain(dpb.long_term_refs_iter()) + .take(16) + .map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference))) + .collect(); + refs.resize_with(16, build_invalid_va_h264_pic); + let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16")); + + let seq_fields = 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, + // See A.3.3.2. + (sps.level_idc >= Level::L3_1) 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 pic_fields = 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, + (pic.nal_ref_idc != 0) as u32, + ); + + // SequenceInfo rejects interlaced input, so map units are frame macroblocks. + let picture_height_in_mbs_minus1 = sps.pic_height_in_map_units_minus1; + + BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new( + curr_pic, + 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, + // FMO is not expressible in VA-API. + 0, + 0, + 0, + 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, + ))) +} + +/// Ported from cros-codecs `fill_ref_pic_list` (BSD-3-Clause). +fn fill_ref_pic_list(list: &[&DpbEntry]) -> [PictureH264; 32] { + let mut pics: Vec = list + .iter() + .take(32) + .map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference))) + .collect(); + pics.resize_with(32, build_invalid_va_h264_pic); + + pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32")) +} + +/// Ported from cros-codecs `build_slice_param` (BSD-3-Clause). +fn build_slice_param( + hdr: &SliceHeader, + slice_size: usize, + list0: &[&DpbEntry], + list1: &[&DpbEntry], + sps: &Sps, + pps: &Pps, +) -> BufferType { + let pwt = &hdr.pred_weight_table; + + let mut luma_weight_l0 = [0i16; 32]; + let mut luma_offset_l0 = [0i16; 32]; + let mut chroma_weight_l0 = [[0i16; 2]; 32]; + let mut chroma_offset_l0 = [[0i16; 2]; 32]; + + let mut luma_weight_l1 = [0i16; 32]; + let mut luma_offset_l1 = [0i16; 32]; + let mut chroma_weight_l1 = [[0i16; 2]; 32]; + let mut chroma_offset_l1 = [[0i16; 2]; 32]; + + // Explicit weighted prediction: P and SP slices weight list 0 only, B slices + // weight both. Implicit (weighted_bipred_idc 2) is derived by the hardware. + let fill_l0 = (pps.weighted_pred_flag && (hdr.slice_type.is_p() || hdr.slice_type.is_sp())) + || (pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b()); + let fill_l1 = pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b(); + let chroma = sps.chroma_array_type() != 0; + + if fill_l0 { + for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { + luma_weight_l0[i] = pwt.luma_weight_l0[i]; + luma_offset_l0[i] = i16::from(pwt.luma_offset_l0[i]); + if chroma { + 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 { + for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { + luma_weight_l1[i] = pwt.luma_weight_l1[i]; + luma_offset_l1[i] = i16::from(pwt.luma_offset_l1[i]); + if chroma { + 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]); + } + } + } + } + + BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new( + slice_size as u32, + 0, + 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, + fill_ref_pic_list(list0), + fill_ref_pic_list(list1), + pwt.luma_log2_weight_denom, + pwt.chroma_log2_weight_denom, + fill_l0 as u8, + luma_weight_l0, + luma_offset_l0, + (fill_l0 && chroma) as u8, + chroma_weight_l0, + chroma_offset_l0, + fill_l1 as u8, + luma_weight_l1, + luma_offset_l1, + (fill_l1 && chroma) as u8, + chroma_weight_l1, + chroma_offset_l1, + ))) +} + +#[cfg(test)] +mod tests { + use std::os::fd::OwnedFd; + use std::process::Command; + + use super::*; + + fn progressive_sps() -> Sps { + Sps { + frame_mbs_only_flag: true, + chroma_format_idc: 1, + pic_width_in_mbs_minus1: 19, + pic_height_in_map_units_minus1: 14, + ..Default::default() + } + } + + #[test] + fn rejects_nonzero_crop_origins() { + for (left, top) in [(1, 0), (0, 1)] { + let sps = Sps { + frame_cropping_flag: true, + frame_crop_left_offset: left, + frame_crop_top_offset: top, + ..progressive_sps() + }; + assert!(SequenceInfo::new(&sps) + .unwrap_err() + .to_string() + .contains("left and top")); + } + } + + #[test] + fn crop_only_updates_change_sequence_identity() { + let original = SequenceInfo::new(&progressive_sps()).unwrap(); + for (right, bottom, expected) in [(1, 0, (318, 240)), (0, 1, (320, 238))] { + let cropped = SequenceInfo::new(&Sps { + frame_cropping_flag: true, + frame_crop_right_offset: right, + frame_crop_bottom_offset: bottom, + ..progressive_sps() + }) + .unwrap(); + assert_eq!(original.coded, cropped.coded); + assert_eq!(cropped.visible, expected); + assert_ne!(original, cropped); + } + } + + #[test] + fn rejects_invalid_crop_dimensions() { + for crop in [160, 161, u32::MAX] { + assert!(SequenceInfo::new(&Sps { + frame_cropping_flag: true, + frame_crop_right_offset: crop, + ..progressive_sps() + }) + .is_err()); + } + } + + #[test] + fn maximum_progressive_height_does_not_overflow_va_parameters() { + let sps = Rc::new(Sps { + pic_height_in_map_units_minus1: u16::MAX, + ..progressive_sps() + }); + let params = build_pic_param( + &SliceHeader::default(), + &PictureData::new_non_existing(0, 0), + VA_INVALID_ID, + &Dpb::default(), + &sps, + &crate::codec::h264::parser::PpsBuilder::new(Rc::clone(&sps)).build(), + ); + let BufferType::PictureParameter(PictureParameter::H264(params)) = params else { + panic!("expected H.264 picture parameters"); + }; + assert_eq!(params.inner().picture_height_in_mbs_minus1, u16::MAX); + assert!(SequenceInfo::new(&Sps { + frame_mbs_only_flag: false, + ..progressive_sps() + }) + .is_err()); + } + + /// Encoder settings shared by the tests that need a stream rather than a + /// particular picture. + fn encoder_config(width: u32, height: u32) -> crate::encode::Config { + crate::encode::Config::new(width, height, 30, 2_000_000, 30) + } + + /// A gray field with a moving block, so a picture that decoded into the + /// wrong surface is visible as the block being in the wrong place. + fn nv12_frame(width: u32, height: u32, step: u32) -> Vec { + let (w, h) = (width as usize, height as usize); + let mut data = vec![128u8; w * h * 3 / 2]; + let x0 = (step * 16) as usize % (w / 2); + for y in h / 4..h / 2 { + for x in x0..x0 + w / 4 { + data[y * w + x] = 235; + } + } + data + } + + /// Exported pictures the caller still holds never share a surface. + /// + /// The invariant `export` exists to keep: a held surface stays out of the + /// pool, because recycling it would have a later picture decoded over pixels + /// the caller still holds a descriptor for. Two pictures coming + /// back with the same modifier and layout is expected; two coming back on + /// the same allocation is the bug. The modifier itself is hardware policy, + /// so it is printed rather than asserted. + #[test] + fn exported_pictures_do_not_share_a_surface() { + let (width, height) = (320u32, 240u32); + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + let Ok(mut decoder) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + + let mut exported = Vec::new(); + for step in 0..8 { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step), step == 0) + .expect("encode a picture"); + exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture")); + } + exported.extend(decoder.flush_exported().expect("flush the decoder")); + assert!(!exported.is_empty(), "the decoder produced no pictures"); + + let first = &exported[0]; + eprintln!( + "exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}", + exported.len(), + first.width, + first.height, + first.descriptor.fourcc, + first.descriptor.objects[0].drm_format_modifier + ); + + let mut seen = Vec::new(); + for (index, frame) in exported.iter().enumerate() { + assert_eq!((frame.width, frame.height), (width, height)); + assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12); + assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object"); + assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes"); + + // Two live descriptors for one allocation would mean the pool handed + // a held surface back out. The inode behind a DMA-BUF names the + // buffer, and is what identifies one allocation from another. + let inode = inode(&frame.descriptor.objects[0].fd); + assert!( + !seen.contains(&inode), + "picture {index} was decoded into an allocation an earlier one still holds" + ); + seen.push(inode); + } + } + + /// With no node named, the decoder opens one that decodes H.264. A named + /// node is used or refused, never swapped for another. + #[test] + fn the_render_node_is_found_or_named() { + if let Err(err) = Decoder::new(Config::new()) { + eprintln!("skipping: no VA-API H.264 decoder: {err:#}"); + return; + } + let named = Config { + device: Some(PathBuf::from("/dev/null")), + ..Config::new() + }; + assert!( + Decoder::new(named).is_err(), + "a named node that is not a render node was swapped for one that is" + ); + } + + /// Every picture fed in comes back out, the last of them only on flush. + /// + /// C.4.5.3 bumps the DPB when a new picture needs a slot, so a stream that + /// simply stops leaves its tail sitting there: one picture for this crate's + /// IPPP encoder, three for a stream coded the way x264 does by default. The + /// first assertion keeps the test honest, since a decoder that held nothing + /// back would satisfy the rest without a flush ever running. + #[test] + fn flush_returns_the_pictures_the_dpb_still_holds() { + const PICTURES: u64 = 5; + let (width, height) = (320u32, 240u32); + + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + let Ok(mut decoder) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + + let mut streamed = Vec::new(); + for step in 0..PICTURES { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step as u32), step == 0) + .expect("encode a picture"); + streamed.extend(decoder.decode(&unit, step).expect("decode a picture")); + } + assert!( + (streamed.len() as u64) < PICTURES, + "the DPB held nothing back, so this test proves nothing" + ); + + let flushed = decoder.flush().expect("flush the decoder"); + let timestamps: Vec = streamed + .iter() + .chain(&flushed) + .map(|picture| picture.timestamp) + .collect(); + assert_eq!( + timestamps, + (0..PICTURES).collect::>(), + "the stream lost pictures at its end" + ); + + // The bumping process marks what it hands out, so a second flush finds + // nothing and a caller that flushes twice never sees a picture twice. + assert!(decoder.flush().expect("flush an empty decoder").is_empty()); + } + + /// A picture the consumer has let go of is decoded into again rather than + /// replaced by a new allocation, and the recycled surfaces still carry the + /// right pictures. + /// + /// Each picture is read back and dropped before the next access unit goes + /// in, the way a renderer that draws a picture and moves on behaves. Without + /// recycling this allocated one surface per picture. + #[test] + fn a_dropped_export_is_decoded_into_again() { + const PICTURES: u32 = 60; + let (width, height) = (320u32, 240u32); + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + let Ok(mut exporting) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + let mut downloading = Decoder::new(Config::new()).expect("a second decoder"); + + let mut compared = 0; + for step in 0..PICTURES { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step), step == 0) + .expect("encode a picture"); + let exported = exporting + .decode_exported(&unit, step as u64) + .expect("decode to a descriptor"); + let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory"); + assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed"); + for (gpu, cpu) in exported.iter().zip(&downloaded) { + let read_back = gpu.download().expect("read the exported surface back"); + assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp); + compared += 1; + } + } + assert!(compared > 0, "the decoder produced no pictures"); + + let pool = &exporting.sequence().expect("a sequence").pool; + let allocated = pool.allocated.get(); + eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures"); + assert!( + allocated <= pool.free.capacity, + "{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}", + pool.free.capacity + ); + } + + /// A consumer that holds many pictures and then lets them all go leaves at + /// most the pool's capacity behind, and the next pictures reuse those. + #[test] + fn the_pool_keeps_a_bounded_number_of_free_surfaces() { + const HELD: u32 = 40; + let (width, height) = (320u32, 240u32); + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + let Ok(mut decoder) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + + let mut step = 0; + let mut decode = |decoder: &mut Decoder| { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step), step == 0) + .expect("encode a picture"); + step += 1; + decoder.decode_exported(&unit, step as u64).expect("decode a picture") + }; + + let mut held = Vec::new(); + for _ in 0..HELD { + held.extend(decode(&mut decoder)); + } + let pool = &decoder.sequence().expect("a sequence").pool; + let allocated = pool.allocated.get(); + assert!( + allocated >= held.len(), + "{} pictures held on {allocated} surfaces", + held.len() + ); + + drop(held); + let free = pool.free.surfaces.lock().unwrap().len(); + assert!( + free <= pool.free.capacity, + "{free} surfaces left free, more than the capacity of {}", + pool.free.capacity + ); + + for _ in 0..10 { + drop(decode(&mut decoder)); + } + let pool = &decoder.sequence().expect("a sequence").pool; + assert_eq!( + pool.allocated.get(), + allocated, + "pictures after the release did not reuse the free surfaces" + ); + } + + /// An exported picture crosses threads, which is the point of handing one to + /// a renderer: the decoder runs on its own thread and the frame outlives it. + /// [`Decoder`] is neither [`Send`] nor [`Sync`], so this pins that the export + /// does not inherit that. + #[test] + fn an_exported_frame_is_send_and_sync() { + const fn assert_send_sync() {} + assert_send_sync::(); + } + + /// An exported picture reads back to the same pixels the ordinary path + /// downloads. + /// + /// The invariant that lets a GPU-resident frame keep a CPU fallback: the + /// surface travels with the descriptor, so `vaDeriveImage` still + /// reaches the picture the descriptor points at. One stream through two + /// decoders, so both sides see the same pictures in the same order and the + /// comparison is exact rather than approximate. + #[test] + fn an_exported_picture_downloads_to_the_same_pixels() { + let (width, height) = (320u32, 240u32); + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + let Ok(mut exporting) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + let mut downloading = Decoder::new(Config::new()).expect("a second decoder"); + + let mut exported = Vec::new(); + let mut downloaded = Vec::new(); + for step in 0..8 { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step), step == 0) + .expect("encode a picture"); + exported.extend( + exporting + .decode_exported(&unit, step as u64) + .expect("decode to a descriptor"), + ); + downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory")); + } + exported.extend(exporting.flush_exported().expect("flush the exporting decoder")); + downloaded.extend(downloading.flush().expect("flush the downloading decoder")); + + assert!(!exported.is_empty(), "the decoder produced no pictures"); + assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed"); + + for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() { + let read_back = gpu.download().expect("read the exported surface back"); + assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp"); + assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height)); + assert!( + read_back.data == cpu.data, + "picture {index} read back differently than it downloaded" + ); + } + } + + /// Every picture matches what ffmpeg's software decoder makes of the same + /// stream, bit for bit, in either codec. + /// + /// The test that says this is a decoder rather than plumbing. The streams + /// are coded with B-frames and three reference frames, so matching the + /// reference means the reference lists, the picture order counts, and the + /// DPB bumping are all right, not just the surfaces. The second size crops + /// on the right and bottom. Half the pictures are taken as descriptors and + /// downloaded after, so both ways out are checked. Skips without ffmpeg, + /// its encoder, or a device. + #[test] + fn decoded_pictures_match_a_software_decoder() { + const PICTURES: usize = 30; + + for codec in [Codec::H264, Codec::H265] { + for (width, height) in [(320u32, 240u32), (852, 478)] { + let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else { + eprintln!("skipping: no ffmpeg that encodes {codec:?}"); + continue; + }; + let reference = software_decode(codec, &stream); + + let picture_len = (width * height * 3 / 2) as usize; + assert_eq!( + reference.len(), + PICTURES * picture_len, + "ffmpeg decoded a different count" + ); + + let Ok(mut decoder) = Decoder::new(Config { codec, ..Config::new() }) else { + eprintln!("skipping: no VA-API {codec:?} decoder"); + continue; + }; + + let units = split_access_units(codec, &stream); + let mut decoded = Vec::new(); + for (index, unit) in units.iter().enumerate() { + if index % 2 == 0 { + decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit")); + } else { + for exported in decoder + .decode_exported(unit, index as u64) + .expect("decode an access unit") + { + decoded.push(exported.download().expect("download an exported picture")); + } + } + } + decoded.extend(decoder.flush().expect("flush the decoder")); + assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures"); + + let mut timestamps: Vec = decoded.iter().map(|picture| picture.timestamp).collect(); + assert!( + timestamps.windows(2).any(|pair| pair[0] > pair[1]), + "the {codec:?} stream came out in decode order, so nothing here tests reordering" + ); + timestamps.sort_unstable(); + assert_eq!( + timestamps, + (0..PICTURES as u64).collect::>(), + "a {codec:?} picture's timestamp did not survive reordering" + ); + + for (index, picture) in decoded.iter().enumerate() { + assert_eq!((picture.width, picture.height), (width, height)); + assert!( + picture.data == reference[index * picture_len..][..picture_len], + "{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder" + ); + } + } + } + } + + /// An H.265 stream coded without reordering comes out as it decodes: C.5.2 + /// bumps by the SPS's reorder limit, which is zero, rather than holding + /// pictures until the DPB fills the way H.264's C.4.5.3 does. + #[test] + fn h265_without_reordering_comes_out_as_it_decodes() { + const PICTURES: usize = 10; + + let Some(stream) = software_encode(Codec::H265, (320, 240), PICTURES, false) else { + eprintln!("skipping: no ffmpeg that encodes H.265"); + return; + }; + let Ok(mut decoder) = Decoder::new(Config { + codec: Codec::H265, + ..Config::new() + }) else { + eprintln!("skipping: no VA-API H.265 decoder"); + return; + }; + + for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() { + let decoded = decoder.decode(unit, index as u64).expect("decode an access unit"); + let timestamps: Vec = decoded.iter().map(|picture| picture.timestamp).collect(); + assert_eq!(timestamps, [index as u64], "access unit {index} was held back"); + } + assert!(decoder.flush().expect("flush the decoder").is_empty()); + } + + /// A 4K H.265 stream coded with wavefronts, as x265 codes by default, signals + /// an entry point per CTB row: 33 at 64-pixel CTBs, past what a fixed array + /// of 32 held. + #[test] + fn a_4k_h265_wavefront_stream_decodes() { + const PICTURES: usize = 2; + let size = (3840, 2160); + + let Some(stream) = software_encode(Codec::H265, size, PICTURES, false) else { + eprintln!("skipping: no ffmpeg that encodes H.265"); + return; + }; + let Ok(mut decoder) = Decoder::new(Config { + codec: Codec::H265, + ..Config::new() + }) else { + eprintln!("skipping: no VA-API H.265 decoder"); + return; + }; + + let mut decoded = Vec::new(); + for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() { + decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit")); + } + decoded.extend(decoder.flush().expect("flush the decoder")); + assert_eq!(decoded.len(), PICTURES); + assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size)); + } + + /// A second H.265 sequence at another size decodes at that size, and the + /// first sequence's tail comes out ahead of it. + #[test] + fn a_new_h265_sequence_decodes_at_its_own_size() { + const PER_SEQUENCE: usize = 6; + let sizes = [(320u32, 240u32), (192u32, 144u32)]; + + let mut stream = Vec::new(); + for &size in &sizes { + let Some(sequence) = software_encode(Codec::H265, size, PER_SEQUENCE, true) else { + eprintln!("skipping: no ffmpeg that encodes H.265"); + return; + }; + stream.extend(sequence); + } + let Ok(mut decoder) = Decoder::new(Config { + codec: Codec::H265, + ..Config::new() + }) else { + eprintln!("skipping: no VA-API H.265 decoder"); + return; + }; + + let mut decoded = Vec::new(); + let units = split_access_units(Codec::H265, &stream); + for (index, unit) in units.iter().enumerate() { + decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit")); + } + decoded.extend(decoder.flush().expect("flush the decoder")); + + let expected: Vec<(u32, u32)> = sizes + .iter() + .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE)) + .collect(); + let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect(); + assert_eq!(actual, expected, "a picture came out at the wrong size or out of order"); + + for picture in &decoded { + let expected_len = (picture.width * picture.height * 3 / 2) as usize; + assert_eq!( + picture.data.len(), + expected_len, + "a picture was read back at the wrong size" + ); + } + } + + /// A second sequence at another size decodes at that size, and the first + /// sequence's tail comes out ahead of it. + /// + /// What `apply_sps` promises: an SPS that changes the coded size rebuilds the + /// VA context and the surface pool, and everything decoded against the old + /// one is let out first so no picture is read back at the wrong size. + #[test] + fn a_new_sequence_decodes_at_its_own_size() { + const PER_SEQUENCE: u32 = 6; + let sizes = [(320u32, 240u32), (192u32, 144u32)]; + + let Ok(mut decoder) = Decoder::new(Config::new()) else { + eprintln!("skipping: no VA-API H.264 decoder"); + return; + }; + + let mut decoded = Vec::new(); + let mut timestamp = 0u64; + for &(width, height) in &sizes { + let Ok(mut encoder) = crate::encode::Encoder::new(encoder_config(width, height)) else { + eprintln!("skipping: no VA-API H.264 encoder"); + return; + }; + for step in 0..PER_SEQUENCE { + let unit = encoder + .encode_nv12(&nv12_frame(width, height, step), step == 0) + .expect("encode a picture"); + decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture")); + timestamp += 1; + } + } + decoded.extend(decoder.flush().expect("flush the decoder")); + + let expected: Vec<(u32, u32)> = sizes + .iter() + .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize)) + .collect(); + let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect(); + assert_eq!(actual, expected, "a picture came out at the wrong size or out of order"); + + let timestamps: Vec = decoded.iter().map(|picture| picture.timestamp).collect(); + assert_eq!(timestamps, (0..timestamp).collect::>()); + + for picture in &decoded { + let expected_len = (picture.width * picture.height * 3 / 2) as usize; + assert_eq!( + picture.data.len(), + expected_len, + "a picture was read back at the wrong size" + ); + } + } + + /// Runs ffmpeg with `args`, returning its standard output, or `None` when + /// ffmpeg is missing or refused the arguments. + fn ffmpeg(args: &[&str]) -> Option> { + let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?; + if !output.status.success() { + eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); + return None; + } + Some(output.stdout) + } + + /// Encodes `pictures` of ffmpeg's test pattern at `size`, with two B-frames + /// and three reference frames when `reorder` is set and neither otherwise, + /// returning the Annex-B stream. `None` without ffmpeg or its encoder. + fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option> { + let source = format!("testsrc2=size={width}x{height}:rate=30"); + let pictures = pictures.to_string(); + let mut args = vec![ + "-f", + "lavfi", + "-i", + &source, + "-frames:v", + &pictures, + "-pix_fmt", + "yuv420p", + ]; + + let x265; + match codec { + Codec::H264 => args.extend([ + "-c:v", + "libx264", + "-profile:v", + "main", + "-bf", + if reorder { "2" } else { "0" }, + "-refs", + if reorder { "3" } else { "1" }, + "-g", + "15", + "-f", + "h264", + ]), + Codec::H265 => { + // x265's defaults are open GOPs, so the second keyframe is a CRA + // picture with leading pictures that refer across it. + x265 = if reorder { + "bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error" + } else { + "bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error" + }; + args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]); + } + } + args.push("-"); + ffmpeg(&args) + } + + /// Decodes `stream` with ffmpeg into packed NV12, one picture after another. + fn software_decode(codec: Codec, stream: &[u8]) -> Vec { + // ffmpeg reads the elementary stream from a file rather than a pipe, so + // the test never has to drain its output while still writing its input. + static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let extension = match codec { + Codec::H264 => "264", + Codec::H265 => "265", + }; + let path = std::env::temp_dir().join(format!("moq-vaapi-decode-{}-{count}.{extension}", std::process::id())); + std::fs::write(&path, stream).expect("write the elementary stream"); + let decoded = ffmpeg(&[ + "-i", + path.to_str().expect("a UTF-8 temporary path"), + "-pix_fmt", + "nv12", + "-f", + "rawvideo", + "-", + ]); + let _ = std::fs::remove_file(&path); + decoded.expect("ffmpeg decodes what it just encoded") + } + + /// Splits an Annex-B elementary stream into access units. + /// + /// A unit ends at the first slice of the next picture, or at a parameter + /// set, SEI, or delimiter that comes before one. + fn split_access_units(codec: Codec, stream: &[u8]) -> Vec> { + let starts: Vec = (0..stream.len().saturating_sub(3)) + .filter(|&i| stream[i..i + 3] == [0, 0, 1]) + .collect(); + + let mut units = Vec::new(); + let mut current: Vec = Vec::new(); + let mut current_has_picture = false; + + for (index, &start) in starts.iter().enumerate() { + let end = starts.get(index + 1).copied().unwrap_or(stream.len()); + let nal = &stream[start + 3..end]; + // The first bit after the NAL header is first_mb_in_slice == 0 for + // H.264 and first_slice_segment_in_pic_flag for H.265: either way, set + // on the first slice of a picture. + let (is_slice, starts_picture, starts_unit) = match codec { + Codec::H264 => { + let nal_type = nal[0] & 0x1f; + let is_slice = (1..=5).contains(&nal_type); + (is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9)) + } + Codec::H265 => { + let nal_type = (nal[0] >> 1) & 0x3f; + let is_slice = nal_type <= 31; + ( + is_slice, + is_slice && nal[2] & 0x80 != 0, + matches!(nal_type, 32..=35 | 39), + ) + } + }; + + if current_has_picture && (starts_picture || starts_unit) { + units.push(std::mem::take(&mut current)); + current_has_picture = false; + } + + current.extend_from_slice(&stream[start..end]); + current_has_picture |= is_slice; + } + + if !current.is_empty() { + units.push(current); + } + units + } + + /// The inode of a descriptor, which for a DMA-BUF names the allocation + /// behind it: every buffer gets its own on the anonymous dma-buf filesystem. + fn inode(fd: &OwnedFd) -> u64 { + use std::os::unix::fs::MetadataExt as _; + + // Stat a duplicate, so the descriptor the caller holds is untouched and + // the `File` wrapper closes only its own copy. + let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor")); + file.metadata().expect("stat the descriptor").ino() + } +} diff --git a/rs/moq-vaapi/src/decode/h265.rs b/rs/moq-vaapi/src/decode/h265.rs new file mode 100644 index 00000000000..6a43bfb4139 --- /dev/null +++ b/rs/moq-vaapi/src/decode/h265.rs @@ -0,0 +1,1019 @@ +//! The H.265 decoder. +//! +//! Ported from discord/cros-codecs's `decoder/stateless/h265.rs` and +//! `decoder/stateless/h265/vaapi.rs` (BSD-3-Clause), driving libva directly the +//! way the H.264 decoder beside it does. The reference picture set (8.3.2), +//! reference list construction (8.3.4), and DPB output (C.5.2) follow the +//! specification as cros-codecs does, with the screen content and range +//! extension paths left out: a sequence that needs them is rejected up front. +//! +//! Output follows C.5.2's bumping, which works from the SPS's reorder limit +//! rather than the DPB size, so a stream coded without reordering comes out the +//! moment each picture decodes. + +use std::cell::RefCell; +use std::io::Cursor; +use std::rc::Rc; +use std::sync::Arc; + +use anyhow::{anyhow, bail, Context as _}; + +use super::{create_buffer, run, Format, Handle, Sequence}; +use crate::codec::h265::dpb::{Dpb, DpbEntry}; +use crate::codec::h265::parser::{Nalu, NaluType, Parser, Pps, ScalingLists, Slice, SliceHeader, Sps}; +use crate::codec::h265::picture::{PictureData, Reference}; +use crate::codec::Codec; +use crate::{ + BufferType, Display, HevcLongSliceFlags, HevcPicFields, HevcSliceParsingFields, IQMatrix, IQMatrixBufferHEVC, + Picture, PictureHEVC, PictureParameter, PictureParameterBufferHEVC, SliceParameter, SliceParameterBufferHEVC, + VAProfile, VA_INVALID_ID, VA_PICTURE_HEVC_INVALID, VA_PICTURE_HEVC_LONG_TERM_REFERENCE, + VA_PICTURE_HEVC_RPS_LT_CURR, VA_PICTURE_HEVC_RPS_ST_CURR_AFTER, VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE, + VA_SLICE_DATA_FLAG_ALL, +}; + +/// The most pictures a DPB holds (A.4.2). +const MAX_DPB_SIZE: usize = 16; + +/// The most reference pictures a VA picture parameter buffer lists. +const MAX_VA_REFERENCES: usize = 15; + +/// The H.265 decoder. +pub(super) struct Decoder { + parser: Parser, + dpb: Dpb, + /// The SPS of the last picture begun, whose limits drive bumping (C.5.2). + sps: Option>, + /// PrevTid0Pic of 8.3.1, which the next picture's order count derives from. + prev_tid0_pic: Option, + first_picture_in_bitstream: bool, + first_picture_after_eos: bool, + /// NoRaslOutputFlag of the last IRAP picture, which decides whether the + /// RASL pictures after it can be decoded at all. + irap_no_rasl_output_flag: bool, + /// The header a dependent slice segment inherits. + last_independent_slice_header: Option, + /// VA state for the active sequence, rebuilt when the SPS changes something + /// the config, context, or surface pool depends on. + pub(super) sequence: Option, + /// Pictures bumped out of the DPB, in output order, awaiting download. + pub(super) ready: Vec, + /// Drop order: everything above borrows the display. + display: Arc, +} + +/// The picture being assembled, held across the slices that make it up. +struct CurrentPicture { + pic: PictureData, + /// The SPS the picture was begun with. + sps: Rc, + /// The reference picture set derived for it (8.3.2). + rps: RefPicSet, + /// The DPB's reference pictures, in the order the picture parameters list + /// them, which is what a slice's reference lists index into. + references: Vec>, + handle: Handle, + picture: Picture, + /// The last slice's parameters and data, held back one slice so the final + /// one can be marked as the last of the picture. + last_slice: Option<(SliceParameterBufferHEVC, Vec)>, +} + +/// The reference picture set of one picture (8.3.2). A missing entry is a +/// reference the stream names but the DPB does not hold. +#[derive(Default)] +struct RefPicSet { + st_curr_before: Vec>>, + st_curr_after: Vec>>, + st_foll: Vec>>, + lt_curr: Vec>>, + lt_foll: Vec>>, +} + +impl RefPicSet { + fn lists(&self) -> [&[Option>]; 5] { + [ + &self.st_curr_before, + &self.st_curr_after, + &self.st_foll, + &self.lt_curr, + &self.lt_foll, + ] + } + + /// 8.3.4: the reference picture lists of a slice, each as long as the + /// slice's active reference count. + fn ref_pic_lists(&self, hdr: &SliceHeader) -> anyhow::Result<[Vec>>; 2]> { + if !hdr.type_.is_p() && !hdr.type_.is_b() { + return Ok(Default::default()); + } + + // RefPicListTemp0 and RefPicListTemp1 (8-8, 8-10) repeat these until + // they are long enough, so an entry is picked modulo their length. + let before = || self.st_curr_before.iter(); + let after = || self.st_curr_after.iter(); + let long = || self.lt_curr.iter(); + let temp0: Vec<_> = before().chain(after()).chain(long()).collect(); + if temp0.is_empty() { + bail!("invalid stream: an inter slice whose reference picture set holds nothing to predict from"); + } + let temp1: Vec<_> = after().chain(before()).chain(long()).collect(); + + let rplm = &hdr.ref_pic_list_modification; + let build = |temp: &[&Option>], active_minus1: u8, modified: bool, entries: &[u32]| { + (0..=usize::from(active_minus1)) + .map(|index| { + // 8-9 and 8-11. + let index = if modified { + entries.get(index).map_or(index, |&entry| entry as usize) + } else { + index + }; + temp[index % temp.len()].clone() + }) + .collect::>() + }; + + let list0 = build( + &temp0, + hdr.num_ref_idx_l0_active_minus1, + rplm.ref_pic_list_modification_flag_l0, + &rplm.list_entry_l0, + ); + let list1 = if hdr.type_.is_b() { + build( + &temp1, + hdr.num_ref_idx_l1_active_minus1, + rplm.ref_pic_list_modification_flag_l1, + &rplm.list_entry_l1, + ) + } else { + Vec::new() + }; + + Ok([list0, list1]) + } +} + +impl Decoder { + pub(super) fn new(display: Arc) -> Self { + Self { + parser: Parser::default(), + dpb: Dpb::default(), + sps: None, + prev_tid0_pic: None, + first_picture_in_bitstream: true, + first_picture_after_eos: true, + irap_no_rasl_output_flag: false, + last_independent_slice_header: None, + sequence: None, + ready: Vec::new(), + display, + } + } + + /// Decodes one access unit into the ready queue, returning how many NAL units it held. + pub(super) fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result { + let mut cursor = Cursor::new(access_unit); + let mut current: Option = None; + let mut nalus = 0usize; + + // `Nalu::next` reports the end of the buffer as an error, so a truncated + // unit is indistinguishable from a complete one and simply stops us. + while let Ok(nalu) = Nalu::next(&mut cursor) { + nalus += 1; + match nalu.header.type_ { + NaluType::VpsNut => { + self.parser.parse_vps(&nalu).map_err(|e| anyhow!("parse VPS: {e}"))?; + } + NaluType::SpsNut => { + self.parser.parse_sps(&nalu).map_err(|e| anyhow!("parse SPS: {e}"))?; + } + NaluType::PpsNut => { + self.parser.parse_pps(&nalu).map_err(|e| anyhow!("parse PPS: {e}"))?; + } + 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 => { + let mut slice = self + .parser + .parse_slice_header(nalu) + .map_err(|e| anyhow!("parse slice header: {e}"))?; + + if slice.header.dependent_slice_segment_flag { + let header = self + .last_independent_slice_header + .clone() + .context("invalid stream: a dependent slice segment with no independent one before it")?; + slice.replace_header(header).map_err(|e| anyhow!("{e}"))?; + } else { + self.last_independent_slice_header = Some(slice.header.clone()); + } + + // An access unit normally holds one picture, but nothing + // forces that: the first segment of a picture ends the one in + // flight. + if slice.header.first_slice_segment_in_pic_flag { + if let Some(picture) = current.take() { + self.finish_picture(picture)?; + } + } + if current.is_none() { + current = self.begin_picture(&slice, timestamp)?; + } + // `None` is a RASL picture that cannot be decoded, skipped + // one slice at a time. + if let Some(picture) = current.as_mut() { + self.decode_slice(picture, &slice)?; + } + } + NaluType::EosNut => { + if let Some(picture) = current.take() { + self.finish_picture(picture)?; + } + // What follows decodes without reference to anything before, + // so nothing before has to wait for it. + self.drain(); + self.first_picture_after_eos = true; + } + NaluType::EobNut => { + if let Some(picture) = current.take() { + self.finish_picture(picture)?; + } + self.drain(); + self.first_picture_in_bitstream = true; + } + _ => {} + } + } + + // Finishing here rather than on the next unit's first slice keeps the + // hardware from holding a half-submitted picture between calls. + if let Some(picture) = current.take() { + self.finish_picture(picture)?; + } + + Ok(nalus) + } + + /// Moves the DPB to the ready queue and forgets the state the next picture + /// would otherwise be derived against, so it starts the stream over. + pub(super) fn reset(&mut self) { + self.drain(); + self.prev_tid0_pic = None; + self.first_picture_after_eos = true; + self.last_independent_slice_header = None; + } + + /// Moves everything left in the DPB to the ready queue. + fn drain(&mut self) { + self.ready.extend(self.dpb.drain().into_iter().map(|entry| entry.1)); + // What is left is reference pictures already output. + self.dpb.clear(); + } + + /// Applies `sps`, rebuilding the VA config, context, and surface pool if it + /// changes anything they depend on. + fn apply_sps(&mut self, sps: &Rc) -> anyhow::Result<()> { + let format = format(sps)?; + self.dpb.set_max_num_pics(format.max_dpb_frames); + self.sps = Some(Rc::clone(sps)); + + if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) { + return Ok(()); + } + + // Surfaces are about to change shape, so let everything decoded against + // the old sequence out first. Those handles keep their own surfaces (and + // through them the old pool) alive until they are downloaded. + self.drain(); + + self.sequence = Some(Sequence::new(&self.display, format)?); + Ok(()) + } + + /// Starts a picture: derives its order count and reference picture set, + /// makes room in the DPB, and hands the driver the picture parameters. + /// + /// Returns `None` for a RASL picture whose IRAP picture started the stream + /// over, which may refer to pictures that were never decoded (8.1.3). + fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result> { + let pps = Rc::clone( + self.parser + .get_pps(slice.header.pic_parameter_set_id) + .context("slice refers to an unknown PPS")?, + ); + let sps = Rc::clone(&pps.sps); + self.apply_sps(&sps)?; + + let max_pic_order_cnt_lsb = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); + let pic = PictureData::new_from_slice( + slice, + self.first_picture_in_bitstream, + self.first_picture_after_eos, + self.prev_tid0_pic.as_ref(), + max_pic_order_cnt_lsb, + ); + self.first_picture_in_bitstream = false; + self.first_picture_after_eos = false; + + if pic.nalu_type.is_irap() { + self.irap_no_rasl_output_flag = pic.no_rasl_output_flag; + } else if pic.nalu_type.is_rasl() && self.irap_no_rasl_output_flag { + tracing::debug!("skipping RASL picture POC {}", pic.pic_order_cnt_val); + return Ok(None); + } + + let rps = self.derive_rps(slice, &sps, &pic, max_pic_order_cnt_lsb); + self.update_dpb_before_decoding(&pic, &sps); + + let references = self.dpb.get_all_references(); + if references.len() > MAX_VA_REFERENCES { + bail!( + "invalid stream: {} reference pictures, more than the {MAX_VA_REFERENCES} a picture can use", + references.len() + ); + } + + // `apply_sps` above either kept the sequence or built a new one. + let sequence = self.sequence.as_ref().expect("sequence built by apply_sps"); + let context = Rc::clone(&sequence.context); + let handle = sequence.handle(timestamp)?; + + let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone()); + let pic_param = build_pic_param(&pic, handle.surface.id(), &references, &rps, &sps, &pps); + picture.add_buffer(create_buffer(&context, pic_param)?); + if let Some(lists) = scaling_lists(&sps, &pps) { + picture.add_buffer(create_buffer(&context, build_iq_matrix(lists))?); + } + + tracing::trace!("starting picture POC {}", pic.pic_order_cnt_val); + Ok(Some(CurrentPicture { + pic, + sps, + rps, + references, + handle, + picture, + last_slice: None, + })) + } + + /// 8.3.2: derives the current picture's reference picture set and marks the + /// DPB to match it. + fn derive_rps(&mut self, slice: &Slice, sps: &Sps, pic: &PictureData, max_pic_order_cnt_lsb: i32) -> RefPicSet { + let hdr = &slice.header; + + if pic.nalu_type.is_irap() && pic.no_rasl_output_flag { + self.dpb.mark_all_as_unused_for_ref(); + } + + let mut rps = RefPicSet::default(); + if !pic.nalu_type.is_idr() { + let poc = pic.pic_order_cnt_val; + + // 8-5: the long-term pictures, found by the low bits of their order + // count unless the stream sent the high bits too. + let mut lt_curr = Vec::new(); + let mut lt_foll = Vec::new(); + 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; + let msb = hdr.delta_poc_msb_present_flag[i]; + if msb { + poc_lt += poc + .wrapping_sub((hdr.delta_poc_msb_cycle_lt[i] as i32).wrapping_mul(max_pic_order_cnt_lsb)) + .wrapping_sub(poc & (max_pic_order_cnt_lsb - 1)); + } + if hdr.used_by_curr_pic_lt[i] { + lt_curr.push((poc_lt, msb)); + } else { + lt_foll.push((poc_lt, msb)); + } + } + + let find_long_term = |&(poc, msb): &(i32, bool)| { + let found = if msb { + self.dpb.find_ref_by_poc(poc) + } else { + self.dpb.find_ref_by_poc_masked(poc, max_pic_order_cnt_lsb - 1) + }; + if found.is_none() { + tracing::warn!("no long-term reference picture with POC {poc}"); + } + found + }; + rps.lt_curr = lt_curr.iter().map(find_long_term).collect(); + rps.lt_foll = lt_foll.iter().map(find_long_term).collect(); + for entry in rps.lt_curr.iter().chain(&rps.lt_foll).flatten() { + entry.0.borrow_mut().set_reference(Reference::LongTerm); + } + + // 8-6: the short-term pictures, after the long-term ones are marked + // so a picture is never both. + let st = 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)] + }; + let find_short_term = |poc: i32| { + let found = self.dpb.find_short_term_ref_by_poc(poc); + if found.is_none() { + tracing::warn!("no short-term reference picture with POC {poc}"); + } + found + }; + for i in 0..usize::from(st.num_negative_pics) { + let entry = find_short_term(poc.wrapping_add(st.delta_poc_s0[i])); + if st.used_by_curr_pic_s0[i] { + rps.st_curr_before.push(entry); + } else { + rps.st_foll.push(entry); + } + } + for i in 0..usize::from(st.num_positive_pics) { + let entry = find_short_term(poc.wrapping_add(st.delta_poc_s1[i])); + if st.used_by_curr_pic_s1[i] { + rps.st_curr_after.push(entry); + } else { + rps.st_foll.push(entry); + } + } + } + + // Every reference picture the set leaves out is no longer one. + for entry in self.dpb.entries() { + let kept = rps + .lists() + .iter() + .any(|list| list.iter().flatten().any(|kept| Rc::ptr_eq(&kept.0, &entry.0))); + if !kept { + entry.0.borrow_mut().set_reference(Reference::None); + } + } + + rps + } + + /// C.5.2.2: empties the DPB at a picture that starts the stream over, and + /// otherwise outputs and removes pictures until the current one fits. + fn update_dpb_before_decoding(&mut self, pic: &PictureData, sps: &Sps) { + if pic.nalu_type.is_irap() && pic.no_rasl_output_flag { + if pic.no_output_of_prior_pics_flag { + self.dpb.clear(); + } else { + self.drain(); + } + } else { + self.dpb.remove_unused(); + while self.dpb.needs_bumping(sps) { + let Some(entry) = self.dpb.bump(false) else { + break; + }; + self.ready.push(entry.1); + } + } + } + + /// Hands the driver one slice. The slice before it goes now; this one waits + /// for the next, or for [`Decoder::finish_picture`] to mark it as the last. + fn decode_slice(&mut self, current: &mut CurrentPicture, slice: &Slice) -> anyhow::Result<()> { + // A slice may refer to a different PPS than the one that started the + // picture, as long as it names the same sequence. + let pps = Rc::clone( + self.parser + .get_pps(slice.header.pic_parameter_set_id) + .context("slice refers to an unknown PPS")?, + ); + if format(&pps.sps)? != format(¤t.sps)? { + bail!("invalid stream: the sequence changed between slices of one picture"); + } + + let [list0, list1] = current.rps.ref_pic_lists(&slice.header)?; + let slice_param = build_slice_param(slice, &pps.sps, &list0, &list1, ¤t.references)?; + + let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context; + if let Some((param, data)) = current.last_slice.take() { + add_slice(&mut current.picture, context, param, data)?; + } + current.last_slice = Some((slice_param, slice.nalu.as_ref().to_vec())); + + Ok(()) + } + + /// Submits the picture to the hardware, stores it in the DPB, and outputs + /// what the store leaves over the reorder limit (C.5.2.3). + fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> { + let CurrentPicture { + pic, + handle, + mut picture, + last_slice, + .. + } = current; + + let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context; + if let Some((mut param, data)) = last_slice { + param.set_as_last(); + add_slice(&mut picture, context, param, data)?; + } + run(picture)?; + tracing::trace!("decoded picture POC {}", pic.pic_order_cnt_val); + + // 8.3.1 + if pic.valid_for_prev_tid0_pic { + self.prev_tid0_pic = Some(pic.clone()); + } + + self.dpb + .store_picture(Rc::new(RefCell::new(pic)), handle) + .map_err(|e| anyhow!("store picture in DPB: {e}"))?; + + let sps = self.sps.as_ref().expect("SPS applied by begin_picture"); + while self.dpb.needs_additional_bumping(sps) { + let Some(entry) = self.dpb.bump(false) else { + break; + }; + self.ready.push(entry.1); + } + + Ok(()) + } +} + +/// Checks that `sps` describes something this decoder handles, and returns what +/// its VA state is built for. +fn format(sps: &Sps) -> anyhow::Result { + // A.3: Main, Main 10, and Main Still Picture, either named or claimed + // through the compatibility flags, which is how a stream marks itself + // decodable by a Main decoder. + let ptl = &sps.profile_tier_level; + let main = + matches!(ptl.general_profile_idc, 1..=3) || ptl.general_profile_compatibility_flag[1..=3].contains(&true); + if !main { + bail!( + "only Main profile H.265 is supported, got general_profile_idc {}", + ptl.general_profile_idc + ); + } + if sps.chroma_format_idc != 1 { + bail!( + "only 4:2:0 chroma is supported, got chroma_format_idc {}", + sps.chroma_format_idc + ); + } + if sps.bit_depth_luma_minus8 != 0 || sps.bit_depth_chroma_minus8 != 0 { + bail!( + "only 8-bit samples are supported, got {}-bit luma and {}-bit chroma", + sps.bit_depth_luma_minus8 + 8, + sps.bit_depth_chroma_minus8 + 8 + ); + } + // H.265 codes interlaced video as a sequence of field pictures, each of + // which would otherwise come out as a frame of half the height. + if sps.vui_parameters_present_flag && sps.vui_parameters.field_seq_flag { + bail!("interlaced H.265 is not supported"); + } + + // The conformance window is in chroma samples, two luma samples each way + // for 4:2:0. + let (crop_right, crop_bottom) = if sps.conformance_window_flag { + if sps.conf_win_left_offset != 0 || sps.conf_win_top_offset != 0 { + bail!("left and top H.265 cropping is not supported"); + } + (sps.conf_win_right_offset, sps.conf_win_bottom_offset) + } else { + (0, 0) + }; + let coded = (u32::from(sps.width()), u32::from(sps.height())); + let width = crop_right + .checked_mul(2) + .and_then(|crop| coded.0.checked_sub(crop)) + .context("invalid horizontal H.265 crop")?; + let height = crop_bottom + .checked_mul(2) + .and_then(|crop| coded.1.checked_sub(crop)) + .context("invalid vertical H.265 crop")?; + if width == 0 || height == 0 { + bail!("visible size {width}x{height} is empty"); + } + + // What the level allows, or what the stream says it needs if that is more, + // so a stream that understates its level still fits. + let highest = usize::from(sps.max_sub_layers_minus1); + let buffering = usize::from(sps.max_dec_pic_buffering_minus1[highest]) + 1; + let max_dpb_frames = sps.max_dpb_size().max(buffering).min(MAX_DPB_SIZE); + + Ok(Format { + codec: Codec::H265, + // Main 10 and Main Still Picture streams that reach here hold 8-bit + // samples, which the Main profile decodes. + profile: VAProfile::VAProfileHEVCMain, + coded, + visible: (width, height), + max_dpb_frames, + }) +} + +/// Adds a slice's parameters and data to `picture`. +fn add_slice( + picture: &mut Picture, + context: &Rc, + param: SliceParameterBufferHEVC, + data: Vec, +) -> anyhow::Result<()> { + picture.add_buffer(create_buffer( + context, + BufferType::SliceParameter(SliceParameter::HEVC(param)), + )?); + picture.add_buffer(create_buffer(context, BufferType::SliceData(data))?); + Ok(()) +} + +/// Describes a DPB picture to the driver, flagged with the part of the current +/// reference picture set it is in. +fn va_picture(entry: &DpbEntry, rps: &RefPicSet) -> PictureHEVC { + let pic = entry.0.borrow(); + let contains = + |list: &[Option>]| list.iter().flatten().any(|other| Rc::ptr_eq(&other.0, &entry.0)); + + let mut flags = 0; + if matches!(pic.reference(), Reference::LongTerm) { + flags |= VA_PICTURE_HEVC_LONG_TERM_REFERENCE; + } + if contains(&rps.st_curr_before) { + flags |= VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE; + } else if contains(&rps.st_curr_after) { + flags |= VA_PICTURE_HEVC_RPS_ST_CURR_AFTER; + } else if contains(&rps.lt_curr) { + flags |= VA_PICTURE_HEVC_RPS_LT_CURR; + } + + PictureHEVC::new(entry.1.surface.id(), pic.pic_order_cnt_val, flags) +} + +fn build_pic_param( + pic: &PictureData, + surface_id: crate::VASurfaceID, + references: &[DpbEntry], + rps: &RefPicSet, + sps: &Sps, + pps: &Pps, +) -> BufferType { + let mut reference_frames = [PictureHEVC::new(VA_INVALID_ID, 0, VA_PICTURE_HEVC_INVALID); MAX_VA_REFERENCES]; + for (slot, entry) in reference_frames.iter_mut().zip(references) { + *slot = va_picture(entry, rps); + } + + let pic_fields = HevcPicFields::new( + u32::from(sps.chroma_format_idc), + u32::from(sps.separate_colour_plane_flag), + u32::from(sps.pcm_enabled_flag), + u32::from(sps.scaling_list_enabled_flag), + u32::from(pps.transform_skip_enabled_flag), + u32::from(sps.amp_enabled_flag), + u32::from(sps.strong_intra_smoothing_enabled_flag), + u32::from(pps.sign_data_hiding_enabled_flag), + u32::from(pps.constrained_intra_pred_flag), + u32::from(pps.cu_qp_delta_enabled_flag), + u32::from(pps.weighted_pred_flag), + u32::from(pps.weighted_bipred_flag), + u32::from(pps.transquant_bypass_enabled_flag), + u32::from(pps.tiles_enabled_flag), + u32::from(pps.entropy_coding_sync_enabled_flag), + u32::from(pps.loop_filter_across_slices_enabled_flag), + u32::from(pps.loop_filter_across_tiles_enabled_flag), + u32::from(sps.pcm_loop_filter_disabled_flag), + // NoPicReorderingFlag and NoBiPredFlag are hints, which ffmpeg and + // GStreamer leave unset too. + 0, + 0, + ); + + let rap_pic_flag = (NaluType::BlaWLp..=NaluType::CraNut).contains(&pic.nalu_type); + let slice_parsing_fields = HevcSliceParsingFields::new( + u32::from(pps.lists_modification_present_flag), + u32::from(sps.long_term_ref_pics_present_flag), + u32::from(sps.temporal_mvp_enabled_flag), + u32::from(pps.cabac_init_present_flag), + u32::from(pps.output_flag_present_flag), + u32::from(pps.dependent_slice_segments_enabled_flag), + u32::from(pps.slice_chroma_qp_offsets_present_flag), + u32::from(sps.sample_adaptive_offset_enabled_flag), + u32::from(pps.deblocking_filter_override_enabled_flag), + u32::from(pps.deblocking_filter_disabled_flag), + u32::from(pps.slice_segment_header_extension_present_flag), + u32::from(rap_pic_flag), + u32::from(pic.nalu_type.is_idr()), + u32::from(pic.nalu_type.is_irap()), + ); + + let pic_param = PictureParameterBufferHEVC::new( + va_current_picture(pic, surface_id), + 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, + // VA takes the signalled sizes only; the last of each is inferred. + std::array::from_fn(|i| pps.column_width_minus1[i] as u16), + std::array::from_fn(|i| pps.row_height_minus1[i] 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, + pic.short_term_ref_pic_set_size_bits, + ); + + BufferType::PictureParameter(PictureParameter::HEVC(pic_param)) +} + +/// Describes the picture being decoded, which is in no reference picture set +/// of its own. +fn va_current_picture(pic: &PictureData, surface_id: crate::VASurfaceID) -> PictureHEVC { + PictureHEVC::new(surface_id, pic.pic_order_cnt_val, 0) +} + +/// The scaling lists a picture is dequantized with, or `None` for the flat +/// default the driver assumes without an IQ matrix (7.3.2.2.1, 7.3.2.3.1). +fn scaling_lists<'a>(sps: &'a Sps, pps: &'a Pps) -> Option<&'a ScalingLists> { + if !sps.scaling_list_enabled_flag { + None + } else if pps.scaling_list_data_present_flag || !sps.scaling_list_data_present_flag { + // The PPS's lists, or the defaults the parser fills in when neither + // parameter set sends any. + Some(&pps.scaling_list) + } else { + Some(&sps.scaling_list) + } +} + +/// 6.5.3: the up-right diagonal scan of a `ROWS` by `ROWS` block, as raster +/// positions. +const fn up_right_diagonal() -> [usize; N] { + let mut scan = [0; N]; + let mut i = 0; + let mut x = 0i32; + let mut y = 0i32; + while i < N { + while y >= 0 { + if x < ROWS as i32 && y < ROWS as i32 { + scan[i] = (x + ROWS as i32 * y) as usize; + i += 1; + } + y -= 1; + x += 1; + } + y = x; + x = 0; + } + scan +} + +const UP_RIGHT_DIAGONAL_4X4: [usize; 16] = up_right_diagonal::<16, 4>(); +const UP_RIGHT_DIAGONAL_8X8: [usize; 64] = up_right_diagonal::<64, 8>(); + +/// Reorders a list coded in up-right diagonal scan into raster order, which is +/// how VA takes it. +fn raster(list: &[u8; N], scan: &[usize; N]) -> [u8; N] { + let mut out = [0; N]; + for (&value, &position) in list.iter().zip(scan) { + out[position] = value; + } + out +} + +fn build_iq_matrix(lists: &ScalingLists) -> BufferType { + // VA carries the 32x32 lists for luma only: matrixId 0 (intra) and 3 + // (inter) of the six the syntax indexes. + BufferType::IQMatrix(IQMatrix::HEVC(IQMatrixBufferHEVC::new( + lists.scaling_list_4x4.map(|list| raster(&list, &UP_RIGHT_DIAGONAL_4X4)), + lists.scaling_list_8x8.map(|list| raster(&list, &UP_RIGHT_DIAGONAL_8X8)), + lists + .scaling_list_16x16 + .map(|list| raster(&list, &UP_RIGHT_DIAGONAL_8X8)), + [0, 3].map(|id| raster(&lists.scaling_list_32x32[id], &UP_RIGHT_DIAGONAL_8X8)), + lists.scaling_list_dc_coef_minus8_16x16.map(|dc| (dc + 8) as u8), + [0, 3].map(|id| (lists.scaling_list_dc_coef_minus8_32x32[id] + 8) as u8), + ))) +} + +/// Maps a slice's reference list onto indices into the picture parameters' +/// reference frames, the way VA takes it. +fn va_ref_pic_list(list: &[Option>], references: &[DpbEntry]) -> [u8; MAX_VA_REFERENCES] { + let mut indices = [0xff; MAX_VA_REFERENCES]; + for (index, entry) in indices.iter_mut().zip(list) { + if let Some(entry) = entry { + if let Some(position) = references + .iter() + .position(|reference| Rc::ptr_eq(&reference.0, &entry.0)) + { + *index = position as u8; + } + } + } + indices +} + +fn build_slice_param( + slice: &Slice, + sps: &Sps, + list0: &[Option>], + list1: &[Option>], + references: &[DpbEntry], +) -> anyhow::Result { + let hdr = &slice.header; + + let long_slice_flags = HevcLongSliceFlags::new( + // Set on the last slice by `finish_picture`, once it is known to be last. + 0, + u32::from(hdr.dependent_slice_segment_flag), + hdr.type_ as u32, + u32::from(hdr.colour_plane_id), + u32::from(hdr.sao_luma_flag), + u32::from(hdr.sao_chroma_flag), + u32::from(hdr.mvd_l1_zero_flag), + u32::from(hdr.cabac_init_flag), + u32::from(hdr.temporal_mvp_enabled_flag), + u32::from(hdr.deblocking_filter_disabled_flag), + u32::from(hdr.collocated_from_l0_flag), + u32::from(hdr.loop_filter_across_slices_enabled_flag), + ); + + let collocated_ref_idx = if hdr.temporal_mvp_enabled_flag { + hdr.collocated_ref_idx + } else { + 0xff + }; + + // 7-56: VA takes the derived chroma offsets, not the deltas the slice codes. + let pwt = &hdr.pred_weight_table; + let half_range = sps.wp_offset_half_range_c as i32; + let chroma_offset = |delta_weight: i8, delta_offset: i16| { + let weight = (1 << pwt.chroma_log2_weight_denom) + i32::from(delta_weight); + let offset = half_range + i32::from(delta_offset) - ((half_range * weight) >> pwt.chroma_log2_weight_denom); + offset.clamp(-half_range, half_range - 1) as i8 + }; + let b = hdr.type_.is_b(); + let mut chroma_offset_l0 = [[0; 2]; MAX_VA_REFERENCES]; + let mut chroma_offset_l1 = [[0; 2]; MAX_VA_REFERENCES]; + for i in 0..MAX_VA_REFERENCES { + for j in 0..2 { + chroma_offset_l0[i][j] = chroma_offset(pwt.delta_chroma_weight_l0[i][j], pwt.delta_chroma_offset_l0[i][j]); + if b { + chroma_offset_l1[i][j] = + chroma_offset(pwt.delta_chroma_weight_l1[i][j], pwt.delta_chroma_offset_l1[i][j]); + } + } + } + let (delta_luma_weight_l1, luma_offset_l1, delta_chroma_weight_l1) = if b { + (pwt.delta_luma_weight_l1, pwt.luma_offset_l1, pwt.delta_chroma_weight_l1) + } else { + Default::default() + }; + + Ok(SliceParameterBufferHEVC::new( + u32::try_from(slice.nalu.size).context("slice NAL unit too large")?, + 0, + VA_SLICE_DATA_FLAG_ALL, + hdr.header_bit_size / 8, + hdr.segment_address, + [va_ref_pic_list(list0, references), va_ref_pic_list(list1, references)], + &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, + pwt.delta_luma_weight_l0, + pwt.luma_offset_l0, + pwt.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, + u16::try_from(hdr.num_entry_point_offsets).context("too many entry points for a VA slice")?, + 0, + u16::try_from(hdr.n_emulation_prevention_bytes) + .context("too many emulation prevention bytes for a VA slice")?, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An SPS this decoder takes: Main, 8-bit 4:2:0, 64x64. + fn main_sps() -> Sps { + let mut sps = Sps { + chroma_format_idc: 1, + pic_width_in_luma_samples: 64, + pic_height_in_luma_samples: 64, + ..Default::default() + }; + sps.profile_tier_level.general_profile_idc = 1; + sps + } + + #[test] + fn a_field_coded_sequence_is_rejected() { + assert!(format(&main_sps()).is_ok()); + + let mut sps = main_sps(); + sps.vui_parameters_present_flag = true; + sps.vui_parameters.field_seq_flag = true; + let err = format(&sps).expect_err("a field-coded sequence decoded as frames"); + assert!(err.to_string().contains("interlaced"), "{err}"); + } + + /// C.5.2.2: a picture is overdue once it has waited SpsMaxLatencyPictures, + /// the reorder limit plus sps_max_latency_increase_plus1 minus one, not + /// sps_max_latency_increase_plus1 alone. + #[test] + fn the_latency_limit_counts_from_the_reorder_limit() { + let mut sps = main_sps(); + sps.max_num_reorder_pics[0] = 2; + sps.max_latency_increase_plus1[0] = 1; + + let mut dpb = Dpb::<()>::default(); + dpb.set_max_num_pics(MAX_DPB_SIZE); + let store = |dpb: &mut Dpb<()>, poc| { + let mut pic = PictureData::default(); + pic.pic_output_flag = true; + pic.pic_order_cnt_val = poc; + dpb.store_picture(Rc::new(RefCell::new(pic)), ()).unwrap(); + }; + + // Two waiting, the oldest for one picture: within both limits. + store(&mut dpb, 0); + store(&mut dpb, 4); + assert!(!dpb.needs_additional_bumping(&sps)); + + // Output the others around POC 4 until it has waited two pictures, which + // is SpsMaxLatencyPictures, with still only two waiting. + dpb.bump(false); + store(&mut dpb, 2); + assert!(!dpb.needs_additional_bumping(&sps)); + dpb.bump(false); + store(&mut dpb, 6); + assert!(dpb.needs_additional_bumping(&sps)); + } + + #[test] + fn the_diagonal_scan_matches_the_specification() { + // 6.5.3, worked by hand for a 4x4 block. + assert_eq!( + UP_RIGHT_DIAGONAL_4X4, + [0, 4, 1, 8, 5, 2, 12, 9, 6, 3, 13, 10, 7, 14, 11, 15] + ); + let mut sorted = UP_RIGHT_DIAGONAL_8X8; + sorted.sort_unstable(); + assert_eq!( + sorted, + std::array::from_fn(|i| i), + "the 8x8 scan visits each position once" + ); + } +} diff --git a/rs/moq-vaapi/src/display.rs b/rs/moq-vaapi/src/display.rs new file mode 100644 index 00000000000..292e891dc4b --- /dev/null +++ b/rs/moq-vaapi/src/display.rs @@ -0,0 +1,388 @@ +// 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 std::sync::Arc; + +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 { + // Skips a missing node rather than stopping at it: numbering follows the + // order devices probed in, and a device that has been unbound leaves a gap. + while self.cur_idx < DRM_RENDER_NODE_START + DRM_NUM_NODES { + let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, self.cur_idx)); + self.cur_idx += 1; + if path.exists() { + return Some(path); + } + } + None + } +} + +/// Opens the first render node whose driver passes `probe`, returning the node with its display. +/// +/// A machine with more than one GPU numbers its render nodes in probe order, +/// so the one a caller needs is not reliably `renderD128`: on a laptop with an +/// NVIDIA and an Intel GPU, either can come first, and only one may offer the +/// entrypoint the caller wants. +/// +/// # Errors +/// +/// Fails when no node passes, naming each node tried and why it was passed over. +pub(crate) fn open_first(probe: impl Fn(&Display) -> anyhow::Result<()>) -> anyhow::Result<(PathBuf, Arc)> { + let mut refused = Vec::new(); + for node in DrmDeviceIterator::default() { + let opened = Display::open_drm_display(&node) + .map_err(anyhow::Error::from) + .and_then(|display| probe(&display).map(|()| display)); + match opened { + Ok(display) => return Ok((node, display)), + Err(err) => refused.push(format!("{}: {err:#}", node.display())), + } + } + match refused.is_empty() { + true => anyhow::bail!("no DRM render node under {DRM_NODE_DEFAULT_PREFIX}*"), + false => anyhow::bail!("no DRM render node qualifies ({})", refused.join("; ")), + } +} + +/// 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. + drm_file: File, +} + +/// Error type for `Display::open_drm_display`. +#[derive(Debug, Error)] +pub enum OpenDrmDisplayError { + #[error("libva could not be loaded: {0}")] + LibvaUnavailable(&'static str), + #[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> { + // dlopen libva up front so a libva-less host fails here (and the caller + // falls back) instead of panicking on the first va* call below. + bindings::load().map_err(OpenDrmDisplayError::LibvaUnavailable)?; + + 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::va().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::va().vaInitialize(display, &mut major, &mut minor) }) + .map(|()| { + Arc::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 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::va().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::va().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::va().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::va().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::va().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::va().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: &Arc, + rt_format: u32, + va_fourcc: Option, + width: u32, + height: u32, + usage_hint: Option, + descriptors: Vec, + ) -> Result>, VaError> { + Surface::new( + Arc::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: &Arc, + config: &Config, + coded_width: u32, + coded_height: u32, + surfaces: Option<&Vec>>, + progressive: bool, + ) -> Result, VaError> { + Context::new( + Arc::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: &Arc, + attrs: Vec, + profile: bindings::VAProfile::Type, + entrypoint: bindings::VAEntrypoint::Type, + ) -> Result { + Config::new(Arc::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::va().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::va().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::va().vaTerminate(self.handle); + // The File will close the DRM fd on drop. + } + } +} + +// Safe because because it only contains a `File` (which is Send+Sync), and a VADisplay handle +// which is also thread-safe. The Drop handler can also be safely called from any thread. +unsafe impl Send for Display {} +unsafe impl Sync for Display {} diff --git a/rs/moq-vaapi/src/dmabuf.rs b/rs/moq-vaapi/src/dmabuf.rs new file mode 100644 index 00000000000..1fbf4b00ef5 --- /dev/null +++ b/rs/moq-vaapi/src/dmabuf.rs @@ -0,0 +1,301 @@ +//! Importing a Linux DMA-BUF as a VA surface, without copying it. +//! +//! A [`DmaBuf`] describes an allocation some other API made (a PipeWire +//! producer, a camera, a V4L2 device, another VA-API context that exported +//! its surface) well enough for the driver to wrap it as a [`Surface`]. The +//! surface reads the producer's memory directly: an encoder given one encodes +//! the producer's pixels, and a post-processor given one converts them, without +//! the frame passing through the CPU. +//! +//! The format is named the DRM way, which is what every producer of a DMA-BUF +//! speaks. [`va_fourcc`] maps it to the VA-API name, which differs for packed +//! RGB (DRM names the channels in little-endian word order, VA-API in byte +//! order) and for planar 4:2:0 (`YU12` against `I420`). + +use std::io::{Seek, SeekFrom}; +use std::os::fd::{AsRawFd, OwnedFd}; +use std::sync::Arc; + +use crate::{ + Color, Display, DrmPrimeSurfaceDescriptor, ExternalBufferDescriptor, MemoryType, Surface, UsageHint, + VADRMPRIMESurfaceDescriptor, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX, VA_FOURCC_I420, VA_FOURCC_NV12, + VA_FOURCC_P010, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_FOURCC_YUY2, VA_FOURCC_YV12, VA_RT_FORMAT_RGB32, + VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, VA_RT_FORMAT_YUV422, +}; + +/// DRM fourcc codes for the formats [`va_fourcc`] maps. +/// +/// These are the `DRM_FORMAT_*` values from `drm_fourcc.h`, which the VA-API +/// headers do not carry. +pub mod drm { + const fn fourcc(code: &[u8; 4]) -> u32 { + u32::from_le_bytes(*code) + } + + /// Semi-planar 4:2:0, a luma plane and an interleaved Cb/Cr plane. + pub const NV12: u32 = fourcc(b"NV12"); + /// Semi-planar 4:2:0 with 10 bits per sample in 16-bit words. + pub const P010: u32 = fourcc(b"P010"); + /// Planar 4:2:0: luma, then Cb, then Cr. + pub const YUV420: u32 = fourcc(b"YU12"); + /// Planar 4:2:0: luma, then Cr, then Cb. + pub const YVU420: u32 = fourcc(b"YV12"); + /// Packed 4:2:2, `Y0 Cb Y1 Cr` in memory. + pub const YUYV: u32 = fourcc(b"YUYV"); + /// Packed 32-bit, `B G R X` in memory. + pub const XRGB8888: u32 = fourcc(b"XR24"); + /// Packed 32-bit, `B G R A` in memory. + pub const ARGB8888: u32 = fourcc(b"AR24"); + /// Packed 32-bit, `R G B X` in memory. + pub const XBGR8888: u32 = fourcc(b"XB24"); + /// Packed 32-bit, `R G B A` in memory. + pub const ABGR8888: u32 = fourcc(b"AB24"); + /// Packed 32-bit, `X R G B` in memory. + pub const BGRX8888: u32 = fourcc(b"BX24"); + /// Packed 32-bit, `A R G B` in memory. + pub const BGRA8888: u32 = fourcc(b"BA24"); +} + +/// Returns the `VA_FOURCC_*` naming the same layout as the DRM format `drm_format`. +/// +/// Returns `None` for a format this crate has no mapping for. +pub fn va_fourcc(drm_format: u32) -> Option { + Some(match drm_format { + drm::NV12 => VA_FOURCC_NV12, + drm::P010 => VA_FOURCC_P010, + drm::YUV420 => VA_FOURCC_I420, + drm::YVU420 => VA_FOURCC_YV12, + drm::YUYV => VA_FOURCC_YUY2, + drm::XRGB8888 => VA_FOURCC_BGRX, + drm::ARGB8888 => VA_FOURCC_BGRA, + drm::XBGR8888 => VA_FOURCC_RGBX, + drm::ABGR8888 => VA_FOURCC_RGBA, + drm::BGRX8888 => VA_FOURCC_XRGB, + drm::BGRA8888 => VA_FOURCC_ARGB, + _ => return None, + }) +} + +/// Returns the `VA_RT_FORMAT_*` a surface of the VA fourcc `fourcc` is allocated as. +/// +/// Returns `None` for a format this crate has no mapping for. Guessing the +/// render-target format wrong makes `vaCreateSurfaces` fail with an error that +/// names neither, so an unknown format is refused up front instead. +pub fn rt_format(fourcc: u32) -> Option { + match fourcc { + VA_FOURCC_NV12 | VA_FOURCC_I420 | VA_FOURCC_YV12 => Some(VA_RT_FORMAT_YUV420), + VA_FOURCC_P010 => Some(VA_RT_FORMAT_YUV420_10), + VA_FOURCC_YUY2 => Some(VA_RT_FORMAT_YUV422), + VA_FOURCC_BGRA | VA_FOURCC_BGRX | VA_FOURCC_RGBA | VA_FOURCC_RGBX | VA_FOURCC_ARGB | VA_FOURCC_XRGB => { + Some(VA_RT_FORMAT_RGB32) + } + _ => None, + } +} + +/// One plane of a DMA-BUF, within the single object holding them all. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Plane { + /// Byte offset of the plane from the start of the object. + pub offset: u32, + /// Bytes between adjacent rows of the plane. + pub pitch: u32, +} + +/// An externally allocated DMA-BUF, described well enough to import as a surface. +/// +/// One object holding every plane, which is what a VA-API decoder exports and +/// what a PipeWire producer negotiating a single modifier hands out. A buffer +/// split across several objects is not describable here. +/// +/// The descriptor owns the file descriptor and keeps it open for the life of the +/// surface built from it. libva does not take ownership (the driver resolves the +/// buffer during `vaCreateSurfaces` and leaves the fd alone), so holding it +/// costs one descriptor and removes the question of whether closing it early is +/// safe. +#[derive(Debug)] +pub struct DmaBuf { + /// Pixel format, a `DRM_FORMAT_*` code; see [`drm`]. + pub drm_format: u32, + /// Format modifier describing the tiling of the object. + pub modifier: u64, + /// Width of the picture in pixels. + /// + /// The visible width, not the allocated one: the padding lives in each + /// plane's pitch and offset. + pub width: u32, + /// Height of the picture in pixels, likewise the visible height. + pub height: u32, + /// Plane offsets and pitches, in format order. One to four. + pub planes: Vec, + /// The exported descriptor, held open until the surface is destroyed. + pub fd: OwnedFd, + /// The YUV color space of the pixels, where the producer knows it. + /// + /// Ignored for packed RGB. The encoder converts a YUV buffer whose space + /// differs from the stream's, and takes one with `None` to be in the + /// stream's space already. + pub color: Option, +} + +impl DmaBuf { + /// Describes a surface exported by [`Surface::export_prime`] for import elsewhere. + /// + /// The color is left unknown; set [`color`](Self::color) when the + /// producer knows it. + /// + /// # Errors + /// + /// Fails unless the export is one object holding one composed layer, which + /// is what `export_prime` asks the driver for. + pub fn from_prime(mut exported: DrmPrimeSurfaceDescriptor) -> anyhow::Result { + if exported.objects.len() != 1 || exported.layers.len() != 1 { + anyhow::bail!( + "expected one object and one layer, the export has {} and {}", + exported.objects.len(), + exported.layers.len() + ); + } + let object = exported.objects.remove(0); + let layer = &exported.layers[0]; + Ok(Self { + drm_format: layer.drm_format, + modifier: object.drm_format_modifier, + width: exported.width, + height: exported.height, + planes: (0..(layer.num_planes as usize).min(4)) + .map(|i| Plane { + offset: layer.offset[i], + pitch: layer.pitch[i], + }) + .collect(), + fd: object.fd, + color: None, + }) + } + + /// Returns the `VA_FOURCC_*` of this buffer's format, if it has one. + pub fn fourcc(&self) -> Option { + va_fourcc(self.drm_format) + } + + /// Imports this buffer as a surface on `display`, without copying it. + /// + /// The returned surface owns the buffer, so the descriptor stays open + /// exactly as long as the surface referring to it. `usage_hint` tells the + /// driver what the surface is for; some drivers only accept an import as an + /// encoder source when it says so. + /// + /// # Errors + /// + /// Fails when the format has no VA-API mapping, when the plane count is not + /// one to four, and when the driver refuses the import, which it does for a + /// modifier or pitch it cannot address. + pub fn import(self, display: &Arc, usage_hint: Option) -> anyhow::Result> { + let fourcc = self + .fourcc() + .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", self.drm_format))?; + let rt_format = + rt_format(fourcc).ok_or_else(|| anyhow::anyhow!("no VA-API render target format for {fourcc:#010x}"))?; + if self.planes.is_empty() || self.planes.len() > 4 { + anyhow::bail!("a DMA-BUF import takes one to four planes, got {}", self.planes.len()); + } + let (width, height) = (self.width, self.height); + + display + .create_surfaces(rt_format, Some(fourcc), width, height, usage_hint, vec![self]) + .map_err(|e| anyhow::anyhow!("import a {width}x{height} DMA-BUF as a surface: {e:?}"))? + .pop() + .ok_or_else(|| anyhow::anyhow!("vaCreateSurfaces returned no surface")) + } +} + +impl ExternalBufferDescriptor for DmaBuf { + const MEMORY_TYPE: MemoryType = MemoryType::DrmPrime2; + type DescriptorAttribute = VADRMPRIMESurfaceDescriptor; + + fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute { + // `import` has checked the format and the plane count; an unmapped format + // reaching here anyway goes out as zero, which the driver refuses. + let mut descriptor = VADRMPRIMESurfaceDescriptor { + fourcc: self.fourcc().unwrap_or(0), + width: self.width, + height: self.height, + num_objects: 1, + num_layers: 1, + ..Default::default() + }; + + descriptor.objects[0].fd = self.fd.as_raw_fd(); + descriptor.objects[0].size = buffer_size(&self.fd); + descriptor.objects[0].drm_format_modifier = self.modifier; + + let layer = &mut descriptor.layers[0]; + layer.drm_format = self.drm_format; + layer.num_planes = self.planes.len().min(4) as u32; + for (index, plane) in self.planes.iter().take(4).enumerate() { + layer.object_index[index] = 0; + layer.offset[index] = plane.offset; + layer.pitch[index] = plane.pitch; + } + + descriptor + } +} + +/// Returns the size of the DMA-BUF behind `fd`, or zero when the kernel will not say. +/// +/// A DMA-BUF reports its size through `lseek(SEEK_END)`. Intel's iHD driver +/// refuses to import packed RGB with a size of zero, where for YUV formats it +/// works the size out from the layout; zero stays the fallback because it is +/// what the other drivers expect when the size is unknown. The seek moves the +/// file offset shared with the producer's descriptor. The kernel accepts only +/// the start and the end as a DMA-BUF offset (not even `SEEK_CUR`), so the +/// offset was at the start before, and seeking back there restores it. +fn buffer_size(fd: &OwnedFd) -> u32 { + let Ok(clone) = fd.try_clone() else { + return 0; + }; + let mut file = std::fs::File::from(clone); + let size = file + .seek(SeekFrom::End(0)) + .ok() + .and_then(|size| u32::try_from(size).ok()); + let _ = file.seek(SeekFrom::Start(0)); + size.unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_mapped_format_has_a_render_target() { + for format in [ + drm::NV12, + drm::P010, + drm::YUV420, + drm::YVU420, + drm::YUYV, + drm::XRGB8888, + drm::ARGB8888, + drm::XBGR8888, + drm::ABGR8888, + drm::BGRX8888, + drm::BGRA8888, + ] { + let fourcc = va_fourcc(format).expect("mapped"); + assert!(rt_format(fourcc).is_some(), "{format:#010x} has no render target"); + } + } + + #[test] + fn packed_rgb_maps_to_the_byte_order_name() { + // DRM XRGB8888 is a little-endian word, so memory holds B G R X, which + // VA-API calls BGRX. + assert_eq!(va_fourcc(drm::XRGB8888), Some(VA_FOURCC_BGRX)); + assert_eq!(va_fourcc(drm::ABGR8888), Some(VA_FOURCC_RGBA)); + assert_eq!(va_fourcc(drm::YUV420), Some(VA_FOURCC_I420)); + assert_eq!(va_fourcc(u32::from_le_bytes(*b"ZZZZ")), None); + } +} diff --git a/rs/moq-vaapi/src/encode.rs b/rs/moq-vaapi/src/encode.rs new file mode 100644 index 00000000000..450f4a58345 --- /dev/null +++ b/rs/moq-vaapi/src/encode.rs @@ -0,0 +1,1733 @@ +// 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. +// +// Adapted from discord/cros-codecs (encoder/stateless/h264/vaapi.rs), itself +// BSD-3-Clause / Copyright The ChromiumOS Authors. See LICENSE.cros-codecs. + +//! Thin VA-API H.264 and H.265 encoder built on the vendored libva binding. +//! +//! For H.264 it reuses the backend-agnostic bitstream layer +//! ([`crate::codec::h264`]) from discord/cros-codecs (BSD-3-Clause) for +//! SPS/PPS/slice synthesis, and drives libva directly for surface upload + +//! slice submission, rather than vendoring cros-codecs's generic multi-backend +//! encoder framework. The per-frame VA buffer population is ported from +//! cros-codecs's `encoder/stateless/h264/vaapi.rs`. H.265 writes its own +//! parameter sets and slice headers (see `h265.rs`). +//! +//! Low-latency only: IPPP (no B-frames), one reference frame, matching the +//! VideoToolbox / Media Foundation / NVENC backends in moq-video. +//! +//! Three ways in, cheapest first: +//! - [`Encoder::encode_dmabuf`] with an NV12 DMA-BUF at the encoder's size +//! encodes the producer's memory in place. +//! - [`Encoder::encode_dmabuf`] with any other importable DMA-BUF (packed RGB +//! from a screen capture, YUYV from a camera, NV12 at another size) converts +//! and scales it into the encoder's own surface with the video processor, on +//! the GPU. +//! - [`Encoder::encode_nv12`] uploads CPU pixels. +//! +//! Checked on Intel Meteor Lake and Arrow Lake with the iHD driver, and on an +//! AMD RX 9070 with radeonsi, by decoding with ffmpeg's software decoder: CPU +//! and DMA-BUF input come back above 35 dB luma PSNR, and BGRX converts to +//! BT.601 and BT.709 with every channel within 6 code values of the reference. +//! The low-power entrypoint is untested, since those devices expose the full +//! one. + +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; + +use crate::codec::h264::parser::SpsBuilder; +use crate::codec::h264::parser::{Level, Pps, PpsBuilder, Profile, SliceHeader, SliceHeaderBuilder, SliceType, Sps}; +use crate::codec::h264::synthesizer::Synthesizer; +use crate::codec::Codec; +use crate::dmabuf::DmaBuf; +use crate::vpp::Processor; +use crate::{ + BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter, + EncMiscParameterFrameRate, EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType, + EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter, EncSequenceParameterBufferH264, + EncSliceParameter, EncSliceParameterBufferH264, H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, + H264VuiFields, Image, MappedCodedBuffer, Picture, PictureH264, RcFlags, Surface, SurfaceMemoryDescriptor, + UsageHint, VAConfigAttrib, VAConfigAttribType, VAEntrypoint, VAProfile, VA_ATTRIB_NOT_SUPPORTED, + VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, + VA_FOURCC_BGRA, VA_FOURCC_BGRX, VA_FOURCC_NV12, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, + VA_PICTURE_H264_INVALID, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RC_CBR, VA_RT_FORMAT_YUV420, +}; + +mod h265; + +/// Whether a frame is used as a reference, and for how long. +/// (Vendored from discord/cros-codecs, BSD-3-Clause; used by the slice synthesizer.) +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum IsReference { + No, + ShortTerm, + LongTerm, +} + +/// Quantizer bounds for the rate controller. +/// +/// The floor keeps an IDR on easy content from taking a large share of the +/// rate. The ceiling is the codecs' own: iHD and radeonsi both honor it, so a +/// lower one sets a smallest picture, and a stream asked for less overshoots +/// its rate several times over. A lower ceiling does steady iHD's H.264 IDRs, +/// but under congestion missing the rate costs more than that. +const MIN_QP: u8 = 18; +const MAX_QP: u8 = 51; +/// Window over which libva's rate controller targets the configured bitrate. +/// +/// This matches cros-codecs. The old `framerate * 1000` value confused frames +/// per second with seconds and gave a 30 fps encoder a 30-second window. +pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500; +/// `max_frame_num` upper bound for the low-delay GOP; matches cros-codecs. +const LIMIT: u32 = 2048; + +/// Encoder configuration. Dimensions must be even (4:2:0 chroma). +#[derive(Clone, Debug)] +pub struct Config { + /// The format to encode, H.264 unless set. Main profile either way. + pub codec: Codec, + pub width: u32, + pub height: u32, + pub framerate: u32, + /// Target bitrate in bits per second (CBR). + pub bitrate: u32, + /// Keyframe interval in frames. + pub gop: u32, + /// DRM render node to open (e.g. `/dev/dri/renderD128`). + /// + /// `None`, the default, opens the first node whose driver can encode + /// [`codec`](Self::codec), and [`Encoder::config`] then names the node it + /// picked. + pub device: Option, + /// Color space written into the SPS, and the target of a conversion from RGB. + /// + /// Defaults to [`Color::infer`] for the height, which is what a decoder + /// assumes for an unlabelled stream. + pub color: Color, +} + +impl Config { + /// Returns an H.264 configuration; set [`codec`](Self::codec) for another format. + pub fn new(width: u32, height: u32, framerate: u32, bitrate: u32, gop: u32) -> Self { + Self { + codec: Codec::H264, + width, + height, + framerate, + bitrate, + gop, + device: None, + color: Color::infer(height), + } + } +} + +/// Per-frame reference metadata. (Mirrors cros-codecs `DpbEntryMeta`.) +#[derive(Copy, Clone)] +struct FrameMeta { + poc: u32, + frame_num: u32, +} + +impl FrameMeta { + /// Returns the H.264 order count and frame number of the picture `count` pictures after an IDR. + /// + /// frame_num counts modulo MaxFrameNum, and the slice header carries only + /// the low bits of the picture order count; the full count goes to the + /// driver in the picture parameters. + fn new(count: u32) -> Self { + Self { + poc: count.wrapping_mul(2), + frame_num: count % LIMIT, + } + } +} + +/// The picture a P picture predicts from: the previous one. +#[derive(Copy, Clone)] +struct Reference { + /// Its reconstructed surface. + surface: crate::bindings::VASurfaceID, + /// How many pictures after the IDR it came. + count: u32, +} + +/// What one picture's parameter buffers are built from. +struct PictureInfo<'a> { + idr: bool, + /// How many IDR pictures came before this one. + idr_id: u32, + /// How many pictures after the IDR this one comes. + count: u32, + /// The surface its reconstruction is written to. + recon: crate::bindings::VASurfaceID, + reference: Option, + coded: &'a EncCodedBuffer, + bitrate: u32, +} + +/// The bitstream syntax of the stream being encoded. +enum Syntax { + H264 { + sps: Rc, + pps: Rc, + /// The packed header kinds the driver takes from us; it writes the rest. + packed: u32, + }, + H265 { + stream: h265::Stream, + /// The packed header kinds the driver takes from us; it writes the rest. + packed: u32, + }, +} + +/// A VA-API H.264 or H.265 encoder. Built once, fed NV12 frames, emits an Annex-B stream. +pub struct Encoder { + config: Config, + syntax: Syntax, + + // Source surface (reused; NV12 re-uploaded per frame) and a 2-deep + // reconstructed surface ring (current + previous reference for IPPP). + input: Option>, + recon: Vec>, + /// Reference from the previous encoded frame: (recon index, pictures after the IDR). + reference: Option<(usize, u32)>, + + counter: u32, + /// IDR pictures coded so far, so two in a row carry different H.264 `idr_pic_id`s. + idrs: u32, + + /// The video processor converting and scaling DMA-BUF input, opened on the + /// first frame that needs it. + processor: Option, + /// Set by a bitrate change, and cleared by the next frame, which asks the + /// driver to restart its rate controller at the new target. + reset_rate_control: bool, + + // Drop order: encode resources before the display they belong to. + coded: EncCodedBuffer, + coded_size: usize, + context: Rc, + _va_config: VaConfig, + display: Arc, +} + +impl Encoder { + /// Opens [`Config::device`], or the first render node that encodes [`Config::codec`], and sets up an encode session for `config`. + /// + /// # Errors + /// + /// Fails when libva cannot be loaded, when the named node cannot be opened + /// or does not encode the codec (a named node is never swapped for + /// another), when no node encodes it, and when the driver refuses the + /// session or, for H.265, requires a coding tool this encoder does not write + /// or takes no packed sequence header. + pub fn new(mut config: Config) -> anyhow::Result { + let codec = config.codec; + let (device, display) = match config.device.take() { + Some(device) => { + let display = Display::open_drm_display(&device) + .map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?; + (device, display) + } + None => crate::display::open_first(|display| probe(display, codec)) + .map_err(|e| e.context(format!("find a render node that encodes {codec:?}")))?, + }; + + let entrypoint = encode_entrypoint(&display, codec)?; + let mut attrs = vec![ + VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribRTFormat, + value: VA_RT_FORMAT_YUV420, + }, + VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribRateControl, + value: VA_RC_CBR, + }, + ]; + // The parameter sets go out as packed headers, so the VUI (color, frame + // buffering) and the level are ours. For H.264 that is the SPS and PPS; + // iHD takes them without being told, and a driver that follows the spec + // writes its own unless the config asks. For H.265 it is the VPS, SPS and + // PPS as one sequence header. Each slice header is packed too, as ffmpeg + // packs them; the driver writes the slice headers if it does not take + // them. radeonsi needs them for H.264: it takes the slice's NAL header + // from the packed one, and drops the packed parameter sets without one. + let wanted = match codec { + Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE, + Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE, + }; + let packed = packed_headers(&display, codec, entrypoint) & wanted; + // VA's H.265 sequence parameters have no conformance window and carry no + // VUI here, so an SPS the driver writes would lose the crop and the color. + if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 { + anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need"); + } + if packed != 0 { + attrs.push(VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders, + value: packed, + }); + } else { + tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own"); + } + let mut va_config = display + .create_config(attrs, profile(codec), entrypoint) + .map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?; + + let syntax = match codec { + Codec::H264 => { + let (sps, pps) = build_sps_pps(&config); + Syntax::H264 { sps, pps, packed } + } + Codec::H265 => Syntax::H265 { + stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?, + packed, + }, + }; + // H.264 sizes the context and its references to the frame, which has + // always worked; H.265 to whole minimum coding blocks, as ffmpeg does, + // and to the driver's surface alignment. + let size = match &syntax { + Syntax::H264 { .. } => (config.width, config.height), + Syntax::H265 { stream, .. } => stream.coded(), + }; + + let context = display + .create_context::<()>(&va_config, size.0, size.1, None, true) + .map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?; + + let coded_size = coded_size(config.bitrate); + let coded = context + .create_enc_coded(coded_size) + .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?; + + let input = make_surface(&display, (config.width, config.height))?; + let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?]; + + tracing::info!( + "opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, low power: {}", + device, + config.width, + config.height, + config.framerate, + config.bitrate, + entrypoint == VAEntrypoint::VAEntrypointEncSliceLP, + ); + config.device = Some(device); + Ok(Self { + config, + syntax, + input: Some(input), + recon, + reference: None, + counter: 0, + idrs: 0, + processor: None, + reset_rate_control: false, + coded, + coded_size, + context, + _va_config: va_config, + display, + }) + } + + /// Encodes one tightly-packed NV12 frame, returning Annex-B (with the + /// parameter sets inline on each IDR). `keyframe` forces an IDR. + /// + /// # Errors + /// + /// Fails when `nv12` is shorter than a frame at the encoder's size, and when + /// the upload or the encode fails. + pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result> { + let (width, height) = (self.config.width as usize, self.config.height as usize); + let expected = width * height + width * height.div_ceil(2); + if nv12.len() < expected { + anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", nv12.len()); + } + let input = self.input.take().expect("input surface present"); + let result = upload_nv12(&self.display, &input, self.config.width, self.config.height, nv12) + .and_then(|()| self.encode_surface(&input, keyframe)); + self.input = Some(input); + result + } + + /// Encodes one frame held in a DMA-BUF, returning Annex-B like + /// [`encode_nv12`](Self::encode_nv12). + /// + /// An NV12 buffer at the encoder's size, which the encoder reads without + /// padding (whole macroblocks for H.264; for H.265, whole minimum coding + /// blocks at the driver's surface alignment), and whose + /// [`color`](DmaBuf::color) is the stream's or unknown, is imported and + /// encoded in place. Any other mapped format or size goes through the video processor into the encoder's own surface + /// first: scaled to the encoder's size and converted to [`Config::color`]. + /// A YUV buffer with no color of its own is taken to be in that space + /// already. Nothing reaches the CPU on either path. + /// + /// The macroblock condition is not a formality: the encoder reads whole + /// macroblocks, so it reads 1088 rows of a 1080-row picture, and a producer + /// that places the chroma plane right after the last visible luma row + /// (PipeWire does) has nothing there to read. + /// + /// The producer must have finished writing the buffer; this does not wait + /// on its fence. + /// + /// # Errors + /// + /// Fails when the driver refuses to import the buffer (an unsupported + /// modifier or layout), when the device has no video processor and the + /// buffer needs one, and when the encode itself fails. The encoder stays + /// usable after a refused import, so a caller can fall back to + /// [`encode_nv12`](Self::encode_nv12) for the same frame. + pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result> { + let fourcc = buffer + .fourcc() + .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?; + let color = self.config.color; + let size = (self.config.width, self.config.height); + let unpadded = match &self.syntax { + Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0, + Syntax::H265 { stream, .. } => stream.coded() == size, + }; + let in_place = fourcc == VA_FOURCC_NV12 + && (buffer.width, buffer.height) == size + && unpadded + && buffer.color.is_none_or(|own| own == color); + if in_place { + let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?; + return self.encode_surface(&source, keyframe); + } + + let input_color = match is_rgb(fourcc) { + true => None, + false => Some(buffer.color.unwrap_or(color)), + }; + let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?; + let input = self.input.take().expect("input surface present"); + let result = self + .processor() + .and_then(|processor| processor.blit(&source, &input, input_color, Some(color))) + .and_then(|()| self.encode_surface(&input, keyframe)); + self.input = Some(input); + result + } + + /// Changes the target bitrate, in bits per second, from the next frame on. + /// + /// The rate control parameters go out with every frame, so this neither + /// forces an IDR nor rebuilds the session; the next frame also asks the + /// driver to reset its rate controller. It then converges over its window, + /// [`RATE_CONTROL_WINDOW_MS`]. + /// + /// The level in the SPS is not revisited, so a rate far above the one the + /// stream opened with can exceed what that level allows. + /// + /// # Errors + /// + /// Fails for a bitrate of zero, and when a larger coded buffer for the new + /// rate cannot be allocated, in which case the old rate stays. + pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> { + if bitrate == 0 { + anyhow::bail!("a bitrate of zero"); + } + let size = coded_size(bitrate); + if size > self.coded_size { + // A higher rate can produce a picture larger than the buffer sized for + // the old one, and a truncated picture is corrupt rather than short. + self.coded = self + .context + .create_enc_coded(size) + .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?; + self.coded_size = size; + } + if bitrate != self.config.bitrate { + self.reset_rate_control = true; + } + self.config.bitrate = bitrate; + Ok(()) + } + + /// Returns the configuration in effect, including a bitrate changed since opening and the render node picked when none was named. + pub fn config(&self) -> &Config { + &self.config + } + + /// Returns the video processor, opening it on first use. + fn processor(&mut self) -> anyhow::Result<&Processor> { + if self.processor.is_none() { + self.processor = Some(Processor::with_display(Arc::clone(&self.display))?); + } + Ok(self.processor.as_ref().expect("opened above")) + } + + /// Encodes the picture in `source`, which must be NV12 at the encoder's size. + fn encode_surface( + &mut self, + source: &Surface, + keyframe: bool, + ) -> anyhow::Result> { + let is_idr = keyframe || self.counter % self.config.gop == 0; + if is_idr { + // An IDR restarts the picture count and drops the reference. + self.counter = 0; + self.reference = None; + } + + let recon_idx = (self.counter as usize) % self.recon.len(); + // The reference is the previous picture's reconstruction, for a P picture. + let reference = match (is_idr, self.reference) { + (false, Some((index, count))) => Some(Reference { + surface: self.recon[index].id(), + count, + }), + _ => None, + }; + let info = PictureInfo { + idr: is_idr, + idr_id: self.idrs, + count: self.counter, + recon: self.recon[recon_idx].id(), + reference, + coded: &self.coded, + bitrate: self.config.bitrate, + }; + let buffers = match &self.syntax { + Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?, + Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed), + }; + + let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source); + + // VA-API spec buffer order: sequence, picture, slice, then packed headers, + // then rate-control misc params. + for buffer in buffers { + picture.add_buffer(self.create(buffer)?); + } + + let bits_per_second = self.config.bitrate; + let rc = EncMiscParameterRateControl::new( + bits_per_second, + 100, // target_percentage (CBR) + RATE_CONTROL_WINDOW_MS, // window_size (ms) + u32::from((MIN_QP + MAX_QP) / 2), + MIN_QP as u32, + 0, // basic_unit_size + // Do not let rate control drop a frame to meet the bitrate. A live + // encoder has already admitted this frame into the media timeline. + RcFlags::new(u32::from(self.reset_rate_control), 1, 0, 0, 0, 0, 0, 0, 0), + 0, // icq_quality_factor + MAX_QP as u32, + 0, // quality_factor + 0, // target_frame_size + ); + picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?); + + let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0); + picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?); + + let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?; + let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?; + let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?; + // Sync (PictureEnd -> PictureSync) so the source is no longer read and + // the coded buffer is ready. + picture + .sync() + .map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?; + + // The reconstructed surface syncs implicitly; read the coded bitstream. + let bitstream = self.read_coded()?; + + self.reference = Some((recon_idx, self.counter)); + self.counter += 1; + self.idrs = self.idrs.wrapping_add(u32::from(is_idr)); + self.reset_rate_control = false; + Ok(bitstream) + } + + fn create(&self, buffer: BufferType) -> anyhow::Result { + self.context + .create_buffer(buffer) + .map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}")) + } + + fn read_coded(&self) -> anyhow::Result> { + let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?; + let mut out = Vec::new(); + for segment in mapped.iter() { + out.extend_from_slice(segment.buf); + } + Ok(out) + } +} + +/// Checks that `display`'s driver can encode `codec`, which is what [`Encoder::new`] needs of a render node. +/// +/// # Errors +/// +/// Fails when the driver offers neither the full nor the low-power Main +/// profile encode entrypoint for `codec`, or cannot be asked. +pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> { + encode_entrypoint(display, codec).map(drop) +} + +/// Returns the VA profile `codec` is encoded in. +fn profile(codec: Codec) -> VAProfile::Type { + match codec { + Codec::H264 => VAProfile::VAProfileH264Main, + Codec::H265 => h265::PROFILE, + } +} + +/// Returns the entrypoint to encode `codec` with: the full one, or the low-power one where it is all there is. +/// +/// Some Intel parts expose encode only through `VAEntrypointEncSliceLP`. +fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result { + let entrypoints = display + .query_config_entrypoints(profile(codec)) + .map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?; + pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint")) +} + +/// Returns the encode entrypoint to use out of those a device offers: the full one when present. +fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option { + [VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP] + .into_iter() + .find(|entrypoint| offered.contains(entrypoint)) +} + +/// Returns the packed header kinds the driver takes for `codec` at `entrypoint`. +/// +/// Zero when it takes none, or when asking fails. +fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 { + let mut attrs = [VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders, + value: 0, + }]; + if display + .get_config_attributes(profile(codec), entrypoint, &mut attrs) + .is_err() + || attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0 + { + return 0; + } + attrs[0].value +} + +/// Returns the lowest H.264 level, from 4 up, whose frame size and macroblock rate cover the stream. +/// +/// Only those two limits: the level's maximum bitrate is not checked. +/// +/// Level 4 is the floor because it was the fixed level before, and decoders +/// take the DPB size from `max_dec_frame_buffering` rather than from the level, +/// so a lower one would buy nothing. Above 1080p (a 1440p or 4K screen share) a +/// fixed level 4 would declare a stream its decoder may refuse. +fn level(width: u32, height: u32, framerate: u32) -> Level { + // H.264 Table A-1: (level, MaxMBPS, MaxFS). + const LEVELS: [(Level, u64, u64); 8] = [ + (Level::L4, 245_760, 8_192), + (Level::L4_2, 522_240, 8_704), + (Level::L5, 589_824, 22_080), + (Level::L5_1, 983_040, 36_864), + (Level::L5_2, 2_073_600, 36_864), + (Level::L6, 4_177_920, 139_264), + (Level::L6_1, 8_355_840, 139_264), + (Level::L6_2, 16_711_680, 139_264), + ]; + let frame = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16)); + let rate = frame * u64::from(framerate.max(1)); + LEVELS + .into_iter() + .find(|&(_, max_rate, max_frame)| frame <= max_frame && rate <= max_rate) + .map(|(level, _, _)| level) + .unwrap_or(Level::L6_2) +} + +/// Returns the coded buffer size in bytes for `bitrate`: two seconds of it, and at least 1.5 MB. +fn coded_size(bitrate: u32) -> usize { + (bitrate as usize / 4).max(1_500_000) +} + +/// Returns whether the VA fourcc `fourcc` is packed RGB, which has no YUV matrix of its own. +fn is_rgb(fourcc: u32) -> bool { + matches!( + fourcc, + VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB + ) +} + +/// Allocate one NV12 encode surface. +fn make_surface(display: &Arc, (width, height): (u32, u32)) -> anyhow::Result> { + let mut surfaces = display + .create_surfaces::<()>( + VA_RT_FORMAT_YUV420, + Some(VA_FOURCC_NV12), + width, + height, + Some(UsageHint::USAGE_HINT_ENCODER), + vec![()], + ) + .map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?; + surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created")) +} + +/// Upload tightly-packed NV12 into a surface. Ported from cros-codecs +/// `upload_nv12_img` (honors the image's per-plane offsets + pitches). +fn upload_nv12( + display: &Arc, + surface: &Surface<()>, + width: u32, + height: u32, + data: &[u8], +) -> anyhow::Result<()> { + let formats = display + .query_image_formats() + .map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?; + let format = formats + .into_iter() + .find(|f| f.fourcc == VA_FOURCC_NV12) + .ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?; + + let mut image = Image::create_from(surface, format, surface.size(), surface.size()) + .map_err(|e| anyhow::anyhow!("create image: {e:?}"))?; + let va_image = *image.image(); + let dest: &mut [u8] = image.as_mut(); + let (w, h) = (width as usize, height as usize); + + // Luma plane. + let mut src = data; + let mut dst = &mut dest[va_image.offsets[0] as usize..]; + for _ in 0..h { + dst[..w].copy_from_slice(&src[..w]); + dst = &mut dst[va_image.pitches[0] as usize..]; + src = &src[w..]; + } + // Interleaved chroma plane (h/2 rows of w bytes). + let mut src = &data[w * h..]; + let mut dst = &mut dest[va_image.offsets[1] as usize..]; + for _ in 0..h / 2 { + dst[..w].copy_from_slice(&src[..w]); + dst = &mut dst[va_image.pitches[1] as usize..]; + src = &src[w..]; + } + + drop(image); + surface.sync().map_err(|e| anyhow::anyhow!("surface sync: {e:?}"))?; + Ok(()) +} + +/// Build the SPS/PPS for a low-latency IPPP stream. Ported from +/// discord/cros-codecs `LowDelayH264Delegate::new_sequence` (BSD-3-Clause). +fn build_sps_pps(config: &Config) -> (Rc, Rc) { + let level = level(config.width, config.height, config.framerate); + let (primaries, transfer, matrix) = config.color.vui(); + let sps = SpsBuilder::new() + .seq_parameter_set_id(0) + .profile_idc(Profile::Main) + .chroma_format_idc(1) + .level_idc(level) + .max_frame_num(LIMIT) + .pic_order_cnt_type(0) + .max_pic_order_cnt_lsb(LIMIT * 2) + .max_num_ref_frames(1) + .frame_mbs_only_flag(true) + .direct_8x8_inference_flag(level >= Level::L3) + .resolution(config.width, config.height) + .bit_depth_luma(8) + .bit_depth_chroma(8) + .aspect_ratio(1, 1) + .timing_info(1, config.framerate * 2, false) + .video_signal_type(config.color.full_range, primaries, transfer, matrix) + .max_num_reorder_frames(0) + .max_dec_frame_buffering(1) + .build(); + + let pps = PpsBuilder::new(Rc::clone(&sps)) + .pic_parameter_set_id(0) + .pic_init_qp(26) + .entropy_coding_mode_flag(true) + .transform_8x8_mode_flag(false) + .deblocking_filter_control_present_flag(true) + .num_ref_idx_l0_default_active(1) + .num_ref_idx_l1_default_active_minus1(0) + .build(); + + (sps, pps) +} + +/// Returns the parameter buffers of one H.264 picture, then the packed headers the driver takes: the SPS and PPS on an IDR, and the slice header. +fn h264_buffers(sps: &Sps, pps: &Rc, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result> { + let meta = FrameMeta::new(picture.count); + let slice_type = if picture.idr { SliceType::I } else { SliceType::P }; + let header = SliceHeaderBuilder::new(pps) + .slice_type(slice_type) + .first_mb_in_slice(0) + .frame_num(meta.frame_num as u16) + .pic_order_cnt_lsb((meta.poc % (LIMIT * 2)) as u16) + // Only consecutive IDRs must differ. + .idr_pic_id((picture.idr_id % 2) as u16) + .build(); + let macroblocks = (sps.pic_width_in_mbs_minus1 as u32 + 1) * (sps.pic_height_in_map_units_minus1 as u32 + 1); + let reference = picture + .reference + .map(|reference| (reference.surface, FrameMeta::new(reference.count))); + + let mut buffers = vec![ + build_enc_seq_param(sps, picture.bitrate, LIMIT, 0), + build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference), + build_enc_slice_param(pps, &header, reference, macroblocks), + ]; + if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 { + buffers.extend(packed_parameter_sets(sps, pps)?); + } + if packed & VA_ENC_PACKED_HEADER_SLICE != 0 { + let mut nal = Vec::new(); + let trailing = Synthesizer::<'_, SliceHeader, _>::synthesize( + &header, + sps, + pps, + picture.idr, + IsReference::ShortTerm, + &mut nal, + true, + ) + .map_err(|e| anyhow::anyhow!("synthesize slice header: {e:?}"))?; + // The slice data follows the header's last bit, not its padded last byte. + let bits = nal.len() * 8 - usize::from(trailing); + buffers.extend(packed_header(EncPackedHeaderType::Slice, &nal, bits)); + } + Ok(buffers) +} + +/// Returns the SPS and PPS as packed headers, which go out with every IDR. +fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> { + let mut sps_nal = Vec::new(); + Synthesizer::<'_, Sps, _>::synthesize(3, sps, &mut sps_nal, true) + .map_err(|e| anyhow::anyhow!("synthesize SPS: {e:?}"))?; + let mut pps_nal = Vec::new(); + Synthesizer::<'_, Pps, _>::synthesize(3, pps, &mut pps_nal, true) + .map_err(|e| anyhow::anyhow!("synthesize PPS: {e:?}"))?; + + let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8); + let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8); + Ok([sps_param, sps_data, pps_param, pps_data]) +} + +fn build_invalid_pic() -> PictureH264 { + PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0) +} + +fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 { + PictureH264::new( + surface_id, + meta.frame_num, + VA_PICTURE_H264_SHORT_TERM_REFERENCE, + meta.poc as i32, + meta.poc as i32, + ) +} + +/// Ported from cros-codecs `build_enc_seq_param` (BSD-3-Clause). +fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType { + 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_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, + ))) +} + +/// Ported from cros-codecs `build_enc_pic_param` (BSD-3-Clause). +fn build_enc_pic_param( + pps: &Pps, + coded: &EncCodedBuffer, + recon_id: u32, + meta: FrameMeta, + is_idr: bool, + reference: Option<(u32, FrameMeta)>, +) -> BufferType { + let pic_fields = H264EncPicFields::new( + is_idr as u32, + 1, // reference_pic_flag: this frame is a short-term reference + pps.entropy_coding_mode_flag as u32, + pps.weighted_pred_flag as u32, + pps.weighted_bipred_idc as u32, + pps.constrained_intra_pred_flag as u32, + pps.transform_8x8_mode_flag as u32, + pps.deblocking_filter_control_present_flag as u32, + pps.redundant_pic_cnt_present_flag as u32, + 0, + pps.pic_scaling_matrix_present_flag as u32, + ); + + let curr_pic = build_h264_pic(recon_id, meta); + let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic()); + if let Some((id, m)) = reference { + reference_frames[0] = build_h264_pic(id, m); + } + + BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new( + curr_pic, + reference_frames, + coded.id(), + pps.pic_parameter_set_id, + pps.seq_parameter_set_id, + 0, + meta.frame_num as u16, + (pps.pic_init_qp_minus26 + 26) as u8, + pps.num_ref_idx_l0_default_active_minus1, + pps.num_ref_idx_l1_default_active_minus1, + pps.chroma_qp_index_offset, + pps.second_chroma_qp_index_offset, + &pic_fields, + ))) +} + +/// Ported from cros-codecs `build_enc_slice_param` (BSD-3-Clause), simplified for +/// IPPP (no weighted prediction, single reference in list 0). +fn build_enc_slice_param( + pps: &Pps, + header: &SliceHeader, + reference: Option<(u32, FrameMeta)>, + num_macroblocks: u32, +) -> BufferType { + let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic()); + if let Some((id, m)) = reference { + ref_pic_list_0[0] = build_h264_pic(id, m); + } + let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic()); + + 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, + 0, + header.pred_weight_table.luma_weight_l0, + [0i16; 32], + 0, + header.pred_weight_table.chroma_weight_l0, + [[0i16; 2]; 32], + 0, + header.pred_weight_table.luma_weight_l1, + [0i16; 32], + 0, + header.pred_weight_table.chroma_weight_l1, + [[0i16; 2]; 32], + header.cabac_init_idc, + header.slice_qp_delta, + header.disable_deblocking_filter_idc, + header.slice_alpha_c0_offset_div2, + header.slice_beta_offset_div2, + ))) +} + +/// Returns the packed-header parameter and data buffers for the first `bits` of `data`, a NAL unit that carries its own emulation prevention. +fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] { + let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true)); + let payload = BufferType::EncPackedHeaderData(data.to_vec()); + [param, payload] +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::process::Command; + use std::sync::atomic::{AtomicU32, Ordering}; + + use super::*; + use crate::dmabuf::DmaBuf; + use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420}; + + // A size every driver encodes: radeonsi's H.265 minimum on VCN 5 is 384 wide. + const WIDTH: u32 = 640; + const HEIGHT: u32 = 480; + const CODECS: [Codec; 2] = [Codec::H264, Codec::H265]; + + fn config(codec: Codec) -> Config { + Config { + codec, + ..Config::new(WIDTH, HEIGHT, 30, 2_000_000, 30) + } + } + + /// Opens an encoder, or `None` to skip on a machine without VA-API encode of its codec. + fn encoder(config: Config) -> Option { + let codec = config.codec; + match Encoder::new(config) { + Ok(encoder) => Some(encoder), + Err(err) => { + eprintln!("skipping: no VA-API {codec:?} encoder: {err:#}"); + None + } + } + } + + /// The NAL unit types that open an IDR access unit: the IDR slice, then the parameter sets it carries. + fn idr_types(codec: Codec) -> (u8, &'static [u8]) { + match codec { + Codec::H264 => (5, &[7, 8]), + Codec::H265 => (19, &[32, 33, 34]), + } + } + + /// A diagonal gradient with a block moving across it, so a stale or + /// misplaced reference shows up as the block in the wrong place. + fn nv12_frame(width: u32, height: u32, step: u32) -> Vec { + let (w, h) = (width as usize, height as usize); + let mut data = vec![128u8; w * h + w * h.div_ceil(2)]; + for y in 0..h { + for x in 0..w { + data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8; + } + } + let x0 = (step as usize * 8) % (w / 2); + for y in h / 4..h / 2 { + for x in x0..x0 + w / 4 { + data[y * w + x] = 220; + } + } + data + } + + /// Returns a temporary file path unique to this call. + /// + /// The tests run as threads of one process, so the process id alone would + /// let two of them share a file. + /// + /// Its extension names `codec`, for ffmpeg to pick the demuxer by. + fn temp_path(codec: Codec, label: &str) -> PathBuf { + static NEXT: AtomicU32 = AtomicU32::new(0); + let index = NEXT.fetch_add(1, Ordering::Relaxed); + let extension = match codec { + Codec::H264 => "264", + Codec::H265 => "265", + }; + std::env::temp_dir().join(format!("moq-vaapi-{label}-{}-{index}.{extension}", std::process::id())) + } + + /// Decodes an Annex-B stream with ffmpeg's software decoder into NV12 + /// pictures, or `None` to skip without ffmpeg. + fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> Option> { + // ffmpeg reads the elementary stream from a file rather than a pipe, so + // the test never has to drain its output while still writing its input. + let path = temp_path(codec, name); + std::fs::write(&path, stream).expect("write the elementary stream"); + let output = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&path) + .args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"]) + .output(); + let _ = std::fs::remove_file(&path); + match output { + Ok(output) if output.status.success() => Some(output.stdout), + Ok(output) => panic!("ffmpeg refused the stream: {}", String::from_utf8_lossy(&output.stderr)), + Err(_) => { + eprintln!("skipping: no ffmpeg"); + None + } + } + } + + /// Asks ffprobe for the stream's `color_range,color_space`. + fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option { + let path = temp_path(codec, "probe"); + std::fs::write(&path, stream).expect("write the elementary stream"); + let output = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "stream=color_range,color_space", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .ok(); + let _ = std::fs::remove_file(&path); + Some(String::from_utf8(output?.stdout).ok()?.trim().to_string()) + } + + /// Returns the peak signal-to-noise ratio of the luma planes, in dB. + fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 { + let len = (width * height) as usize; + let mse = a[..len] + .iter() + .zip(&b[..len]) + .map(|(&x, &y)| (x as f64 - y as f64).powi(2)) + .sum::() + / len as f64; + 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10() + } + + /// Returns the mean of the samples in a rectangle of one plane. + fn mean( + plane: &[u8], + stride: usize, + (x0, y0, x1, y1): (usize, usize, usize, usize), + step: usize, + at: usize, + ) -> f64 { + let mut sum = 0.0; + let mut count = 0.0; + for y in y0..y1 { + for x in x0..x1 { + sum += plane[y * stride + x * step + at] as f64; + count += 1.0; + } + } + sum / count + } + + /// Returns the NAL unit types in an Annex-B access unit. + fn nal_types(codec: Codec, unit: &[u8]) -> Vec { + let mut types = Vec::new(); + let mut i = 0; + while i + 3 < unit.len() { + if unit[i..i + 3] == [0, 0, 1] { + types.push(match codec { + Codec::H264 => unit[i + 3] & 0x1f, + Codec::H265 => (unit[i + 3] >> 1) & 0x3f, + }); + i += 3; + } + i += 1; + } + types + } + + /// Returns a driver surface of `fourcc` on `display`, filled through an image. + fn surface_with( + display: &Arc, + fourcc: u32, + rt_format: u32, + (width, height): (u32, u32), + fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage), + ) -> Surface<()> { + let surface = display + .create_surfaces( + rt_format, + Some(fourcc), + width, + height, + Some(UsageHint::USAGE_HINT_EXPORT), + vec![()], + ) + .expect("allocate a surface") + .pop() + .expect("one surface"); + let format = display + .query_image_formats() + .expect("query image formats") + .into_iter() + .find(|f| f.fourcc == fourcc) + .expect("the driver has an image format for the surface format"); + let mut image = + Image::create_from(&surface, format, (width, height), (width, height)).expect("create an image"); + let va_image = *image.image(); + fill(image.as_mut(), &va_image); + drop(image); + surface.sync().expect("sync the filled surface"); + surface + } + + /// Returns an NV12 surface holding `nv12_frame`, exported as a DMA-BUF. + fn nv12_dmabuf(display: &Arc, (width, height): (u32, u32), step: u32) -> DmaBuf { + let surface = surface_with(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height), |_, _| {}); + upload_nv12(display, &surface, width, height, &nv12_frame(width, height, step)).expect("upload"); + DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object") + } + + /// With no node named, the encoder opens one that encodes its codec and + /// records which. A named node is used or refused, never swapped for another. + #[test] + fn the_render_node_is_found_or_named() { + for codec in CODECS { + let Some(encoder) = encoder(config(codec)) else { + continue; + }; + let device = encoder.config().device.clone().expect("the picked node is recorded"); + let display = Display::open_drm_display(&device).expect("reopen the picked node"); + probe(&display, codec).expect("the picked node encodes the codec"); + + let named = Config { + device: Some(PathBuf::from("/dev/null")), + ..config(codec) + }; + assert!( + Encoder::new(named).is_err(), + "a named node that is not a render node was swapped for one that is" + ); + } + } + + /// CPU NV12 in, a stream out that an independent decoder reads back as the + /// same pictures, at a size that is whole coding blocks and at one that is not. + #[test] + fn nv12_round_trips_through_a_software_decoder() { + for codec in CODECS { + for (width, height) in [(WIDTH, HEIGHT), (852, 478)] { + let Some(mut encoder) = encoder(Config { + width, + height, + ..config(codec) + }) else { + continue; + }; + let mut stream = Vec::new(); + let mut frames = Vec::new(); + for step in 0..10 { + let frame = nv12_frame(width, height, step); + stream.extend(encoder.encode_nv12(&frame, false).expect("encode")); + frames.push(frame); + } + let Some(decoded) = ffmpeg_decode(codec, &stream, "nv12") else { + return; + }; + let len = frames[0].len(); + assert_eq!( + decoded.len(), + len * frames.len(), + "{codec:?} at {width}x{height}: ffmpeg decoded a different count or size" + ); + for (index, frame) in frames.iter().enumerate() { + let psnr = luma_psnr(frame, &decoded[index * len..], width, height); + assert!( + psnr > 35.0, + "{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB" + ); + } + } + } + } + + /// The SPS names the color space the encoder was configured with. + #[test] + fn the_stream_is_labelled_with_its_color_space() { + for codec in CODECS { + for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] { + let Some(mut encoder) = encoder(Config { color, ..config(codec) }) else { + break; + }; + let unit = encoder + .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true) + .expect("encode"); + let Some(found) = ffprobe_color(codec, &unit) else { + eprintln!("skipping: no ffprobe"); + return; + }; + assert_eq!(found, expected, "{codec:?}"); + } + } + } + + /// An IDR opens every group, and only there, carrying the parameter sets. + #[test] + fn keyframes_follow_the_group_length() { + for codec in CODECS { + let Some(mut encoder) = encoder(Config { + gop: 10, + ..config(codec) + }) else { + continue; + }; + let (idr_type, parameter_sets) = idr_types(codec); + for step in 0..25 { + let unit = encoder + .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false) + .expect("encode"); + let types = nal_types(codec, &unit); + let idr = types.contains(&idr_type); + assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}"); + if idr { + assert!( + parameter_sets.iter().all(|kind| types.contains(kind)), + "a {codec:?} IDR carries its parameter sets: {types:?}" + ); + } + } + // A forced keyframe restarts the count: the next IDR is a group later. + for step in 0..=10 { + let unit = encoder + .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0) + .expect("encode"); + assert_eq!( + nal_types(codec, &unit).contains(&idr_type), + step % 10 == 0, + "{codec:?} frame {step} after the forced keyframe" + ); + } + } + } + + #[test] + fn the_full_entrypoint_wins_and_low_power_is_the_fallback() { + use VAEntrypoint::{ + VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode, + }; + assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full)); + assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower)); + assert_eq!(pick_entrypoint(&[Decode]), None); + } + + /// A buffer the driver refuses leaves the encoder usable, so the caller's + /// CPU fallback can encode the same frame. + #[test] + fn a_refused_import_leaves_the_encoder_usable() { + let Some(mut encoder) = encoder(config(Codec::H264)) else { + return; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + // A format with no mapping, and a real buffer under a modifier no driver has. + let unmapped = DmaBuf { + drm_format: u32::from_le_bytes(*b"ZZZZ"), + ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0) + }; + assert!(encoder.encode_dmabuf(unmapped, true).is_err()); + let unknown_modifier = DmaBuf { + modifier: 0x00ff_ffff_ffff_fffe, + ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0) + }; + assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err()); + + let unit = encoder + .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true) + .expect("the CPU path still encodes"); + let Some(decoded) = ffmpeg_decode(Codec::H264, &unit, "refused") else { + return; + }; + let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT); + assert!(psnr > 35.0, "decoded at {psnr:.1} dB"); + } + + /// A buffer short of whole coding blocks is not encoded in place: the + /// encoder reads whole blocks, so it goes through the video processor into + /// the padded input surface. That is 1080 rows for H.264, which reads 1088, + /// and 1076 for H.265, whose minimum coding blocks are 8 or 16 rows. + #[test] + fn a_buffer_short_of_whole_coding_blocks_is_blitted() { + for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] { + let Some(mut encoder) = encoder(Config { + codec, + ..Config::new(width, height, 30, 4_000_000, 30) + }) else { + continue; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let unit = encoder + .encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true) + .expect("encode the DMA-BUF"); + let Some(decoded) = ffmpeg_decode(codec, &unit, "short") else { + return; + }; + let frame = nv12_frame(width, height, 0); + assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size"); + let psnr = luma_psnr(&frame, &decoded, width, height); + assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB"); + } + } + + /// A YUV buffer labelled with another color space is converted into the + /// stream's, not relabelled. + #[test] + fn a_yuv_dmabuf_in_another_space_is_converted() { + for codec in CODECS { + yuv_dmabuf_in_another_space_is_converted(codec); + } + } + + fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) { + let Some(mut encoder) = encoder(Config { + color: Color::BT601, + ..config(codec) + }) else { + return; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + // Flat red, written in BT.709. + let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8); + let surface = surface_with( + &display, + VA_FOURCC_NV12, + VA_RT_FORMAT_YUV420, + (WIDTH, HEIGHT), + |data, image| { + for row in 0..HEIGHT as usize { + let at = image.offsets[0] as usize + row * image.pitches[0] as usize; + data[at..at + WIDTH as usize].fill(y); + } + for row in 0..HEIGHT as usize / 2 { + let at = image.offsets[1] as usize + row * image.pitches[1] as usize; + for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) { + pair.copy_from_slice(&[u, v]); + } + } + }, + ); + let buffer = DmaBuf { + color: Some(Color::BT709), + ..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object") + }; + let unit = encoder.encode_dmabuf(buffer, true).expect("encode"); + let Some(decoded) = ffmpeg_decode(codec, &unit, "yuv-color") else { + return; + }; + + let (w, h) = (WIDTH as usize, HEIGHT as usize); + let (luma, chroma) = decoded.split_at(w * h); + let actual = [ + mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0), + mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0), + mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1), + ]; + let expected = limited([255, 0, 0], Color::BT601); + for (channel, (a, e)) in actual.iter().zip(expected).enumerate() { + assert!( + (a - e).abs() < 6.0, + "{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}" + ); + } + } + + /// An NV12 DMA-BUF at the encoder's size is encoded from the producer's memory. + #[test] + fn an_nv12_dmabuf_encodes_in_place() { + for codec in CODECS { + let Some(mut encoder) = encoder(config(codec)) else { + continue; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let mut stream = Vec::new(); + for step in 0..5 { + let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step); + stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF")); + } + let Some(decoded) = ffmpeg_decode(codec, &stream, "dmabuf") else { + return; + }; + let len = nv12_frame(WIDTH, HEIGHT, 0).len(); + assert_eq!(decoded.len(), 5 * len, "{codec:?}"); + for step in 0..5 { + let psnr = luma_psnr( + &nv12_frame(WIDTH, HEIGHT, step), + &decoded[step as usize * len..], + WIDTH, + HEIGHT, + ); + assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB"); + } + } + } + + /// An NV12 DMA-BUF at another size is scaled to the encoder's on the GPU. + #[test] + fn a_dmabuf_at_another_size_is_scaled() { + for codec in CODECS { + dmabuf_at_another_size_is_scaled(codec); + } + } + + fn dmabuf_at_another_size_is_scaled(codec: Codec) { + let Some(mut encoder) = encoder(config(codec)) else { + return; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let mut stream = Vec::new(); + for step in 0..3 { + let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step); + stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF")); + } + let Some(decoded) = ffmpeg_decode(codec, &stream, "scaled") else { + return; + }; + let len = nv12_frame(WIDTH, HEIGHT, 0).len(); + assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size"); + // Compare against the source scaled on the CPU by point sampling, which + // differs from the GPU filter only at edges. 25 dB separates a scale + // from a crop, which scores about 16 dB on this gradient. + for step in 0..3u32 { + let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step); + let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize]; + for y in 0..HEIGHT as usize { + for x in 0..WIDTH as usize { + expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2]; + } + } + let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT); + assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB"); + } + } + + /// A packed RGB DMA-BUF is converted on the GPU into the configured color space. + #[test] + fn an_rgb_dmabuf_is_converted_to_the_configured_space() { + // Four flat quadrants, so the check reads colors rather than edges. + const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; + for (codec, color) in CODECS + .into_iter() + .flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)]) + { + let Some(mut encoder) = encoder(Config { color, ..config(codec) }) else { + continue; + }; + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let surface = surface_with( + &display, + VA_FOURCC_BGRX, + VA_RT_FORMAT_RGB32, + (WIDTH, HEIGHT), + |data, image| { + let pitch = image.pitches[0] as usize; + let offset = image.offsets[0] as usize; + for y in 0..HEIGHT as usize { + for x in 0..WIDTH as usize { + let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize; + let [r, g, b] = QUADRANTS[quadrant]; + let at = offset + y * pitch + x * 4; + data[at..at + 4].copy_from_slice(&[b, g, r, 255]); + } + } + }, + ); + let exported = surface.export_prime().expect("export"); + let buffer = DmaBuf::from_prime(exported).expect("one object"); + assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888); + let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF"); + let Some(decoded) = ffmpeg_decode(codec, &unit, "rgb") else { + return; + }; + + let (w, h) = (WIDTH as usize, HEIGHT as usize); + let (luma, chroma) = decoded.split_at(w * h); + for (quadrant, rgb) in QUADRANTS.iter().enumerate() { + let (qx, qy) = (quadrant % 2, quadrant / 2); + // The middle half of each quadrant, clear of the chroma bleed at its edges. + let area = |scale: usize| { + let (qw, qh) = (w / 2 / scale, h / 2 / scale); + ( + qx * qw + qw / 4, + qy * qh + qh / 4, + qx * qw + qw * 3 / 4, + qy * qh + qh * 3 / 4, + ) + }; + let actual = [ + mean(luma, w, area(1), 1, 0), + mean(chroma, w, area(2), 2, 0), + mean(chroma, w, area(2), 2, 1), + ]; + let expected = limited(*rgb, color); + for (channel, (a, e)) in actual.iter().zip(expected).enumerate() { + assert!( + (a - e).abs() < 6.0, + "{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}" + ); + } + } + } + } + + #[test] + fn the_level_covers_the_frame_size_and_rate() { + assert_eq!(level(320, 240, 30), Level::L4); + assert_eq!(level(1920, 1080, 30), Level::L4); + assert_eq!(level(1920, 1080, 60), Level::L4_2); + assert_eq!(level(2560, 1440, 30), Level::L5); + assert_eq!(level(3840, 2160, 30), Level::L5_1); + assert_eq!(level(3840, 2160, 60), Level::L5_2); + } + + /// Returns the limited-range Y'CbCr of an RGB color, per BT.601 or BT.709. + fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] { + let (kr, kb) = match color.matrix { + crate::Matrix::Bt601 => (0.299, 0.114), + crate::Matrix::Bt709 => (0.2126, 0.0722), + }; + let (r, g, b) = (r as f64, g as f64, b as f64); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + [ + 16.0 + y * 219.0 / 255.0, + 128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0, + 128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0, + ] + } + + /// Lowering the bitrate mid-stream shrinks the pictures without an IDR, and + /// the rate controller holds the stream near each target. + #[test] + fn a_bitrate_change_takes_effect_without_a_keyframe() { + for codec in CODECS { + bitrate_change_takes_effect_without_a_keyframe(codec); + } + } + + fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) { + let Some(mut encoder) = encoder(Config { + codec, + ..Config::new(WIDTH, HEIGHT, 30, 2_000_000, 1_000) + }) else { + return; + }; + let (idr_type, _) = idr_types(codec); + // A zone plate whose phase moves every picture: detail motion + // compensation cannot predict, so 2 Mbps is spent, yet the drivers + // can code it at 250 kbps when the quantizer may go high enough. + let frame = |step: u32| { + let (w, h) = (WIDTH as usize, HEIGHT as usize); + let mut frame = vec![128u8; w * h + w * h.div_ceil(2)]; + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0); + let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5; + frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8; + } + } + frame + }; + // The mean picture size over the second half of 60 frames, once the + // rate controller has settled. + // Also asserts that no picture after the first is an IDR. + let average = |encoder: &mut Encoder, from: u32| { + let sizes: Vec = (from..from + 60) + .map(|step| { + let unit = encoder.encode_nv12(&frame(step), false).expect("encode"); + if step > 0 { + assert!( + !nal_types(codec, &unit).contains(&idr_type), + "{codec:?} picture {step} is an IDR" + ); + } + unit.len() + }) + .collect(); + sizes[30..].iter().sum::() / 30 + }; + + // A settled stream within a quarter above its target; a quantizer + // ceiling the rate controller cannot get past misses by double or more. + let within = |bytes: usize, bitrate: u32| { + let target = bitrate as usize / 8 / 30; + assert!( + bytes * 4 <= target * 5, + "{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}" + ); + }; + + let high = average(&mut encoder, 0); + within(high, 2_000_000); + encoder.set_bitrate(250_000).expect("set the bitrate"); + assert_eq!(encoder.config().bitrate, 250_000); + assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused"); + let low = average(&mut encoder, 60); + eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes"); + within(low, 250_000); + assert!( + low * 3 < high, + "{codec:?}: the rate did not drop: {high} -> {low} bytes per picture" + ); + } +} diff --git a/rs/moq-vaapi/src/encode/h265.rs b/rs/moq-vaapi/src/encode/h265.rs new file mode 100644 index 00000000000..e7d0a08ea59 --- /dev/null +++ b/rs/moq-vaapi/src/encode/h265.rs @@ -0,0 +1,876 @@ +//! The H.265 half of the encoder: Main profile parameter sets and slice headers +//! written here, and the VA-API buffers that describe each picture. +//! +//! The parameter sets and slice headers are written here and handed to the +//! driver packed, so it produces only the slice data. That is what ffmpeg's +//! `hevc_vaapi` does, and the path the Intel and AMD drivers are exercised on. +//! A driver must take the packed parameter sets, since VA's sequence parameters +//! cannot carry the conformance window or the VUI; one that does not take +//! packed slice headers writes them itself, from parameter buffers that +//! describe the same stream. +//! +//! The coding tools follow what the driver reports through +//! `VAConfigAttribEncHEVCFeatures` and `VAConfigAttribEncHEVCBlockSizes`: a +//! tool it supports or requires is on, and one it requires that this writer +//! does not emit fails the open. A driver that can predict only from +//! non-empty lists in both directions (`VA_PREDICTION_DIRECTION_BI_NOT_EMPTY`, +//! Intel's low-power encoder among them) gets each P picture as a generalized +//! B picture: a B slice whose list 1 repeats list 0. + +use std::rc::Rc; + +use anyhow::{anyhow, bail}; + +use super::{Config, Reference}; +use crate::{ + bindings, BufferType, Config as VaConfig, Display, EncCodedBuffer, EncPackedHeaderType, EncPictureParameter, + EncPictureParameterBufferHEVC, EncSequenceParameter, EncSequenceParameterBufferHEVC, EncSliceParameter, + EncSliceParameterBufferHEVC, GenericValue, HEVCEncPicFields, HEVCEncSeqFields, HevcEncPicSccFields, + HevcEncSeqSccFields, HevcEncSliceFields, PictureHEVC, VAConfigAttrib, VAConfigAttribType, VAEntrypoint, VAProfile, + VASurfaceAttribType, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, + VA_INVALID_ID, VA_PICTURE_HEVC_INVALID, VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE, VA_PREDICTION_DIRECTION_BI_NOT_EMPTY, +}; + +/// NAL unit types, H.265 Table 7-1. +const TRAIL_R: u8 = 1; +const IDR_W_RADL: u8 = 19; +const VPS: u8 = 32; +const SPS: u8 = 33; +const PPS: u8 = 34; + +/// Slice types, H.265 Table 7-7. +const SLICE_B: u8 = 0; +const SLICE_P: u8 = 1; +const SLICE_I: u8 = 2; + +/// `general_profile_idc` of the Main profile. +const MAIN: u8 = 1; + +/// `log2_max_pic_order_cnt_lsb_minus4`: twelve bits of order count per slice, as ffmpeg writes. +const LOG2_MAX_POC_LSB_MINUS4: u32 = 8; + +/// The QP the PPS opens each picture at; rate control moves off it per picture. +const INIT_QP: i32 = 26; + +/// The VA profile this encoder opens. +pub(super) const PROFILE: VAProfile::Type = VAProfile::VAProfileHEVCMain; + +/// How a feature of `VAConfigAttribValEncHEVCFeatures` is offered. +const UNSUPPORTED: u32 = 0; +const REQUIRED: u32 = 2; + +/// The coding tools and block sizes a stream is written with, settled once from what the driver reports. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Tools { + log2_min_cb: u32, + log2_ctb: u32, + log2_min_tb: u32, + log2_max_tb: u32, + depth_inter: u32, + depth_intra: u32, + amp: bool, + sao: bool, + temporal_mvp: bool, + transform_skip: bool, + cu_qp_delta: bool, + /// Whether P pictures go out as B slices whose list 1 repeats list 0. + gpb: bool, +} + +impl Tools { + /// What ffmpeg assumes of a driver too old to report its block sizes and features: the first Intel HEVC encoder's. + const FALLBACK: Self = Self { + log2_min_cb: 4, + log2_ctb: 5, + log2_min_tb: 2, + log2_max_tb: 5, + depth_inter: 3, + depth_intra: 3, + amp: true, + sao: false, + temporal_mvp: false, + transform_skip: false, + cu_qp_delta: true, + gpb: false, + }; + + /// Asks `display` what its H.265 Main encoder on `entrypoint` supports. + /// + /// # Errors + /// + /// Fails when the driver cannot be asked, when it predicts from no + /// previous picture, and when it requires a tool this writer does not emit. + fn query(display: &Display, entrypoint: VAEntrypoint::Type) -> anyhow::Result { + let mut attrs = [ + VAConfigAttribType::VAConfigAttribEncHEVCFeatures, + VAConfigAttribType::VAConfigAttribEncHEVCBlockSizes, + VAConfigAttribType::VAConfigAttribEncMaxRefFrames, + VAConfigAttribType::VAConfigAttribPredictionDirection, + ] + .map(|type_| VAConfigAttrib { type_, value: 0 }); + display + .get_config_attributes(PROFILE, entrypoint, &mut attrs) + .map_err(|e| anyhow!("query H.265 encode attributes: {e:?}"))?; + let reported = |index: usize| Some(attrs[index].value).filter(|&value| value != VA_ATTRIB_NOT_SUPPORTED); + let (features, blocks, references, direction) = (reported(0), reported(1), reported(2), reported(3)); + + let mut tools = Self::FALLBACK; + if let Some(blocks) = blocks { + let blocks = bindings::VAConfigAttribValEncHEVCBlockSizes { value: blocks }; + // Safe because both members of the union are plain integers over the same 32 bits. + let blocks = unsafe { blocks.bits }; + tools.log2_ctb = blocks.log2_max_coding_tree_block_size_minus3() + 3; + tools.log2_min_cb = blocks.log2_min_luma_coding_block_size_minus3() + 3; + tools.log2_min_tb = blocks.log2_min_luma_transform_block_size_minus2() + 2; + tools.log2_max_tb = blocks.log2_max_luma_transform_block_size_minus2() + 2; + tools.depth_inter = blocks.max_max_transform_hierarchy_depth_inter(); + tools.depth_intra = blocks.max_max_transform_hierarchy_depth_intra(); + } + if let Some(features) = features { + let features = bindings::VAConfigAttribValEncHEVCFeatures { value: features }; + // Safe because both members of the union are plain integers over the same 32 bits. + let features = unsafe { features.bits }; + tools.amp = features.amp() != UNSUPPORTED; + tools.sao = features.sao() != UNSUPPORTED; + tools.temporal_mvp = features.temporal_mvp() != UNSUPPORTED; + tools.transform_skip = features.transform_skip() != UNSUPPORTED; + tools.cu_qp_delta = features.cu_qp_delta() != UNSUPPORTED; + for (name, offered) in [ + ("separate colour planes", features.separate_colour_planes()), + ("scaling lists", features.scaling_lists()), + ("PCM", features.pcm()), + ("strong intra smoothing", features.strong_intra_smoothing()), + ("dependent slices", features.dependent_slices()), + ("sign data hiding", features.sign_data_hiding()), + ("constrained intra prediction", features.constrained_intra_pred()), + ("weighted prediction", features.weighted_prediction()), + ("transquant bypass", features.transquant_bypass()), + ("a disabled deblocking filter", features.deblocking_filter_disable()), + ] { + if offered == REQUIRED { + bail!("the driver requires {name}, which this encoder does not write"); + } + } + } + if tools.log2_min_cb > tools.log2_ctb + || tools.log2_min_tb > tools.log2_max_tb + || tools.log2_max_tb > tools.log2_ctb.min(5) + || tools.log2_min_tb >= tools.log2_min_cb + { + bail!("the driver reports inconsistent H.265 block sizes: {tools:?}"); + } + + let (list0, list1) = match references { + Some(value) => (value & 0xffff, value >> 16 & 0xffff), + None => (1, 0), + }; + if list0 == 0 { + bail!("the driver's H.265 encoder predicts from no reference picture"); + } + tools.gpb = + list1 > 0 && direction.is_some_and(|direction| direction & VA_PREDICTION_DIRECTION_BI_NOT_EMPTY != 0); + Ok(tools) + } +} + +/// An H.265 stream's settled parameters: everything per picture derives from these. +pub(super) struct Stream { + tools: Tools, + /// The coded size: the frame rounded up to whole minimum coding blocks and to the driver's surface alignment. + coded: (u32, u32), + level_idc: u8, + /// The VPS, SPS, and PPS, each behind a start code, sent ahead of every IDR. + headers: Vec, +} + +impl Stream { + /// Settles the parameters for `config` on `display`'s encoder at `entrypoint`, configured as `va_config`. + /// + /// # Errors + /// + /// Fails as [`Tools::query`] does, and for a frame too large for any level. + pub(super) fn new( + display: &Display, + entrypoint: VAEntrypoint::Type, + va_config: &mut VaConfig, + config: &Config, + ) -> anyhow::Result { + let tools = Tools::query(display, entrypoint)?; + Self::with_tools(tools, alignment(va_config), config) + } + + /// `alignment` is the driver's surface alignment, in samples across and down. + fn with_tools(tools: Tools, alignment: (u32, u32), config: &Config) -> anyhow::Result { + let min_cb = 1 << tools.log2_min_cb; + let coded = ( + config.width.next_multiple_of(min_cb.max(alignment.0)), + config.height.next_multiple_of(min_cb.max(alignment.1)), + ); + let level_idc = level(coded, config.framerate).ok_or_else(|| { + anyhow!( + "{}x{} at {} fps exceeds every H.265 level", + coded.0, + coded.1, + config.framerate + ) + })?; + let mut stream = Self { + tools, + coded, + level_idc, + headers: Vec::new(), + }; + stream.headers = [stream.vps(config), stream.sps(config), stream.pps()].concat(); + Ok(stream) + } + + /// Returns the coded size: what the context, the reconstructed surfaces, and the SPS are sized to. + pub(super) fn coded(&self) -> (u32, u32) { + self.coded + } + + /// Returns the VA buffers for one picture, in the order the driver takes them: sequence, picture, slice, then packed headers. + pub(super) fn buffers(&self, config: &Config, picture: &super::PictureInfo<'_>, packed: u32) -> Vec { + let tools = &self.tools; + let poc = picture.count as i32; + let current = PictureHEVC::new(picture.recon, poc, 0); + let reference = picture.reference.map(|Reference { surface, count }| { + PictureHEVC::new(surface, count as i32, VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE) + }); + let slice_type = match (reference.is_some(), tools.gpb) { + (false, _) => SLICE_I, + (true, false) => SLICE_P, + (true, true) => SLICE_B, + }; + let nal_type = if picture.idr { IDR_W_RADL } else { TRAIL_R }; + + let mut buffers = vec![ + self.sequence_parameters(config, picture.bitrate), + self.picture_parameters(picture.coded, current, reference.as_ref(), nal_type), + self.slice_parameters(slice_type, reference.as_ref()), + ]; + if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 { + buffers.extend(super::packed_header( + EncPackedHeaderType::Sequence, + &self.headers, + self.headers.len() * 8, + )); + } + if packed & VA_ENC_PACKED_HEADER_SLICE != 0 { + let header = self.slice_header(nal_type, slice_type, picture.count); + buffers.extend(super::packed_header( + EncPackedHeaderType::Slice, + &header, + header.len() * 8, + )); + } + buffers + } + + fn ctb_count(&self) -> u32 { + let ctb = 1 << self.tools.log2_ctb; + self.coded.0.div_ceil(ctb) * self.coded.1.div_ceil(ctb) + } + + fn sequence_parameters(&self, config: &Config, bitrate: u32) -> BufferType { + let tools = &self.tools; + let fields = HEVCEncSeqFields::new( + 1, // chroma_format_idc: 4:2:0 + 0, + 0, + 0, + 0, + 0, + tools.amp as u32, + tools.sao as u32, + 0, + 0, + tools.temporal_mvp as u32, + 0, + 0, + ); + BufferType::EncSequenceParameter(EncSequenceParameter::HEVC(EncSequenceParameterBufferHEVC::new( + MAIN, + self.level_idc, + 0, // Main tier + config.gop, + config.gop, + 1, // ip_period: no B pictures + bitrate, + self.coded.0 as u16, + self.coded.1 as u16, + &fields, + (tools.log2_min_cb - 3) as u8, + (tools.log2_ctb - tools.log2_min_cb) as u8, + (tools.log2_min_tb - 2) as u8, + (tools.log2_max_tb - tools.log2_min_tb) as u8, + tools.depth_inter as u8, + tools.depth_intra as u8, + 0, + 0, + 0, + 0, + // The VUI is in the packed SPS, which is what goes out. + None, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + &HevcEncSeqSccFields::new(0), + ))) + } + + fn picture_parameters( + &self, + coded: &EncCodedBuffer, + current: PictureHEVC, + reference: Option<&PictureHEVC>, + nal_type: u8, + ) -> BufferType { + let tools = &self.tools; + let idr = nal_type == IDR_W_RADL; + let fields = HEVCEncPicFields::new( + idr as u32, + if reference.is_some() { 2 } else { 1 }, // coding_type: P (or GPB), else I + 1, // reference_pic_flag + 0, + 0, + 0, + tools.transform_skip as u32, + tools.cu_qp_delta as u32, + 0, + 0, + 0, + 0, + 0, + 0, + 1, // pps_loop_filter_across_slices_enabled_flag + 0, + 0, + 0, + 0, + ); + let mut references: [PictureHEVC; 15] = std::array::from_fn(|_| invalid()); + if let Some(reference) = reference { + references[0] = reference.clone(); + } + BufferType::EncPictureParameter(EncPictureParameter::HEVC(EncPictureParameterBufferHEVC::new( + current, + references, + coded.id(), + if tools.temporal_mvp { 0 } else { 0xff }, + 0, + INIT_QP as u8, + self.diff_cu_qp_delta_depth() as u8, + 0, + 0, + 0, + 0, + [0; 19], + [0; 21], + 0, + 0, + 0, + 0, + 0, + nal_type, + &fields, + 0, + 0, + &HevcEncPicSccFields::new(0), + ))) + } + + fn slice_parameters(&self, slice_type: u8, reference: Option<&PictureHEVC>) -> BufferType { + let tools = &self.tools; + let mut list0: [PictureHEVC; 15] = std::array::from_fn(|_| invalid()); + let mut list1: [PictureHEVC; 15] = std::array::from_fn(|_| invalid()); + if let Some(reference) = reference { + list0[0] = reference.clone(); + if slice_type == SLICE_B { + list1[0] = reference.clone(); + } + } + let fields = HevcEncSliceFields::new( + 1, // last_slice_of_pic_flag + 0, + 0, + (tools.temporal_mvp && reference.is_some()) as u32, + tools.sao as u32, + tools.sao as u32, + 0, + 0, + 0, + 0, + 0, + 1, // collocated_from_l0_flag + ); + BufferType::EncSliceParameter(EncSliceParameter::HEVC(EncSliceParameterBufferHEVC::new( + 0, + self.ctb_count(), + slice_type, + 0, + 0, + 0, + list0, + list1, + 0, + 0, + [0; 15], + [0; 15], + [[0; 2]; 15], + [[0; 2]; 15], + [0; 15], + [0; 15], + [[0; 2]; 15], + [[0; 2]; 15], + 5, // max_num_merge_cand + 0, + 0, + 0, + 0, + 0, + &fields, + 0, + 0, + ))) + } + + fn diff_cu_qp_delta_depth(&self) -> u32 { + match self.tools.cu_qp_delta { + true => self.tools.log2_ctb - self.tools.log2_min_cb, + false => 0, + } + } + + /// Writes `profile_tier_level` for Main with no sub-layers, H.265 7.3.3. + fn profile_tier_level(&self, w: &mut Rbsp) { + w.bits(2, 0); // general_profile_space + w.flag(false); // general_tier_flag: Main + w.bits(5, MAIN.into()); + // Main, and Main 10 which every Main stream also conforms to. + w.bits(32, 1 << (31 - 1) | 1 << (31 - 2)); + w.flag(true); // general_progressive_source_flag + w.flag(false); // general_interlaced_source_flag + w.flag(true); // general_non_packed_constraint_flag + w.flag(true); // general_frame_only_constraint_flag + // The 43 reserved bits and general_inbld_flag of a Main profile. + w.bits(32, 0); + w.bits(12, 0); + w.bits(8, self.level_idc.into()); + } + + /// Writes the video parameter set, H.265 7.3.2.1. + fn vps(&self, config: &Config) -> Vec { + let mut w = Rbsp::default(); + w.bits(4, 0); // vps_video_parameter_set_id + w.flag(true); // vps_base_layer_internal_flag + w.flag(true); // vps_base_layer_available_flag + w.bits(6, 0); // vps_max_layers_minus1 + w.bits(3, 0); // vps_max_sub_layers_minus1 + w.flag(true); // vps_temporal_id_nesting_flag + w.bits(16, 0xffff); + self.profile_tier_level(&mut w); + w.flag(false); // vps_sub_layer_ordering_info_present_flag + ordering(&mut w); + w.bits(6, 0); // vps_max_layer_id + w.ue(0); // vps_num_layer_sets_minus1 + w.flag(true); // vps_timing_info_present_flag + timing(&mut w, config.framerate); + w.ue(0); // vps_num_hrd_parameters + w.flag(false); // vps_extension_flag + w.trailing(); + nal(VPS, &w.finish()) + } + + /// Writes the sequence parameter set, H.265 7.3.2.2, with its VUI. + fn sps(&self, config: &Config) -> Vec { + let tools = &self.tools; + let mut w = Rbsp::default(); + w.bits(4, 0); // sps_video_parameter_set_id + w.bits(3, 0); // sps_max_sub_layers_minus1 + w.flag(true); // sps_temporal_id_nesting_flag + self.profile_tier_level(&mut w); + w.ue(0); // sps_seq_parameter_set_id + w.ue(1); // chroma_format_idc: 4:2:0 + w.ue(self.coded.0); + w.ue(self.coded.1); + // The conformance window crops the coded size back to the frame, in + // chroma samples, so in units of two luma samples each way. + let crop = (self.coded.0 - config.width, self.coded.1 - config.height); + w.flag(crop != (0, 0)); + if crop != (0, 0) { + w.ue(0); + w.ue(crop.0 / 2); + w.ue(0); + w.ue(crop.1 / 2); + } + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(LOG2_MAX_POC_LSB_MINUS4); + w.flag(false); // sps_sub_layer_ordering_info_present_flag + ordering(&mut w); + w.ue(tools.log2_min_cb - 3); + w.ue(tools.log2_ctb - tools.log2_min_cb); + w.ue(tools.log2_min_tb - 2); + w.ue(tools.log2_max_tb - tools.log2_min_tb); + w.ue(tools.depth_inter); + w.ue(tools.depth_intra); + w.flag(false); // scaling_list_enabled_flag + w.flag(tools.amp); + w.flag(tools.sao); + w.flag(false); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets: each slice carries its own + w.flag(false); // long_term_ref_pics_present_flag + w.flag(tools.temporal_mvp); + w.flag(false); // strong_intra_smoothing_enabled_flag + w.flag(true); // vui_parameters_present_flag + self.vui(&mut w, config); + w.flag(false); // sps_extension_present_flag + w.trailing(); + nal(SPS, &w.finish()) + } + + /// Writes the VUI, H.265 E.2.1: the color space, the frame rate, and the restrictions IPPP coding keeps. + fn vui(&self, w: &mut Rbsp, config: &Config) { + let (primaries, transfer, matrix) = config.color.vui(); + w.flag(false); // aspect_ratio_info_present_flag + w.flag(false); // overscan_info_present_flag + w.flag(true); // video_signal_type_present_flag + w.bits(3, 5); // video_format: unspecified + w.flag(config.color.full_range); + w.flag(true); // colour_description_present_flag + w.bits(8, primaries.into()); + w.bits(8, transfer.into()); + w.bits(8, matrix.into()); + w.flag(false); // chroma_loc_info_present_flag + w.flag(false); // neutral_chroma_indication_flag + w.flag(false); // field_seq_flag + w.flag(false); // frame_field_info_present_flag + w.flag(false); // default_display_window_flag + w.flag(true); // vui_timing_info_present_flag + timing(w, config.framerate); + w.flag(false); // vui_hrd_parameters_present_flag + w.flag(true); // bitstream_restriction_flag + w.flag(false); // tiles_fixed_structure_flag + w.flag(true); // motion_vectors_over_pic_boundaries_flag + w.flag(true); // restricted_ref_pic_lists_flag + w.ue(0); // min_spatial_segmentation_idc + w.ue(0); // max_bytes_per_pic_denom + w.ue(0); // max_bits_per_min_cu_denom + w.ue(15); // log2_max_mv_length_horizontal + w.ue(15); // log2_max_mv_length_vertical + } + + /// Writes the picture parameter set, H.265 7.3.2.3. + fn pps(&self) -> Vec { + let tools = &self.tools; + let mut w = Rbsp::default(); + w.ue(0); // pps_pic_parameter_set_id + w.ue(0); // pps_seq_parameter_set_id + w.flag(false); // dependent_slice_segments_enabled_flag + w.flag(false); // output_flag_present_flag + w.bits(3, 0); // num_extra_slice_header_bits + w.flag(false); // sign_data_hiding_enabled_flag + w.flag(false); // cabac_init_present_flag + w.ue(0); // num_ref_idx_l0_default_active_minus1 + w.ue(0); // num_ref_idx_l1_default_active_minus1 + w.se(INIT_QP - 26); + w.flag(false); // constrained_intra_pred_flag + w.flag(tools.transform_skip); + w.flag(tools.cu_qp_delta); + if tools.cu_qp_delta { + w.ue(self.diff_cu_qp_delta_depth()); + } + w.se(0); // pps_cb_qp_offset + w.se(0); // pps_cr_qp_offset + w.flag(false); // pps_slice_chroma_qp_offsets_present_flag + w.flag(false); // weighted_pred_flag + w.flag(false); // weighted_bipred_flag + w.flag(false); // transquant_bypass_enabled_flag + w.flag(false); // tiles_enabled_flag + w.flag(false); // entropy_coding_sync_enabled_flag + w.flag(true); // pps_loop_filter_across_slices_enabled_flag + w.flag(false); // deblocking_filter_control_present_flag + w.flag(false); // pps_scaling_list_data_present_flag + w.flag(false); // lists_modification_present_flag + w.ue(0); // log2_parallel_merge_level_minus2 + w.flag(false); // slice_segment_header_extension_present_flag + w.flag(false); // pps_extension_present_flag + w.trailing(); + nal(PPS, &w.finish()) + } + + /// Writes the header of a picture's one slice segment, H.265 7.3.6.1. + /// + /// A P or GPB picture refers to the one before it, so its short-term + /// reference set is that single picture, one order count back. + fn slice_header(&self, nal_type: u8, slice_type: u8, count: u32) -> Vec { + let tools = &self.tools; + let mut w = Rbsp::default(); + w.flag(true); // first_slice_segment_in_pic_flag + if nal_type == IDR_W_RADL { + w.flag(false); // no_output_of_prior_pics_flag + } + w.ue(0); // slice_pic_parameter_set_id + w.ue(slice_type.into()); + if nal_type != IDR_W_RADL { + let lsb_bits = LOG2_MAX_POC_LSB_MINUS4 + 4; + w.bits(lsb_bits, count & ((1 << lsb_bits) - 1)); + w.flag(false); // short_term_ref_pic_set_sps_flag + // st_ref_pic_set(0): no inter prediction of the set at index 0. + w.ue(1); // num_negative_pics + w.ue(0); // num_positive_pics + w.ue(0); // delta_poc_s0_minus1: the previous picture + w.flag(true); // used_by_curr_pic_s0_flag + if tools.temporal_mvp { + w.flag(true); // slice_temporal_mvp_enabled_flag + } + } + if tools.sao { + w.flag(true); // slice_sao_luma_flag + w.flag(true); // slice_sao_chroma_flag + } + if slice_type != SLICE_I { + w.flag(false); // num_ref_idx_active_override_flag + if slice_type == SLICE_B { + w.flag(false); // mvd_l1_zero_flag + } + if tools.temporal_mvp && slice_type == SLICE_B { + w.flag(true); // collocated_from_l0_flag + } + w.ue(0); // five_minus_max_num_merge_cand + } + w.se(0); // slice_qp_delta + // Loop filtering is on, so this is present; with one slice it filters nothing. + w.flag(false); // slice_loop_filter_across_slices_enabled_flag + w.byte_alignment(); + nal(nal_type, &w.finish()) + } +} + +/// Returns an empty reference slot. +fn invalid() -> PictureHEVC { + PictureHEVC::new(VA_INVALID_ID, 0, VA_PICTURE_HEVC_INVALID) +} + +/// Writes the one set of sub-layer ordering limits, for IPPP coding: one reference and the current picture, nothing reordered. +fn ordering(w: &mut Rbsp) { + w.ue(1); // max_dec_pic_buffering_minus1 + w.ue(0); // max_num_reorder_pics + w.ue(0); // max_latency_increase_plus1 +} + +/// Returns the surface alignment the driver encodes at, in samples across and down: 1 where it names none. +/// +/// radeonsi encodes a picture rounded up to it (64 by 16) and rewrites the SPS +/// at that size, keeping our conformance window, so a coded size short of it +/// would decode with the wrong crop. +fn alignment(va_config: &mut VaConfig) -> (u32, u32) { + let named = va_config + .query_surface_attributes_by_type(VASurfaceAttribType::VASurfaceAttribAlignmentSize) + .ok() + .and_then(|values| values.into_iter().next()); + match named { + // VASurfaceAttribAlignmentStruct: log2 width in bits 0-3, log2 height in bits 4-7. + Some(GenericValue::Integer(value)) => (1 << (value & 0xf), 1 << ((value >> 4) & 0xf)), + _ => (1, 1), + } +} + +/// Writes the timing a VPS and a VUI share: one tick per frame, and an order count step per picture. +fn timing(w: &mut Rbsp, framerate: u32) { + w.bits(32, 1); // num_units_in_tick + w.bits(32, framerate.max(1)); // time_scale + w.flag(true); // poc_proportional_to_timing_flag + w.ue(0); // num_ticks_poc_diff_one_minus1 +} + +/// Returns `general_level_idc` for the lowest Main tier level whose picture size and sample rate cover a `coded` picture at `framerate`. +/// +/// Only those limits, as for H.264: the level's maximum bitrate is not +/// checked, since the bitrate can change while the SPS cannot. +fn level((width, height): (u32, u32), framerate: u32) -> Option { + // H.265 Table A.8: (level_idc, MaxLumaPs, MaxLumaSr). + const LEVELS: [(u8, u64, u64); 13] = [ + (30, 36_864, 552_960), + (60, 122_880, 3_686_400), + (63, 245_760, 7_372_800), + (90, 552_960, 16_588_800), + (93, 983_040, 33_177_600), + (120, 2_228_224, 66_846_720), + (123, 2_228_224, 133_693_440), + (150, 8_912_896, 267_386_880), + (153, 8_912_896, 534_773_760), + (156, 8_912_896, 1_069_547_520), + (180, 35_651_584, 1_069_547_520), + (183, 35_651_584, 2_139_095_040), + (186, 35_651_584, 4_278_190_080), + ]; + let size = u64::from(width) * u64::from(height); + let rate = size * u64::from(framerate.max(1)); + // A.4.1: neither side may exceed sqrt(8 * MaxLumaPs). + let side = u64::from(width.max(height)).pow(2); + LEVELS + .into_iter() + .find(|&(_, max_size, max_rate)| size <= max_size && side <= 8 * max_size && rate <= max_rate) + .map(|(level, _, _)| level) +} + +/// Writes NAL unit type `kind` behind a four-byte start code, with emulation prevention. +fn nal(kind: u8, rbsp: &[u8]) -> Vec { + // nal_unit_header: forbidden_zero_bit, nal_unit_type, nuh_layer_id 0, nuh_temporal_id_plus1 1. + let mut out = vec![0, 0, 0, 1, kind << 1, 1]; + let mut zeros = 0; + for &byte in rbsp { + if zeros == 2 && byte <= 3 { + out.push(3); + zeros = 0; + } + out.push(byte); + zeros = if byte == 0 { zeros + 1 } else { 0 }; + } + out +} + +/// A raw byte sequence payload, written a field at a time. +#[derive(Default)] +struct Rbsp { + bytes: Vec, + /// The partial byte, its bits filled from the top. + current: u8, + /// How many bits of `current` are filled. + filled: u32, +} + +impl Rbsp { + /// Writes the low `count` bits of `value`, most significant first. + fn bits(&mut self, count: u32, value: u32) { + debug_assert!( + count <= 32 && (count == 32 || value >> count == 0), + "{value} in {count} bits" + ); + for bit in (0..count).rev() { + self.flag(value >> bit & 1 == 1); + } + } + + fn flag(&mut self, bit: bool) { + self.current |= (bit as u8) << (7 - self.filled); + self.filled += 1; + if self.filled == 8 { + self.bytes.push(self.current); + self.current = 0; + self.filled = 0; + } + } + + /// Writes `value` as an unsigned Exp-Golomb code, H.265 9.2. + fn ue(&mut self, value: u32) { + let coded = u64::from(value) + 1; + let length = 64 - coded.leading_zeros(); + self.bits(length - 1, 0); + for bit in (0..length).rev() { + self.flag(coded >> bit & 1 == 1); + } + } + + /// Writes `value` as a signed Exp-Golomb code, H.265 9.2.2. + fn se(&mut self, value: i32) { + let mapped = match value > 0 { + true => 2 * value.unsigned_abs() - 1, + false => 2 * value.unsigned_abs(), + }; + self.ue(mapped); + } + + /// Writes `rbsp_trailing_bits`: a one, then zeros to the byte boundary. + fn trailing(&mut self) { + self.flag(true); + while self.filled != 0 { + self.flag(false); + } + } + + /// Writes `byte_alignment` at the end of a slice header, which is the same bits. + fn byte_alignment(&mut self) { + self.trailing(); + } + + fn finish(self) -> Vec { + debug_assert_eq!(self.filled, 0, "an RBSP ends on a byte boundary"); + self.bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn written(write: impl FnOnce(&mut Rbsp)) -> Vec { + let mut w = Rbsp::default(); + write(&mut w); + w.trailing(); + w.finish() + } + + #[test] + fn exp_golomb_codes_match_the_spec_table() { + // 9.2: 0 -> 1, 1 -> 010, 2 -> 011, 3 -> 00100, then the stop bit. + assert_eq!(written(|w| w.ue(0)), [0b1100_0000]); + assert_eq!(written(|w| w.ue(1)), [0b0101_0000]); + assert_eq!(written(|w| w.ue(2)), [0b0111_0000]); + assert_eq!(written(|w| w.ue(3)), [0b0010_0100]); + // 9.2.2: k > 0 maps to 2k - 1, k <= 0 to -2k. + assert_eq!(written(|w| w.se(1)), written(|w| w.ue(1))); + assert_eq!(written(|w| w.se(-1)), written(|w| w.ue(2))); + assert_eq!(written(|w| w.se(-26)), written(|w| w.ue(52))); + assert_eq!(written(|w| w.ue(u32::MAX - 1)).len(), 8, "63 bits and the stop bit"); + assert_eq!(written(|w| w.ue(u32::MAX)).len(), 9, "65 bits and the stop bit"); + } + + /// 7.4.2: two zeros then a byte below 4 take an emulation prevention byte, + /// and the zeros count again from the byte after it. + #[test] + fn start_code_patterns_are_escaped() { + assert_eq!( + nal(PPS, &[0, 0, 1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0]), + [0, 0, 0, 1, 0x44, 1, 0, 0, 3, 1, 0, 0, 3, 0, 0, 4, 0, 0, 3, 0, 0, 3, 0] + ); + } + + #[test] + fn the_level_covers_the_picture_size_and_sample_rate() { + assert_eq!(level((640, 360), 30), Some(63)); + assert_eq!(level((1280, 720), 30), Some(93)); + assert_eq!(level((1920, 1080), 30), Some(120)); + assert_eq!(level((1920, 1080), 60), Some(123)); + assert_eq!(level((3840, 2160), 30), Some(150)); + assert_eq!(level((3840, 2160), 60), Some(153)); + // A sliver within level 3's area but longer than its widest side, and level 3.1's. + assert_eq!(level((4096, 64), 30), Some(120)); + assert_eq!(level((16384, 16384), 30), None); + } + + /// The coded size rounds up to whole minimum coding blocks, and the SPS crops it back. + #[test] + fn the_coded_size_is_whole_coding_blocks() { + let config = Config::new(852, 478, 30, 1_000_000, 30); + let stream = Stream::with_tools(Tools::FALLBACK, (1, 1), &config).unwrap(); + assert_eq!(stream.coded(), (864, 480)); + let tools = Tools { + log2_min_cb: 3, + ..Tools::FALLBACK + }; + assert_eq!(Stream::with_tools(tools, (1, 1), &config).unwrap().coded(), (856, 480)); + // radeonsi's 64 by 16 surface alignment. + assert_eq!( + Stream::with_tools(tools, (64, 16), &config).unwrap().coded(), + (896, 480) + ); + } +} diff --git a/rs/moq-vaapi/src/generic_value.rs b/rs/moq-vaapi/src/generic_value.rs new file mode 100644 index 00000000000..18db23ba6e6 --- /dev/null +++ b/rs/moq-vaapi/src/generic_value.rs @@ -0,0 +1,42 @@ +// 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/rs/moq-vaapi/src/image.rs b/rs/moq-vaapi/src/image.rs new file mode 100644 index 00000000000..3e1f1aec81c --- /dev/null +++ b/rs/moq-vaapi/src/image.rs @@ -0,0 +1,230 @@ +// 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::sync::Arc; + +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: Arc, + /// 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::va().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: Arc::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::va().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::va().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, VaError> { + // 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::va().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::va().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::va().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::va().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::va().vaUnmapBuffer(self.display.handle(), self.image.buf); + // Safe since `self.image` represents a valid `VAImage`. + bindings::va().vaDestroyImage(self.display.handle(), self.image.image_id); + } + } +} diff --git a/rs/moq-vaapi/src/lib.rs b/rs/moq-vaapi/src/lib.rs new file mode 100644 index 00000000000..e41a4937b2f --- /dev/null +++ b/rs/moq-vaapi/src/lib.rs @@ -0,0 +1,130 @@ +// 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. + +//! 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. + +#![allow( + dead_code, + unused_imports, + unexpected_cfgs, + mismatched_lifetime_syntaxes, + clippy::all, + reason = "vendored from discord/cros-libva and discord/cros-codecs; kept close to upstream so fixes port cleanly" +)] + +mod bindings; +pub mod buffer; +mod config; +mod context; +mod display; +mod generic_value; +mod image; +mod picture; +mod pool; +mod surface; +mod usage_hint; + +// Vendored from discord/cros-codecs (BSD-3-Clause): the backend-agnostic H.264 +// bitstream layer (SPS/PPS/slice synthesis) plus a thin VA-API encode driver. +pub mod bitstream_utils; +pub mod codec; +pub mod decode; +pub mod encode; + +// Written for this crate: DMA-BUF import, the color space an encoder labels its +// stream with, and the VA-API video post-processing entrypoint, which scales, +// converts, and re-tiles surfaces on the GPU. +pub mod color; +pub mod dmabuf; +pub mod vpp; + +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 codec::Codec; +pub use color::{Color, Matrix}; +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::*; + +/// A frame resolution in pixels. (Vendored from discord/cros-codecs, BSD-3-Clause.) +#[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 + } + + 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) + } +} + +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::va().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) })), + } +} diff --git a/rs/moq-vaapi/src/picture.rs b/rs/moq-vaapi/src/picture.rs new file mode 100644 index 00000000000..5b2e17eee02 --- /dev/null +++ b/rs/moq-vaapi/src/picture.rs @@ -0,0 +1,300 @@ +// 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::va().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::va().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::va().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, VaError> + 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, VaError> + 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/rs/moq-vaapi/src/pool.rs b/rs/moq-vaapi/src/pool.rs new file mode 100644 index 00000000000..a9bc3ca51b3 --- /dev/null +++ b/rs/moq-vaapi/src/pool.rs @@ -0,0 +1,137 @@ +//! A recycling pool of NV12 surfaces of one size, shared by the decoder's +//! targets and the video processor's outputs. + +use std::cell::Cell; +use std::sync::{Arc, Mutex, Weak}; + +use anyhow::{anyhow, Context as _}; + +use crate::{bindings, Display, Surface, UsageHint, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420}; + +/// A recycling pool of NV12 surfaces. +/// +/// Surfaces are allocated on demand and come back when the last reference to +/// one drops, such as an [`ExportedFrame`](crate::decode::ExportedFrame)'s. So +/// a picture a consumer holds is never written over, and one it has let go of +/// is written into again rather than replaced by a fresh allocation. +/// +/// The pool keeps at most [`FreeList::capacity`] surfaces free and destroys +/// any returned past that, so a consumer that held many pictures and then let +/// them all go does not leave that many parked here. +pub(crate) struct SurfacePool { + display: Arc, + width: u32, + height: u32, + hint: UsageHint, + /// Shared with every surface on loan, which puts itself back from whichever + /// thread drops it last. + pub(crate) free: Arc, + /// Surfaces allocated over the pool's life. + pub(crate) allocated: Cell, +} + +/// The surfaces a [`SurfacePool`] has free to write into. +pub(crate) struct FreeList { + pub(crate) surfaces: Mutex>>, + /// The most surfaces kept; one returned past this is destroyed. + pub(crate) capacity: usize, +} + +impl SurfacePool { + /// Returns an empty pool of `width` by `height` surfaces allocated with `hint`, keeping at most `capacity` free. + pub(crate) fn new(display: &Arc, (width, height): (u32, u32), hint: UsageHint, capacity: usize) -> Self { + Self { + display: Arc::clone(display), + width, + height, + hint, + free: Arc::new(FreeList { + surfaces: Mutex::new(Vec::new()), + capacity, + }), + allocated: Cell::new(0), + } + } + + /// Returns a free surface, or allocates one when none is. + pub(crate) fn alloc(&self) -> anyhow::Result { + let recycled = self.free.surfaces.lock().expect("poisoned").pop(); + let surface = match recycled { + Some(surface) => surface, + None => { + let surface = self + .display + .create_surfaces::<()>( + VA_RT_FORMAT_YUV420, + Some(VA_FOURCC_NV12), + self.width, + self.height, + Some(self.hint), + vec![()], + ) + .map_err(|e| anyhow!("create a {}x{} surface: {e:?}", self.width, self.height))? + .pop() + .context("VA-API returned an empty surface list")?; + self.allocated.set(self.allocated.get() + 1); + tracing::debug!( + "allocated surface {} at {}x{}", + self.allocated.get(), + self.width, + self.height + ); + surface + } + }; + + Ok(PooledSurface { + surface: Some(surface), + free: Arc::downgrade(&self.free), + }) + } +} + +/// A surface on loan from a [`SurfacePool`], returned to it on drop. +/// +/// Shared behind an [`Arc`] by whatever still reads it, such as the decoder's +/// DPB and an [`ExportedFrame`](crate::decode::ExportedFrame), so it goes back +/// only once none refers to it. The pool is held weakly: a surface that +/// outlives its pool is destroyed rather than kept for a size nobody asks for +/// any more. +pub(crate) struct PooledSurface { + /// Always `Some` until dropped; the `Option` is only there so [`Drop`] can + /// move the surface back into the pool. + surface: Option>, + /// Where to return the surface. Empty for a surface that came from + /// somewhere other than a pool, which is destroyed on drop. + free: Weak, +} + +impl PooledSurface { + /// Wraps a surface that belongs to no pool. + pub(crate) fn unpooled(surface: Surface<()>) -> Self { + Self { + surface: Some(surface), + free: Weak::new(), + } + } + + pub(crate) fn get(&self) -> &Surface<()> { + self.surface.as_ref().expect("surface is taken only on drop") + } + + pub(crate) fn id(&self) -> bindings::VASurfaceID { + self.get().id() + } +} + +impl Drop for PooledSurface { + fn drop(&mut self) { + let (Some(surface), Some(free)) = (self.surface.take(), self.free.upgrade()) else { + return; + }; + let mut surfaces = free.surfaces.lock().expect("poisoned"); + if surfaces.len() < free.capacity { + surfaces.push(surface); + } + } +} diff --git a/rs/moq-vaapi/src/surface.rs b/rs/moq-vaapi/src/surface.rs new file mode 100644 index 00000000000..36c62730a33 --- /dev/null +++ b/rs/moq-vaapi/src/surface.rs @@ -0,0 +1,441 @@ +// 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::sync::Arc; + +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, + 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: Arc, + 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: Arc, + 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::va().vaCreateSurfaces( + display.handle(), + rt_format, + width, + height, + &mut surface_id, + 1, + attrs.as_mut_ptr(), + attrs.len() as u32, + ) + }) { + Ok(()) => surfaces.push(Self { + display: Arc::clone(&display), + id: surface_id, + descriptor, + width, + height, + }), + Err(e) => return Err(e), + } + } + + Ok(surfaces) + } + + pub fn display(&self) -> &Arc { + &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::va().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::va().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::va().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, + bindings::VADecodeErrorType::VADecodeReset => DecodeErrorType::Reset, + _ => { + tracing::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::va().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::va().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/rs/moq-vaapi/src/usage_hint.rs b/rs/moq-vaapi/src/usage_hint.rs new file mode 100644 index 00000000000..026dc87f354 --- /dev/null +++ b/rs/moq-vaapi/src/usage_hint.rs @@ -0,0 +1,26 @@ +// 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 bitflags::bitflags; + +use crate::bindings; + +bitflags! { + /// Gives the driver a hint of intended usage to optimize allocation (e.g. tiling). + #[derive(Debug, Clone, Copy)] + pub struct UsageHint: u32 { + /// Surface used by video decoder. + const USAGE_HINT_DECODER = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER; + /// Surface used by video encoder. + const USAGE_HINT_ENCODER = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER; + /// Surface read by video post-processing. + const USAGE_HINT_VPP_READ = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_VPP_READ; + /// Surface written by video post-processing. + const USAGE_HINT_VPP_WRITE = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_VPP_WRITE; + /// Surface used for display. + const USAGE_HINT_DISPLAY = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_DISPLAY; + /// Surface used for export to third-party APIs, e.g. via `vaExportSurfaceHandle()`. + const USAGE_HINT_EXPORT = bindings::VA_SURFACE_ATTRIB_USAGE_HINT_EXPORT; + } +} diff --git a/rs/moq-vaapi/src/vpp.rs b/rs/moq-vaapi/src/vpp.rs new file mode 100644 index 00000000000..587f92280e2 --- /dev/null +++ b/rs/moq-vaapi/src/vpp.rs @@ -0,0 +1,602 @@ +//! Video post-processing: the `VAEntrypointVideoProc` pipeline. +//! +//! The one operation is a blit from one surface into another, which the video +//! processor stretches to fit the destination and converts to the destination's +//! format on the way. That covers three jobs without the pixels leaving the GPU: +//! +//! - Scaling: blit into a smaller or larger surface. [`Processor::resize`] +//! blits into NV12 surfaces it recycles per size and exports the result. +//! - Color conversion: blit a packed RGB or YUYV surface into an NV12 one, the +//! format an encoder takes. [`Processor::blit`] takes the YUV space to write. +//! - Re-tiling: blit into a surface of the same size and format. The destination +//! is one the driver allocated for itself, so the blit rewrites the pixels +//! into whatever tiling the driver prefers for a fresh allocation. That is how +//! a DMA-BUF carrying a format modifier some other API refuses to import +//! becomes one it accepts. Measured on Intel Meteor Lake with iHD 26.1.5 (the +//! `retile_round_trip` test prints it), a decode target exports at +//! `0x100000000000009` (`I915_FORMAT_MOD_4_TILED`), which Mesa's Vulkan driver +//! lists, so that combination does not need it. Older iHD releases wrote +//! `Y_TILED` (`0x100000000000002`), which Mesa does not list. +//! +//! ```no_run +//! # fn example(buffer: moq_vaapi::dmabuf::DmaBuf) -> anyhow::Result<()> { +//! use moq_vaapi::vpp::Processor; +//! +//! let processor = Processor::new("/dev/dri/renderD128")?; +//! let retiled = processor.retile(buffer)?; +//! let exported = retiled.export_prime().map_err(|e| anyhow::anyhow!("export: {e:?}"))?; +//! # let _ = exported; +//! # Ok(()) +//! # } +//! ``` + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::Path; +use std::rc::Rc; +use std::sync::Arc; + +use crate::decode::ExportedFrame; +use crate::dmabuf::{rt_format, DmaBuf}; +use crate::pool::SurfacePool; +use crate::{ + bindings, BufferType, Color, Config as VaConfig, Context, Display, Picture, ProcColorProperties, + ProcPipelineParameterBuffer, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType, + VAEntrypoint, VAProfile, +}; + +/// ITU-T H.273 code points for an explicitly described side of a blit. +const PRIMARIES_BT709: u8 = 1; +const TRANSFER_BT709: u8 = 1; +const MATRIX_UNSPECIFIED: u8 = 2; + +/// Checks that `display`'s driver offers video post-processing, which is what [`Processor::with_display`] needs of a render node. +/// +/// # Errors +/// +/// Fails when the driver has no `VAEntrypointVideoProc`, or cannot be asked. +pub fn probe(display: &Display) -> anyhow::Result<()> { + let entrypoints = display + .query_config_entrypoints(VAProfile::VAProfileNone) + .map_err(|e| anyhow::anyhow!("query video processing entrypoints: {e:?}"))?; + match entrypoints.contains(&VAEntrypoint::VAEntrypointVideoProc) { + true => Ok(()), + false => anyhow::bail!("the driver has no video post-processing entrypoint"), + } +} + +/// A video post-processor on one device. +/// +/// Holds the display, the VPP configuration, and per destination size a +/// processing context and the surfaces [`resize`](Self::resize) writes into, +/// which are what cost something to build. A caller converting every frame of +/// a stream, or of a few renditions, pays for each once. +pub struct Processor { + display: Arc, + /// How the driver reads a named color space; see [`Colors`]. + colors: Colors, + /// The NV12 surfaces [`resize`](Self::resize) writes into, recycled per size. + outputs: RefCell>, + // Drop order: the contexts before the config they were created from. + contexts: RefCell>>, + config: VaConfig, +} + +impl Processor { + /// Opens `device` and configures it for video post-processing. + /// + /// `device` is a DRM render node, e.g. `/dev/dri/renderD128`. Pick the one + /// matching the device that will consume the result: the blit only stays on + /// the GPU when both ends are the same device. + pub fn new>(device: P) -> anyhow::Result { + let device = device.as_ref(); + let display = + Display::open_drm_display(device).map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e}"))?; + Self::with_display(display) + } + + /// Opens the first device whose driver can post-process, if any. + /// + /// Mirrors [`Display::open`], and is what a caller with no opinion about + /// which GPU should use. A machine with more than one wants + /// [`Processor::new`] or [`Processor::with_display`] instead. + pub fn open() -> anyhow::Result { + let (_, display) = + crate::display::open_first(probe).map_err(|e| e.context("find a render node that post-processes video"))?; + Self::with_display(display) + } + + /// Configures an already open display for video post-processing. + /// + /// Sharing the display with a decoder or an encoder is what lets a surface + /// move between them: a surface belongs to the display that created it. + /// + /// # Errors + /// + /// Fails when the device has no `VAEntrypointVideoProc`, which is how a + /// caller finds out before the first frame rather than during it. + pub fn with_display(display: Arc) -> anyhow::Result { + // Asking for the attribute is the probe: a device without the VPP + // entrypoint fails here instead of at vaCreateConfig, with an error that + // says which entrypoint was missing. + let mut attrs = [VAConfigAttrib { + type_: VAConfigAttribType::VAConfigAttribRTFormat, + value: 0, + }]; + display + .get_config_attributes( + VAProfile::VAProfileNone, + VAEntrypoint::VAEntrypointVideoProc, + &mut attrs, + ) + .map_err(|e| anyhow::anyhow!("query VPP config attributes: {e:?}"))?; + + let config = display + .create_config( + attrs.to_vec(), + VAProfile::VAProfileNone, + VAEntrypoint::VAEntrypointVideoProc, + ) + .map_err(|e| anyhow::anyhow!("create VPP config: {e:?}"))?; + + // Mesa's VA frontend serves every Gallium driver, radeonsi included. + let colors = match display.query_vendor_string() { + Ok(vendor) if vendor.starts_with("Mesa Gallium driver") => Colors::Explicit, + _ => Colors::Standard, + }; + Ok(Self { + display, + colors, + outputs: RefCell::new(HashMap::new()), + contexts: RefCell::new(HashMap::new()), + config, + }) + } + + /// Returns the display this processor runs on, to share with a decoder or an encoder. + pub fn display(&self) -> &Arc { + &self.display + } + + /// Imports an exported DMA-BUF as a surface on this processor's display, without copying it. + /// + /// The returned surface owns `buffer`, so the descriptor stays open exactly + /// as long as the surface referring to it. + /// + /// # Errors + /// + /// See [`DmaBuf::import`]. + pub fn import(&self, buffer: DmaBuf) -> anyhow::Result> { + buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ)) + } + + /// Blits `input` into `output`, scaling to the size of `output` and converting to its format. + /// + /// `input_color` and `output_color` name the YUV space on each side. Leave + /// the input side `None` for an RGB input, which has no matrix; set the + /// output side to the space a YUV destination should be written in. A side + /// left `None` is up to the driver, which is right for a blit that only + /// re-tiles, and for a scale that names neither side. Returns once the + /// destination holds the result. + /// + /// # Errors + /// + /// Fails when either surface belongs to another display, and when the + /// driver refuses the blit (a format pair or scale it cannot do). + pub fn blit( + &self, + input: &Surface, + output: &Surface, + input_color: Option, + output_color: Option, + ) -> anyhow::Result<()> + where + D: SurfaceMemoryDescriptor, + E: SurfaceMemoryDescriptor, + { + // A surface id means something only on the display that made it, and + // the driver would read another display's id as one of its own. + if !Arc::ptr_eq(input.display(), &self.display) || !Arc::ptr_eq(output.display(), &self.display) { + anyhow::bail!("a VPP blit between surfaces of another display"); + } + let size = output.size(); + let context = self.context(size)?; + let parameters = pipeline(input.id(), self.colors, input_color, output_color); + let result = run_blit(&context, output, parameters); + if result.is_err() { + // A picture that failed half way can leave the context mid-picture, + // so the next blit of this size starts on a fresh one. + self.contexts.borrow_mut().remove(&size); + } + result + } + + /// Scales `input` to `width` by `height` and converts it to NV12, returning the result exported. + /// + /// The output comes from a pool per size, so a stream of frames costs no + /// allocation per frame: once the returned frame drops, its surface is the + /// next one written at that size. A frame still held is never written over; + /// the next resize allocates another surface instead. At most one free + /// surface is kept per size, and any returned past that is destroyed. See + /// [`blit`](Self::blit) for the colors. + /// + /// The frame's timestamp is zero, for the caller to set. + /// + /// # Errors + /// + /// Fails when the destination cannot be allocated or exported, and as + /// [`blit`](Self::blit) does. + pub fn resize( + &self, + input: &Surface, + size: (u32, u32), + input_color: Option, + output_color: Option, + ) -> anyhow::Result { + let output = self + .outputs + .borrow_mut() + .entry(size) + .or_insert_with(|| { + let hint = UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT; + SurfacePool::new(&self.display, size, hint, 1) + }) + .alloc()?; + self.blit(input, output.get(), input_color, output_color)?; + ExportedFrame::export(Arc::new(output), 0, size) + } + + /// Blits `input` into a new driver-allocated surface of `fourcc`, `width` and `height`. + /// + /// The destination is hinted as post-processing output that will be + /// exported, so [`Surface::export_prime`] works on it. See + /// [`blit`](Self::blit) for the colors. + /// + /// # Errors + /// + /// Fails for a format with no render target mapping, when the destination + /// cannot be allocated, and as [`blit`](Self::blit) does. + fn process( + &self, + input: &Surface, + fourcc: u32, + (width, height): (u32, u32), + input_color: Option, + output_color: Option, + ) -> anyhow::Result> { + let rt_format = rt_format(fourcc).ok_or_else(|| anyhow::anyhow!("no RT format for fourcc {fourcc:#x}"))?; + let output = self + .display + .create_surfaces( + rt_format, + Some(fourcc), + width, + height, + Some(UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT), + vec![()], + ) + .map_err(|e| anyhow::anyhow!("allocate a {width}x{height} VPP output surface: {e:?}"))? + .pop() + .ok_or_else(|| anyhow::anyhow!("vaCreateSurfaces returned no surface"))?; + + self.blit(input, &output, input_color, output_color)?; + Ok(output) + } + + /// Imports `buffer` and blits it into a driver-allocated surface of the same format and size. + /// + /// This is the whole re-tile. Export the result with + /// [`Surface::export_prime`] and read the modifier off the object to see what + /// the driver chose. + /// Destroying the returned surface does not invalidate an export taken from + /// it, since the exported descriptor holds its own reference on the + /// underlying buffer. + pub fn retile(&self, buffer: DmaBuf) -> anyhow::Result> { + let fourcc = buffer + .fourcc() + .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?; + let input = self.import(buffer)?; + self.process(&input, fourcc, input.size(), None, None) + } + + /// Returns the processing context for a destination of `size`, building it on first use. + fn context(&self, (width, height): (u32, u32)) -> anyhow::Result> { + let mut contexts = self.contexts.borrow_mut(); + if let Some(context) = contexts.get(&(width, height)) { + return Ok(Rc::clone(context)); + } + // No render targets: a VPP context takes its destination per picture, and + // binding it to one surface would make every other destination a rebuild. + let context = self + .display + .create_context::<()>(&self.config, width, height, None, true) + .map_err(|e| anyhow::anyhow!("create a {width}x{height} VPP context: {e:?}"))?; + contexts.insert((width, height), Rc::clone(&context)); + Ok(context) + } +} + +/// Runs one blit on `context` and waits for it to finish. +fn run_blit( + context: &Rc, + output: &Surface, + parameters: ProcPipelineParameterBuffer, +) -> anyhow::Result<()> { + let buffer = context + .create_buffer(BufferType::ProcPipelineParameter(parameters)) + .map_err(|e| anyhow::anyhow!("create VPP pipeline buffer: {e:?}"))?; + + let mut picture = Picture::new(0, Rc::clone(context), output); + picture.add_buffer(buffer); + picture + .begin() + .map_err(|e| anyhow::anyhow!("vaBeginPicture: {e:?}"))? + .render() + .map_err(|e| anyhow::anyhow!("vaRenderPicture: {e:?}"))? + .end() + .map_err(|e| anyhow::anyhow!("vaEndPicture: {e:?}"))? + .sync() + .map_err(|(e, _)| anyhow::anyhow!("vaSyncSurface: {e:?}"))?; + Ok(()) +} + +/// How a driver's video processor reads a named color space. +/// +/// A [`Color`] is a matrix and a range and nothing more, as every other +/// conversion in the stack is, so a blit has to change those two alone. A +/// named standard asks iHD for exactly that. Mesa takes the BT.601 standard to +/// mean SMPTE 170M primaries and transfer as well, and gamut-maps red and green +/// by up to 10 code values, so it is given each side explicitly with the same +/// primaries and transfer on both. iHD reads an explicit side by its primaries +/// alone, which is why the two cannot share one form. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Colors { + Standard, + Explicit, +} + +/// Returns a pipeline parameter buffer describing a plain blit of `surface`. +/// +/// No regions (so the whole input stretched over the whole output), no +/// filters, no references, no rotation or mirroring, and each side's color +/// space and range as given, in the form `colors` names. A side left `None` is +/// the driver's default for its format. +fn pipeline( + surface: bindings::VASurfaceID, + colors: Colors, + input_color: Option, + output_color: Option, +) -> ProcPipelineParameterBuffer { + let named = input_color.is_some() || output_color.is_some(); + let side = |color: Option| match (colors, color) { + (Colors::Explicit, _) if named => { + let (range, matrix) = color.map_or((0, MATRIX_UNSPECIFIED), |color| (color.va_range(), color.vui().2)); + ( + bindings::_VAProcColorStandardType_VAProcColorStandardExplicit as u8, + ProcColorProperties::new(0, range, PRIMARIES_BT709, TRANSFER_BT709, matrix), + ) + } + (_, Some(color)) => ( + color.va_standard(), + ProcColorProperties::new(0, color.va_range(), 0, 0, 0), + ), + (_, None) => (0, ProcColorProperties::default()), + }; + let (input_standard, input_properties) = side(input_color); + let (output_standard, output_properties) = side(output_color); + ProcPipelineParameterBuffer::new( + surface, + None, + input_standard, + None, + 0, + output_standard, + 0, + 0, + None, + None, + None, + 0, + None, + 0, + None, + 0, + 0, + input_properties, + output_properties, + 0, + None, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{VA_FOURCC_NV12, VA_RT_FORMAT_YUV420}; + + /// A driver-allocated NV12 surface survives a round trip through the + /// post-processor, and the modifier the driver picked is printed. + /// + /// Skips without a VA-API device, so it is a no-op on a builder and real + /// coverage on a machine with a GPU. What it asserts is that the whole + /// sequence runs (import an exported DMA-BUF, blit, export the result); the + /// modifier the driver picks is hardware policy, so it is printed rather + /// than asserted. + #[test] + fn retile_round_trip() { + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let Ok(processor) = Processor::with_display(display) else { + eprintln!("skipping: device has no video post-processing entrypoint"); + return; + }; + + // A decode-hinted surface, which is the allocation whose tiling is the + // problem a re-tile exists for. + let mut surfaces = processor + .display() + .create_surfaces( + VA_RT_FORMAT_YUV420, + Some(VA_FOURCC_NV12), + 640, + 480, + Some(UsageHint::USAGE_HINT_DECODER | UsageHint::USAGE_HINT_EXPORT), + vec![()], + ) + .expect("allocate a decode surface"); + let decoded = surfaces.pop().expect("one surface"); + let exported = decoded.export_prime().expect("export the decode surface"); + let source_modifier = exported.objects[0].drm_format_modifier; + let (fourcc, size, planes) = ( + exported.fourcc, + (exported.width, exported.height), + exported.layers[0].num_planes, + ); + let buffer = DmaBuf::from_prime(exported).expect("a composed export is one object"); + + let retiled = processor.retile(buffer).expect("re-tile the decode surface"); + let output = retiled.export_prime().expect("export the re-tiled surface"); + let target_modifier = output.objects[0].drm_format_modifier; + + eprintln!("modifier {source_modifier:#x} -> {target_modifier:#x}"); + assert_eq!(output.fourcc, fourcc, "the blit preserves the pixel format"); + assert_eq!((output.width, output.height), size); + assert_eq!(output.objects.len(), 1, "a composed export is one object"); + assert_eq!( + output.layers[0].num_planes, planes, + "the blit preserves the plane count" + ); + } + /// An NV12 surface whose left half has luma `left` and right half `right`, so a crop and a scale differ. + fn split_surface(processor: &Processor, (width, height): (u32, u32), [left, right]: [u8; 2]) -> Surface<()> { + let source = processor + .display() + .create_surfaces( + VA_RT_FORMAT_YUV420, + Some(VA_FOURCC_NV12), + width, + height, + Some(UsageHint::USAGE_HINT_EXPORT), + vec![()], + ) + .expect("allocate a surface") + .pop() + .expect("one surface"); + let format = processor + .display() + .query_image_formats() + .expect("query image formats") + .into_iter() + .find(|f| f.fourcc == VA_FOURCC_NV12) + .expect("an NV12 image format"); + { + let mut image = + crate::Image::create_from(&source, format, (width, height), (width, height)).expect("create an image"); + let va_image = *image.image(); + let data = image.as_mut(); + for y in 0..height as usize { + let row = va_image.offsets[0] as usize + y * va_image.pitches[0] as usize; + for x in 0..width as usize { + data[row + x] = if x < width as usize / 2 { left } else { right }; + } + } + for y in 0..height as usize / 2 { + let row = va_image.offsets[1] as usize + y * va_image.pitches[1] as usize; + data[row..row + width as usize].fill(128); + } + } + source + } + + /// Reads `frame` back and returns the luma at the middle of its left and right halves. + fn halves(frame: &ExportedFrame) -> [u8; 2] { + let data = frame.download().expect("read the frame back").data; + let (w, h) = (frame.width as usize, frame.height as usize); + assert_eq!(data.len(), w * h * 3 / 2); + [data[h / 2 * w + w / 8], data[h / 2 * w + w * 7 / 8]] + } + + /// Whether every value is within 4 of the expected one. + fn near(actual: [u8; 2], expected: [u8; 2]) -> bool { + actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) < 4) + } + + /// The inode of an exported frame's descriptor, which names the allocation + /// behind it: every DMA-BUF gets its own on the anonymous dma-buf filesystem, + /// while each export of one surface is a new descriptor. + fn inode(frame: &ExportedFrame) -> u64 { + use std::os::unix::fs::MetadataExt as _; + + let fd = frame.descriptor.objects[0] + .fd + .try_clone() + .expect("duplicate the descriptor"); + std::fs::File::from(fd).metadata().expect("stat the descriptor").ino() + } + + /// A surface scaled by the processor exports and reads back at its new + /// size, with the picture scaled rather than cropped. + #[test] + fn a_scaled_surface_reads_back_at_its_new_size() { + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let Ok(processor) = Processor::with_display(display) else { + eprintln!("skipping: device has no video post-processing entrypoint"); + return; + }; + + let source = split_surface(&processor, (640, 480), [40, 200]); + let exported = processor + .resize(&source, (320, 240), None, None) + .expect("scale the surface"); + assert_eq!((exported.width, exported.height), (320, 240)); + assert_eq!(exported.descriptor.fourcc, VA_FOURCC_NV12); + let read = halves(&exported); + assert!(near(read, [40, 200]), "read back {read:?}"); + } + + /// A resize writes into the surface of an output that was let go, never + /// into one still held, and keeps at most one free surface per size. + #[test] + fn a_released_output_is_written_into_again() { + let Some(display) = Display::open() else { + eprintln!("skipping: no VA-API display"); + return; + }; + let Ok(processor) = Processor::with_display(display) else { + eprintln!("skipping: device has no video post-processing entrypoint"); + return; + }; + let dark_left = split_surface(&processor, (640, 480), [40, 200]); + let dark_right = split_surface(&processor, (640, 480), [200, 40]); + let size = (320, 240); + let resize = |source| processor.resize(source, size, None, None).expect("resize"); + + let first = resize(&dark_left); + let released = inode(&first); + drop(first); + let held = resize(&dark_left); + assert_eq!(inode(&held), released, "the released output was not written into again"); + + let other = resize(&dark_right); + assert_ne!(inode(&other), inode(&held), "an output still held was written over"); + let (read, other_read) = (halves(&held), halves(&other)); + assert!(near(read, [40, 200]), "the held output now reads {read:?}"); + assert!(near(other_read, [200, 40]), "the second output reads {other_read:?}"); + + drop(held); + drop(other); + let outputs = processor.outputs.borrow(); + let pool = &outputs[&size]; + assert_eq!(pool.allocated.get(), 2, "two outputs held at once need two surfaces"); + assert_eq!( + pool.free.surfaces.lock().unwrap().len(), + 1, + "one free surface is kept per size, and the other destroyed" + ); + } +} diff --git a/rs/moq-video/DESIGN-native-codecs.md b/rs/moq-video/DESIGN-native-codecs.md index 73545625cdb..eb57806a453 100644 --- a/rs/moq-video/DESIGN-native-codecs.md +++ b/rs/moq-video/DESIGN-native-codecs.md @@ -43,7 +43,7 @@ capture still pulls in `libav*`. This proposal replaces encode **and** capture. |---|---|---|---| | VideoToolbox (macOS, iOS) | [`objc2-video-toolbox`](https://docs.rs/objc2-video-toolbox/) + `objc2-core-media` / `objc2-core-video` | Raw FFI. We hand-write the `VTCompressionSession` glue. | System frameworks, always present. Zero external runtime deps. | | NVENC (NVIDIA) | `moq-nvenc` (in-tree `rs/moq-nvenc`; fork of [`nvidia-video-codec-sdk`](https://crates.io/crates/nvidia-video-codec-sdk) 0.4 trimmed to dlopen-only) | Safe `Encoder` wrapper. | NVENC API lives in the driver (`libnvidia-encode.so`), `dlopen`'d at runtime. No build-time SDK linking. | -| VAAPI (Intel/AMD) | [`moq-vaapi`](https://crates.io/crates/moq-vaapi) `0.0.2` (published; vendored+trimmed from cros-libva + discord/cros-codecs) | VAAPI H.264 encoder (Google/ChromeOS, ships in crosvm). | As of 0.0.2 *links* `libva` (`NEEDED libva.so.2`), build needs libva-dev; `dlopen` (no NEEDED, no build dep) is intended but not yet realized, see #1837. | +| VAAPI (Intel/AMD) | `moq-vaapi` (in-tree `rs/moq-vaapi`; fork of cros-libva + discord/cros-codecs) | VAAPI H.264/H.265 encoder and decoder (Google/ChromeOS, ships in crosvm). | libva `dlopen`'d at runtime, bindings checked in: no libva-dev or libclang at build, no `NEEDED libva.so.2`. | | Software fallback | [`openh264`](https://crates.io/crates/openh264) | Pure fallback when no GPU. | Vendored build -> static, zero runtime deps. | Decisions and rationale: @@ -227,7 +227,7 @@ objc2-core-video = "..." # NVENC rides the default-on `nvidia` feature and VAAPI the default-on `vaapi` # feature. Both dlopen their drivers at runtime, so they link on a GPU-less builder. moq-nvenc = { path = "../moq-nvenc", optional = true } # in-tree fork, dlopen-only -moq-vaapi = { version = "0.0.2", optional = true } # standalone; vendored cros-libva + cros-codecs +moq-vaapi = { path = "../moq-vaapi", optional = true } # in-tree fork of cros-libva + cros-codecs [dependencies] openh264 = { version = "...", optional = true } # default software fallback @@ -262,9 +262,7 @@ A backend "fails to open" (driver missing, no device) the same way an ffmpeg - **Linux**: one binary that - `dlopen`s `libnvidia-encode` if an NVIDIA driver is present (no build dep), - - `dlopen`s `libva` for Intel/AMD (no build dep on libva-dev) - *intended*; - moq-vaapi 0.0.2 currently links libva instead, so this isn't realized yet - (see #1837), + - `dlopen`s `libva` for Intel/AMD (no build dep on libva-dev), - falls back to OpenH264 when its default feature is enabled and no GPU encoder is usable. That single artifact runs across Ubuntu 20.04 -> 24.04, Debian, Fedora, etc., @@ -408,10 +406,9 @@ actively-maintained fork (Discord ships it for Go Live) that bumps to cros-libva links on a libva-less builder and loads on a libva-less machine, falling back to software (see `backend::open`). -> **Status: realized in moq-vaapi 0.0.3** (#1837, bumped in #2465). It dlopens -> libva and vendors the libva headers. Since moq-dev/vaapi#8 it also checks its -> bindings in, so VAAPI costs the build nothing: no libva-dev, no libclang, no -> `NEEDED libva.so.2`, no entry in the nix devShell. +moq-vaapi dlopens libva and checks in bindings generated from vendored libva +headers, so VAAPI costs the build nothing: no libva-dev, no libclang, no +`NEEDED libva.so.2`, no entry in the nix devShell. **Input: DMA-BUFs stay on the GPU, CPU frames are uploaded.** A `Surface::DmaBuf` is encoded without a download. An NV12 buffer at the encoder's diff --git a/rs/moq-video/src/encode/backend/vaapi.rs b/rs/moq-video/src/encode/backend/vaapi.rs index c3397cecaa9..d6264939a0c 100644 --- a/rs/moq-video/src/encode/backend/vaapi.rs +++ b/rs/moq-video/src/encode/backend/vaapi.rs @@ -5,7 +5,7 @@ //! with the parameter sets in band, matching avc3 and hev1, and labels the color //! space in the VUI. H.265 is the Main profile. //! -//! As of moq-vaapi 0.0.3 libva is `dlopen`'d at runtime, so a VAAPI-enabled build +//! libva is `dlopen`'d at runtime, so a VAAPI-enabled build //! needs no libva at build time and the binary carries no `NEEDED libva`. A //! libva-less host, or a present-but-unusable VA stack (no render node, no usable //! driver), makes `Encoder::new` return an error; under automatic selection @@ -35,8 +35,9 @@ //! frames, VA-API decodes handed over as DMA-BUFs, and packed RGB buffers at //! and above the encoder's size, decode each stream with openh264, and compare //! pixels. The H.265 case decodes with the VA-API decoder, since there is no -//! software one, and was validated on Intel Arrow Lake (iHD 26.1.2). They skip -//! on a machine without a VA-API device. +//! software one, and was validated on Intel Arrow Lake (iHD 26.1.2). All of them, +//! ignored ones included, pass on an AMD Radeon RX 9070 (radeonsi, Mesa 26.2.5). +//! They skip on a machine without a VA-API device. use std::collections::HashSet; use std::path::Path;