Merge remote-tracking branch 'origin/main' into worktree-agent-a01b6420b0fc19427
Browse files at this commit21 changed files +3732 -84
- Cargo.toml +10 -1
- crates/engine-hw/src/lib.rs +133 -25
- crates/engine/examples/bench.rs +13 -3
- crates/engine/src/caps.rs +7 -6
- crates/engine/src/export.rs +31 -9
- crates/engine/src/hw.rs +26 -0
- crates/engine/src/playback.rs +44 -12
- crates/engine/tests/backends.rs +76 -5
- crates/engine/tests/playback.rs +11 -20
- scripts/bench.sh +1 -1
- vendor/cros-codecs/src/codec/h264/nalu_writer.rs +9 -2
- vendor/cros-codecs/src/codec/h265.rs +2 -0
- vendor/cros-codecs/src/codec/h265/nalu_writer.rs +335 -0
- vendor/cros-codecs/src/codec/h265/parser.rs +659 -0
- vendor/cros-codecs/src/codec/h265/synthesizer.rs +1142 -0
- vendor/cros-codecs/src/encoder.rs +9 -0
- vendor/cros-codecs/src/encoder/h265.rs +4 -0
- vendor/cros-codecs/src/encoder/stateless.rs +2 -0
- vendor/cros-codecs/src/encoder/stateless/h265.rs +205 -0
- vendor/cros-codecs/src/encoder/stateless/h265/predictor.rs +288 -0
- vendor/cros-codecs/src/encoder/stateless/h265/vaapi.rs +725 -0
Cargo.tomlmodified+10 -1
| @@ -25,7 +25,16 @@ edition = "2024" | ||
| 25 | 25 | # declared one, which fails every seek into an open-GOP Blu-ray |
| 26 | 26 | # remux -- the gap is the *editor's*, made by restarting at a |
| 27 | 27 | # random access point, so the patch fills it with the §8.2.5.2 |
| 28 | -# non-existing frames the loop right below it already builds | |
| 28 | +# non-existing frames the loop right below it already builds. | |
| 29 | +# It also has no HEVC *encoder* at all in 0.0.6: the seven | |
| 30 | +# commits behind cros-codecs' own `hevc-vaapi-encoder` branch | |
| 31 | +# (`codec/h265/{nalu_writer,synthesizer}`, the VPS/SPS/PPS | |
| 32 | +# builders in `codec/h265/parser.rs`, `encoder/stateless/h265` | |
| 33 | +# with its predictor and VA-API backend, and the H.264 NALU | |
| 34 | +# writer's emulation-prevention fix that shares that code) are | |
| 35 | +# applied here verbatim -- upstream work carried early, not a | |
| 36 | +# local invention, and the H.265 half of what makes edith's | |
| 37 | +# HEVC export run on the GPU | |
| 29 | 38 | # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per |
| 30 | 39 | # term (the fast path in the same file serves the encoder only), |
| 31 | 40 | # which is 4x slower than real time for 5.1 and therefore not |
crates/engine-hw/src/lib.rsmodified+133 -25
| @@ -1,5 +1,5 @@ | ||
| 1 | -//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264, and AV1 where | |
| 2 | -//! the GPU has an entrypoint for it), shipped as a | |
| 1 | +//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV1 | |
| 2 | +//! where the GPU has an entrypoint for it), shipped as a | |
| 3 | 3 | //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on |
| 4 | 4 | //! libva/gbm/drm. Every entry point is |
| 5 | 5 | //! `extern "C"`, catches unwinds and reports failure as a null pointer or a |
| @@ -20,6 +20,7 @@ use cros_codecs::backend::vaapi::decoder::VaapiBackend; | ||
| 20 | 20 | use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend; |
| 21 | 21 | use cros_codecs::codec::av1::parser::Profile as Av1Profile; |
| 22 | 22 | use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile}; |
| 23 | +use cros_codecs::codec::h265::parser::{Level as H265Level, Profile as H265Profile}; | |
| 23 | 24 | use cros_codecs::decoder::stateless::av1::Av1; |
| 24 | 25 | use cros_codecs::decoder::stateless::h264::H264; |
| 25 | 26 | use cros_codecs::decoder::stateless::h265::H265; |
| @@ -28,8 +29,10 @@ use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVi | ||
| 28 | 29 | use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; |
| 29 | 30 | use cros_codecs::encoder::av1::EncoderConfig as Av1Config; |
| 30 | 31 | use cros_codecs::encoder::h264::EncoderConfig as H264Config; |
| 32 | +use cros_codecs::encoder::h265::EncoderConfig as H265Config; | |
| 31 | 33 | use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder; |
| 32 | 34 | use cros_codecs::encoder::stateless::h264::StatelessEncoder; |
| 35 | +use cros_codecs::encoder::stateless::h265::StatelessEncoder as H265StatelessEncoder; | |
| 33 | 36 | use cros_codecs::encoder::{ |
| 34 | 37 | FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder, |
| 35 | 38 | }; |
| @@ -98,6 +101,10 @@ type Av1Encoder = Av1StatelessEncoder< | ||
| 98 | 101 | GenericDmaVideoFrame, |
| 99 | 102 | VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>, |
| 100 | 103 | >; |
| 104 | +type HevcEncoder = H265StatelessEncoder< | |
| 105 | + GenericDmaVideoFrame, | |
| 106 | + VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>, | |
| 107 | +>; | |
| 101 | 108 | |
| 102 | 109 | /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking |
| 103 | 110 | /// mode should always either hand back an event or accept input; this only |
| @@ -608,8 +615,8 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) { | ||
| 608 | 615 | |
| 609 | 616 | /// What each codec needs of the driver before this plugin can claim it: the |
| 610 | 617 | /// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here |
| 611 | -/// would open -- `None` for the two this plugin has no encoder for at all, so a | |
| 612 | -/// GPU with an HEVC or VP9 encode entrypoint is never reported as one edith can | |
| 618 | +/// would open -- `None` for the one this plugin has no encoder for at all, so a | |
| 619 | +/// GPU with a VP9 encode entrypoint is never reported as one edith can | |
| 613 | 620 | /// reach. The encode profiles are the very ones [`EncSession::open_codec`] |
| 614 | 621 | /// asks for, which is what keeps this a description of the plugin rather than a |
| 615 | 622 | /// second opinion about it. |
| @@ -628,7 +635,11 @@ const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile | ||
| 628 | 635 | CAP_HEVC, |
| 629 | 636 | &[VAProfile::VAProfileHEVCMain], |
| 630 | 637 | &[VAProfile::VAProfileHEVCMain10], |
| 631 | - None, | |
| 638 | + // 8-bit Main only: the encoder here opens Main whatever the source was, | |
| 639 | + // so a Main 10 entrypoint is a *decode* claim on this line and nothing | |
| 640 | + // more. Main 10 encode would be a second profile here and a 10-bit input | |
| 641 | + // buffer in `EncSession`, neither of which exists yet. | |
| 642 | + Some(VAProfile::VAProfileHEVCMain), | |
| 632 | 643 | ), |
| 633 | 644 | ( |
| 634 | 645 | CAP_VP9, |
| @@ -762,13 +773,15 @@ fn fix_slice_nal_headers(au: &mut [u8]) { | ||
| 762 | 773 | /// point polls it before returning, so the GPU is finished with the buffer |
| 763 | 774 | /// before the next picture is written into it. |
| 764 | 775 | struct EncSession { |
| 765 | - /// Boxed because the two codecs are two types and everything past `encode` | |
| 766 | - /// is the same trait: one session type serves both, which is what keeps the | |
| 767 | - /// C ABI at one new symbol (the open) instead of four. | |
| 776 | + /// Boxed because the three codecs are three types and everything past | |
| 777 | + /// `encode` is the same trait: one session type serves them all, which is | |
| 778 | + /// what keeps the C ABI at one new symbol per codec (the open) instead of | |
| 779 | + /// four. | |
| 768 | 780 | encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>>, |
| 769 | - /// H.264 only: the byte the driver leaves at zero is a *NAL* header, and an | |
| 770 | - /// AV1 temporal unit has no such thing. | |
| 771 | - h264: bool, | |
| 781 | + /// Which codec the open picked, kept because one thing past it still | |
| 782 | + /// differs: the H.264 driver leaves a *NAL* header byte at zero, and | |
| 783 | + /// neither an HEVC access unit nor an AV1 temporal unit has that one. | |
| 784 | + codec: EncCodec, | |
| 772 | 785 | /// Owns the DRM node the buffer object below was allocated from. |
| 773 | 786 | _gbm: gbm::Device<std::fs::File>, |
| 774 | 787 | frame: GenericDmaVideoFrame, |
| @@ -786,9 +799,18 @@ struct EncSession { | ||
| 786 | 799 | out: Vec<u8>, |
| 787 | 800 | } |
| 788 | 801 | |
| 802 | +/// Which codec an [`EncSession`] was opened for. Decided once, at the open, the | |
| 803 | +/// way the H.264 seat's dimensions are -- everything after it is one trait. | |
| 804 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 805 | +enum EncCodec { | |
| 806 | + H264, | |
| 807 | + Hevc, | |
| 808 | + Av1, | |
| 809 | +} | |
| 810 | + | |
| 789 | 811 | impl EncSession { |
| 790 | 812 | fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> { |
| 791 | - Self::open_codec(width, height, fps_num, fps_den, bitrate, false) | |
| 813 | + Self::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::H264) | |
| 792 | 814 | } |
| 793 | 815 | |
| 794 | 816 | fn open_codec( |
| @@ -797,13 +819,21 @@ impl EncSession { | ||
| 797 | 819 | fps_num: u32, |
| 798 | 820 | fps_den: u32, |
| 799 | 821 | bitrate: u64, |
| 800 | - av1: bool, | |
| 822 | + codec: EncCodec, | |
| 801 | 823 | ) -> Option<Self> { |
| 802 | 824 | // NV12 chroma is half resolution, so odd dimensions have no packing; |
| 803 | 825 | // and radeonsi refuses encode contexts below 64x64 (measured). |
| 804 | 826 | if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 { |
| 805 | 827 | return None; |
| 806 | 828 | } |
| 829 | + // The HEVC entrypoint's own floor, which is a different number: the same | |
| 830 | + // driver that takes a 128x128 H.264 context answers `VaError(19)` to an | |
| 831 | + // HEVC one below 384x384 (measured 2026-08-13 on radeonsi). Said here so | |
| 832 | + // a small export falls back to software at the open rather than through | |
| 833 | + // a driver refusal, and so the C ABI never claims a seat it has not got. | |
| 834 | + if codec == EncCodec::Hevc && (width < 384 || height < 384) { | |
| 835 | + return None; | |
| 836 | + } | |
| 807 | 837 | if fps_num == 0 || fps_den == 0 || bitrate == 0 { |
| 808 | 838 | return None; |
| 809 | 839 | } |
| @@ -813,9 +843,10 @@ impl EncSession { | ||
| 813 | 843 | height: align16(height), |
| 814 | 844 | }; |
| 815 | 845 | let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32; |
| 816 | - let profile = match av1 { | |
| 817 | - true => VAProfile::VAProfileAV1Profile0, | |
| 818 | - false => VAProfile::VAProfileH264Main, | |
| 846 | + let profile = match codec { | |
| 847 | + EncCodec::Av1 => VAProfile::VAProfileAV1Profile0, | |
| 848 | + EncCodec::Hevc => VAProfile::VAProfileHEVCMain, | |
| 849 | + EncCodec::H264 => VAProfile::VAProfileH264Main, | |
| 819 | 850 | }; |
| 820 | 851 | // The driver's own answer to "can you encode this at all": a GPU with no |
| 821 | 852 | // AV1 encode entrypoint is what makes the caller fall back to `rav1e`, |
| @@ -833,8 +864,8 @@ impl EncSession { | ||
| 833 | 864 | let pred_structure = PredictionStructure::LowDelay { |
| 834 | 865 | limit: (framerate * 2) as u16, |
| 835 | 866 | }; |
| 836 | - let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match av1 { | |
| 837 | - true => { | |
| 867 | + let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match codec { | |
| 868 | + EncCodec::Av1 => { | |
| 838 | 869 | // Constant quality, because that is the only rate control the |
| 839 | 870 | // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses |
| 840 | 871 | // anything else outright); 128 of 255 is its own reference |
| @@ -867,7 +898,50 @@ impl EncSession { | ||
| 867 | 898 | .ok()?, |
| 868 | 899 | ) |
| 869 | 900 | } |
| 870 | - false => { | |
| 901 | + EncCodec::Hevc => { | |
| 902 | + // **Every picture an IDR**, which is the one place this seat | |
| 903 | + // does not mirror the H.264 one. A GOP's P slices come out of | |
| 904 | + // this driver undecodable: the slice segment headers are the | |
| 905 | + // *driver's* to write (as they are for H.264) and radeonsi | |
| 906 | + // writes a constant picture order count into every one of them, | |
| 907 | + // so a decoder sees frame after frame claiming to be the same | |
| 908 | + // output picture. Measured 2026-08-13: with the default GOP, | |
| 909 | + // only the leading IDR of each group decodes. | |
| 910 | + // | |
| 911 | + // So the hardware seat is intra-only exactly as the software one | |
| 912 | + // is (`export::Enc::open_hevc`), and an HEVC export is an | |
| 913 | + // intraframe master either way -- the same file, coded by the | |
| 914 | + // GPU instead of by twelve cores. | |
| 915 | + // | |
| 916 | + // corner-cut: inter HEVC on this GPU needs the slice segment | |
| 917 | + // header written here rather than by the driver | |
| 918 | + // (`VAEncPackedHeaderSlice`), which is a change in the vendored | |
| 919 | + // backend; upgrade path is that, or a driver that writes a | |
| 920 | + // correct POC. | |
| 921 | + let config = H265Config { | |
| 922 | + resolution: Resolution { width, height }, | |
| 923 | + profile: H265Profile::Main, | |
| 924 | + level: H265Level::L4, | |
| 925 | + pred_structure: PredictionStructure::LowDelay { limit: 1 }, | |
| 926 | + initial_tunings: Tunings { | |
| 927 | + rate_control: RateControl::ConstantBitrate(bitrate), | |
| 928 | + framerate, | |
| 929 | + ..Default::default() | |
| 930 | + }, | |
| 931 | + }; | |
| 932 | + Box::new( | |
| 933 | + HevcEncoder::new_vaapi( | |
| 934 | + display, | |
| 935 | + config, | |
| 936 | + Fourcc::from(b"NV12"), | |
| 937 | + coded, | |
| 938 | + low_power, | |
| 939 | + BlockingMode::Blocking, | |
| 940 | + ) | |
| 941 | + .ok()?, | |
| 942 | + ) | |
| 943 | + } | |
| 944 | + EncCodec::H264 => { | |
| 871 | 945 | let config = H264Config { |
| 872 | 946 | resolution: Resolution { width, height }, |
| 873 | 947 | profile: H264Profile::Main, |
| @@ -898,7 +972,7 @@ impl EncSession { | ||
| 898 | 972 | let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); |
| 899 | 973 | Some(Self { |
| 900 | 974 | encoder, |
| 901 | - h264: !av1, | |
| 975 | + codec, | |
| 902 | 976 | _gbm: gbm, |
| 903 | 977 | frame, |
| 904 | 978 | layout, |
| @@ -981,7 +1055,7 @@ impl EncSession { | ||
| 981 | 1055 | fn collect(&mut self) -> Result<(), String> { |
| 982 | 1056 | while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { |
| 983 | 1057 | let mut au = coded.bitstream; |
| 984 | - if self.h264 { | |
| 1058 | + if self.codec == EncCodec::H264 { | |
| 985 | 1059 | fix_slice_nal_headers(&mut au); |
| 986 | 1060 | } |
| 987 | 1061 | self.ready.push_back(au); |
| @@ -1044,7 +1118,37 @@ pub extern "C" fn vh_enc_av1_open( | ||
| 1044 | 1118 | bitrate: u64, |
| 1045 | 1119 | ) -> *mut c_void { |
| 1046 | 1120 | catch_unwind(AssertUnwindSafe(|| { |
| 1047 | - match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, true) { | |
| 1121 | + match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Av1) { | |
| 1122 | + Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, | |
| 1123 | + None => std::ptr::null_mut(), | |
| 1124 | + } | |
| 1125 | + })) | |
| 1126 | + .unwrap_or(std::ptr::null_mut()) | |
| 1127 | +} | |
| 1128 | + | |
| 1129 | +/// The same, coding HEVC: null unless this GPU has an HEVC encode entrypoint and | |
| 1130 | +/// the picture is at least 384x384 ([`EncSession::open_codec`] states that floor | |
| 1131 | +/// and where it was measured), and the caller then encodes HEVC in software | |
| 1132 | +/// instead. | |
| 1133 | +/// | |
| 1134 | +/// **Intra-only**: every picture it hands back is an IDR carrying its own VPS, | |
| 1135 | +/// SPS and PPS, which is what makes the file decodable at all on this driver -- | |
| 1136 | +/// see the `EncCodec::Hevc` arm of [`EncSession::open_codec`]. `bitrate` is the | |
| 1137 | +/// constant bitrate the GPU codes at, as the H.264 seat's is. | |
| 1138 | +/// | |
| 1139 | +/// The session it returns is fed, drained and closed through `vh_enc_frame`, | |
| 1140 | +/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back | |
| 1141 | +/// out of them is Annex-B HEVC access units. | |
| 1142 | +#[unsafe(no_mangle)] | |
| 1143 | +pub extern "C" fn vh_enc_hevc_open( | |
| 1144 | + width: u32, | |
| 1145 | + height: u32, | |
| 1146 | + fps_num: u32, | |
| 1147 | + fps_den: u32, | |
| 1148 | + bitrate: u64, | |
| 1149 | +) -> *mut c_void { | |
| 1150 | + catch_unwind(AssertUnwindSafe(|| { | |
| 1151 | + match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Hevc) { | |
| 1048 | 1152 | Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, |
| 1049 | 1153 | None => std::ptr::null_mut(), |
| 1050 | 1154 | } |
| @@ -1160,9 +1264,13 @@ mod tests { | ||
| 1160 | 1264 | return; |
| 1161 | 1265 | }; |
| 1162 | 1266 | eprintln!("{caps:?}"); |
| 1163 | - // Encode is this plugin's two seats and no others, whatever entrypoints | |
| 1164 | - // the driver has: an HEVC or VP9 EncSlice is not an encoder here. | |
| 1165 | - assert_eq!(caps.encode & !(CAP_H264 | CAP_AV1), 0, "{caps:?}"); | |
| 1267 | + // Encode is this plugin's three seats and no others, whatever | |
| 1268 | + // entrypoints the driver has: a VP9 EncSlice is not an encoder here. | |
| 1269 | + assert_eq!( | |
| 1270 | + caps.encode & !(CAP_H264 | CAP_HEVC | CAP_AV1), | |
| 1271 | + 0, | |
| 1272 | + "{caps:?}" | |
| 1273 | + ); | |
| 1166 | 1274 | // A 10-bit claim is a decode claim -- same profile family, read back |
| 1167 | 1275 | // through P010 -- and there is no 10-bit encode path at all. |
| 1168 | 1276 | assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}"); |
crates/engine/examples/bench.rsmodified+13 -3
| @@ -26,7 +26,8 @@ | ||
| 26 | 26 | //! first frame, `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single |
| 27 | 27 | //! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times |
| 28 | 28 | //! an export is repeated *if the cap leaves room* -- a 4K encode gets one |
| 29 | -//! capped rep, the small control gets five. | |
| 29 | +//! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether | |
| 30 | +//! the exported file survives the run instead of being deleted with the number. | |
| 30 | 31 | |
| 31 | 32 | use std::path::{Path, PathBuf}; |
| 32 | 33 | use std::time::{Duration, Instant}; |
| @@ -63,7 +64,7 @@ fn usage() -> ! { | ||
| 63 | 64 | eprintln!( |
| 64 | 65 | "usage: bench open <file>\n bench seek <file> <secs>\n \ |
| 65 | 66 | bench scrub <file>\n bench waveform <file>\n \ |
| 66 | - bench export <file> <h264sw|h264hw|av1|hevc> <out_dir>" | |
| 67 | + bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>" | |
| 67 | 68 | ); |
| 68 | 69 | std::process::exit(2) |
| 69 | 70 | } |
| @@ -356,7 +357,11 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | ||
| 356 | 357 | "h264sw" => (Format::Mp4, true), |
| 357 | 358 | "h264hw" => (Format::Mp4, false), |
| 358 | 359 | "av1" => (Format::Av1, true), |
| 360 | + // `hevc` keeps meaning the software intra seat, so a row measured | |
| 361 | + // against an older baseline still compares with the one beside it; the | |
| 362 | + // GPU seat is the new name. | |
| 359 | 363 | "hevc" => (Format::Hevc, true), |
| 364 | + "hevchw" => (Format::Hevc, false), | |
| 360 | 365 | _ => usage(), |
| 361 | 366 | }; |
| 362 | 367 | let metric = format!("export_fps_{seat}"); |
| @@ -426,7 +431,12 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | ||
| 426 | 431 | } |
| 427 | 432 | let seats = handle.encoders().unwrap_or_else(|| "?".into()); |
| 428 | 433 | let outcome = handle.result(); |
| 429 | - let _ = std::fs::remove_file(&out); | |
| 434 | + // A throughput run leaves nothing behind; `BENCH_KEEP=1` keeps the last | |
| 435 | + // one, which is how a seat is checked for *decodability* rather than | |
| 436 | + // speed (`ffprobe -count_frames` on the file it wrote). | |
| 437 | + if std::env::var_os("BENCH_KEEP").is_none() { | |
| 438 | + let _ = std::fs::remove_file(&out); | |
| 439 | + } | |
| 430 | 440 | if capped { |
| 431 | 441 | samples.push(progress * f64::from(span) / elapsed); |
| 432 | 442 | notes.push(format!("CAPPED at {:.0}s, {:.0}% done, {seats}", elapsed, progress * 100.0)); |
crates/engine/src/caps.rsmodified+7 -6
| @@ -104,18 +104,19 @@ mod tests { | ||
| 104 | 104 | assert!(hw_line(None).starts_with("none —")); |
| 105 | 105 | // A driver that answers with nothing is its own sentence. |
| 106 | 106 | assert!(hw_line(Some(VhCaps::default())).starts_with("none —")); |
| 107 | - // This project's own GPU as `vainfo` lists it: H.264 both ways, HEVC | |
| 108 | - // and VP9 decode with their 10-bit profiles, AV1 both ways. HEVC has a | |
| 109 | - // VA encode entrypoint here and is *not* an encode seat: the plugin has | |
| 110 | - // no HEVC encoder, so the line must not offer one. | |
| 107 | + // This project's own GPU as `vainfo` lists it: H.264, HEVC and AV1 both | |
| 108 | + // ways, VP9 decode only, and the 10-bit profiles on three of the four. | |
| 109 | + // HEVC is an encode seat here as of the plugin's `vh_enc_hevc_open` -- | |
| 110 | + // the 10-bit note beside it stays a *decode* claim, that seat coding | |
| 111 | + // 8-bit Main whatever the source was. | |
| 111 | 112 | let radeonsi = VhCaps { |
| 112 | 113 | decode: CAP_H264 | CAP_HEVC | CAP_VP9 | CAP_AV1, |
| 113 | - encode: CAP_H264 | CAP_AV1, | |
| 114 | + encode: CAP_H264 | CAP_HEVC | CAP_AV1, | |
| 114 | 115 | decode_10bit: CAP_HEVC | CAP_VP9 | CAP_AV1, |
| 115 | 116 | }; |
| 116 | 117 | assert_eq!( |
| 117 | 118 | hw_line(Some(radeonsi)), |
| 118 | - "H.264 dec+enc · HEVC dec (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)" | |
| 119 | + "H.264 dec+enc · HEVC dec+enc (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)" | |
| 119 | 120 | ); |
| 120 | 121 | // A codec the driver has neither seat for is left out rather than |
| 121 | 122 | // listed as a refusal: this line is what the machine *can* do. |
crates/engine/src/export.rsmodified+31 -9
| @@ -496,11 +496,15 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> { | ||
| 496 | 496 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; |
| 497 | 497 | let bitrate = bitrate_of(meta, settings); |
| 498 | 498 | match settings.format { |
| 499 | - // The HEVC pair is software only, and not for want of a GPU: the plugin | |
| 500 | - // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264 | |
| 501 | - // and AV1), so there is no seat to probe. Said here rather than left to | |
| 502 | - // a failed open, which would read as a driver refusal. | |
| 503 | - format if format.is_hevc() => None, | |
| 499 | + // Both HEVC formats sit on the plugin's HEVC seat, and it is the | |
| 500 | + // default: what it codes is intra-only, the very file the software seat | |
| 501 | + // writes, so preferring the GPU changes how long an export takes and | |
| 502 | + // not what comes out of it. `None` here is the plugin's own "no" -- | |
| 503 | + // no entrypoint, or a picture under the driver's 384x384 floor -- and | |
| 504 | + // the software intra encoder takes the file. | |
| 505 | + format if format.is_hevc() => { | |
| 506 | + HwEncoder::open_hevc(meta.width, meta.height, fps_num, fps_den, bitrate) | |
| 507 | + } | |
| 504 | 508 | // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both |
| 505 | 509 | // AV1 formats sit on it: the container is not the encoder's business. |
| 506 | 510 | format if format.is_av1() && !forced("VE_HW_AV1") => None, |
| @@ -2627,6 +2631,9 @@ enum Enc { | ||
| 2627 | 2631 | }, |
| 2628 | 2632 | /// AV1 on the GPU, through the same plugin the H.264 seat uses. |
| 2629 | 2633 | Av1Hw(HwEncoder), |
| 2634 | + /// HEVC on the GPU, through that same plugin -- and intra-only there too, | |
| 2635 | + /// so this and [`Enc::Hevc`] write the same kind of file. | |
| 2636 | + HevcHw(HwEncoder), | |
| 2630 | 2637 | Av1Sw { |
| 2631 | 2638 | context: rav1e::Context<u8>, |
| 2632 | 2639 | /// Temporal units the encoder has finished but the caller has not |
| @@ -2687,6 +2694,7 @@ impl Enc { | ||
| 2687 | 2694 | Self::Sw { .. } => video_label(Format::Mp4, false), |
| 2688 | 2695 | Self::Av1Hw(_) => video_label(Format::Av1, true), |
| 2689 | 2696 | Self::Av1Sw { .. } => video_label(Format::Av1, false), |
| 2697 | + Self::HevcHw(_) => video_label(Format::Hevc, true), | |
| 2690 | 2698 | Self::Hevc(_) => video_label(Format::Hevc, false), |
| 2691 | 2699 | } |
| 2692 | 2700 | } |
| @@ -2810,11 +2818,14 @@ impl Enc { | ||
| 2810 | 2818 | }) |
| 2811 | 2819 | } |
| 2812 | 2820 | |
| 2813 | - /// The intra HEVC seat, software and frame-parallel. There is no hardware | |
| 2814 | - /// half: the plugin encodes H.264 and AV1 and nothing else, which | |
| 2815 | - /// [`hw_seat`] says by refusing to probe one. | |
| 2821 | + /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the | |
| 2822 | + /// frame-parallel software encoder everywhere else -- below the driver's | |
| 2823 | + /// 384x384 floor, on a plugin too old to carry the symbol, on a GPU with no | |
| 2824 | + /// HEVC encode entrypoint. Silent either way, because both write the same | |
| 2825 | + /// kind of file. | |
| 2816 | 2826 | /// |
| 2817 | - /// **Intra-only, deliberately.** The vendored encoder's inter modes code | |
| 2827 | + /// **Intra-only, deliberately, on both seats.** The software encoder's inter | |
| 2828 | + /// modes code | |
| 2818 | 2829 | /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of |
| 2819 | 2830 | /// timeline in half an hour, which is not an export anybody waits for -- |
| 2820 | 2831 | /// while the intra path does 4.30 fps on the same picture and the same |
| @@ -2839,6 +2850,10 @@ impl Enc { | ||
| 2839 | 2850 | ) |
| 2840 | 2851 | .into()); |
| 2841 | 2852 | } |
| 2853 | + if let Some(hw) = hw_seat(meta, settings) { | |
| 2854 | + eprintln!("export encoder: hardware HEVC intra (VA-API plugin)"); | |
| 2855 | + return Ok(Self::HevcHw(hw)); | |
| 2856 | + } | |
| 2842 | 2857 | let (width, height) = ( |
| 2843 | 2858 | (meta.width as usize).next_multiple_of(CTB), |
| 2844 | 2859 | (meta.height as usize).next_multiple_of(CTB), |
| @@ -2900,6 +2915,12 @@ impl Enc { | ||
| 2900 | 2915 | collect_av1(context, ready)?; |
| 2901 | 2916 | Ok(pop_av1(ready, au)) |
| 2902 | 2917 | } |
| 2918 | + // Every unit this seat hands back is an IDR carrying its own | |
| 2919 | + // parameter sets (the plugin codes HEVC intra-only), so every one of | |
| 2920 | + // them is a sync point -- said as a constant rather than parsed back | |
| 2921 | + // out of the bitstream, because it is this encoder's configuration | |
| 2922 | + // and not a driver's choice. | |
| 2923 | + Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))), | |
| 2903 | 2924 | Self::Hevc(hevc) => { |
| 2904 | 2925 | hevc.pending.push(pad_to_ctb( |
| 2905 | 2926 | y, |
| @@ -2956,6 +2977,7 @@ impl Enc { | ||
| 2956 | 2977 | } |
| 2957 | 2978 | Ok(pop_av1(ready, au)) |
| 2958 | 2979 | } |
| 2980 | + Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))), | |
| 2959 | 2981 | Self::Hevc(hevc) => { |
| 2960 | 2982 | // The tail batch: fewer frames than lanes, coded on as many |
| 2961 | 2983 | // cores as there are frames left. |
crates/engine/src/hw.rsmodified+26 -0
| @@ -259,6 +259,9 @@ struct EncPlugin { | ||
| 259 | 259 | /// plugin keeps one session type for both codecs, so the codec is decided |
| 260 | 260 | /// once, at the open, exactly as the H.264 seat's parameters are. |
| 261 | 261 | open_av1: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>, |
| 262 | + /// The HEVC seat, missing from an older plugin for the same reason and at | |
| 263 | + /// the same cost: an HEVC export then runs on the software intra encoder. | |
| 264 | + open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>, | |
| 262 | 265 | frame: |
| 263 | 266 | unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, |
| 264 | 267 | drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, |
| @@ -285,6 +288,7 @@ fn load_enc() -> Option<EncPlugin> { | ||
| 285 | 288 | Some(EncPlugin { |
| 286 | 289 | open: *lib.get(b"vh_enc_open\0").ok()?, |
| 287 | 290 | open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), |
| 291 | + open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), | |
| 288 | 292 | frame: *lib.get(b"vh_enc_frame\0").ok()?, |
| 289 | 293 | drain: *lib.get(b"vh_enc_drain\0").ok()?, |
| 290 | 294 | close: *lib.get(b"vh_enc_close\0").ok()?, |
| @@ -345,6 +349,28 @@ impl HwEncoder { | ||
| 345 | 349 | Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) |
| 346 | 350 | } |
| 347 | 351 | |
| 352 | + /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an | |
| 353 | + /// opt-in: it is the default for an HEVC export, and what makes that safe is | |
| 354 | + /// that the pictures it codes are intra-only, which is the same file the | |
| 355 | + /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the | |
| 356 | + /// GPU-resetting inter path AV1's opt-in exists for. | |
| 357 | + /// | |
| 358 | + /// `None` on everything [`HwEncoder::open`] answers `None` to, on a plugin | |
| 359 | + /// too old to export the symbol, on a GPU with no HEVC encode entrypoint, | |
| 360 | + /// and below 384x384 -- the driver's own floor, stated in the plugin. The | |
| 361 | + /// caller then takes the software intra encoder without a word about it. | |
| 362 | + pub fn open_hevc( | |
| 363 | + width: u32, | |
| 364 | + height: u32, | |
| 365 | + fps_num: u32, | |
| 366 | + fps_den: u32, | |
| 367 | + bitrate: u64, | |
| 368 | + ) -> Option<Self> { | |
| 369 | + let plugin = enc_plugin()?; | |
| 370 | + let open = plugin.open_hevc?; | |
| 371 | + Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) | |
| 372 | + } | |
| 373 | + | |
| 348 | 374 | /// The null check both opens share, which is the plugin's whole way of |
| 349 | 375 | /// saying "no". |
| 350 | 376 | fn opened( |
crates/engine/src/playback.rsmodified+44 -12
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | //! the renderer decides which frame that means. |
| 13 | 13 | |
| 14 | 14 | use std::path::Path; |
| 15 | -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; | |
| 15 | +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; | |
| 16 | 16 | use std::sync::mpsc::{Receiver, TryRecvError}; |
| 17 | 17 | use std::sync::{Arc, Mutex}; |
| 18 | 18 | use std::thread; |
| @@ -116,6 +116,11 @@ struct Audio { | ||
| 116 | 116 | /// is not the device's own callback -- the plugin's RT thread never sees |
| 117 | 117 | /// this lock, and the feeder holds it for one memcpy per write. |
| 118 | 118 | tap: Arc<Mutex<Vec<f32>>>, |
| 119 | + /// Feeder threads started and not yet returned. They are detached, so there | |
| 120 | + /// is no handle to count instead, and a scrub leaves dozens of them exiting | |
| 121 | + /// at once -- which is precisely what | |
| 122 | + /// [`live_workers`](PlaybackSession::live_workers) is asked about. | |
| 123 | + feeders: Arc<AtomicUsize>, | |
| 119 | 124 | } |
| 120 | 125 | |
| 121 | 126 | /// How much of the played signal the tap keeps. A power of two, because what |
| @@ -174,24 +179,35 @@ impl Audio { | ||
| 174 | 179 | ) -> bool { |
| 175 | 180 | let me = self.clone(); |
| 176 | 181 | let epoch = self.epoch.load(Ordering::Acquire); |
| 177 | - thread::Builder::new() | |
| 182 | + // Counted before the spawn, so the count is never behind the thread. | |
| 183 | + self.feeders.fetch_add(1, Ordering::Release); | |
| 184 | + let started = thread::Builder::new() | |
| 178 | 185 | .name("audio-feed".into()) |
| 179 | 186 | .spawn(move || { |
| 180 | 187 | // Superseded before this thread was even scheduled: do not open |
| 181 | 188 | // anything at all. A scrub leaves all but the last one here. |
| 182 | - if me.epoch.load(Ordering::Acquire) != epoch { | |
| 183 | - return; | |
| 184 | - } | |
| 185 | - if let Some(rx) = open() { | |
| 186 | - feed(rx, &me, epoch); | |
| 187 | - } | |
| 188 | - // Only the current feeder gets to declare the end of the audio: | |
| 189 | - // a superseded one is finished, the stream is not. | |
| 190 | 189 | if me.epoch.load(Ordering::Acquire) == epoch { |
| 191 | - me.fed_all.store(true, Ordering::Release); | |
| 190 | + if let Some(rx) = open() { | |
| 191 | + feed(rx, &me, epoch); | |
| 192 | + } | |
| 193 | + // Only the current feeder gets to declare the end of the | |
| 194 | + // audio: a superseded one is finished, the stream is not. | |
| 195 | + if me.epoch.load(Ordering::Acquire) == epoch { | |
| 196 | + me.fed_all.store(true, Ordering::Release); | |
| 197 | + } | |
| 192 | 198 | } |
| 199 | + me.feeders.fetch_sub(1, Ordering::Release); | |
| 193 | 200 | }) |
| 194 | - .is_ok() | |
| 201 | + .is_ok(); | |
| 202 | + if !started { | |
| 203 | + self.feeders.fetch_sub(1, Ordering::Release); | |
| 204 | + } | |
| 205 | + started | |
| 206 | + } | |
| 207 | + | |
| 208 | + /// Feeder threads still running; see [`Self::feeders`]. | |
| 209 | + fn live_feeders(&self) -> usize { | |
| 210 | + self.feeders.load(Ordering::Acquire) | |
| 195 | 211 | } |
| 196 | 212 | } |
| 197 | 213 | |
| @@ -1219,6 +1235,21 @@ impl PlaybackSession { | ||
| 1219 | 1235 | self.retired.retain(|w| !w.is_finished()); |
| 1220 | 1236 | } |
| 1221 | 1237 | |
| 1238 | + /// How many threads this session still has running of its own: the decode | |
| 1239 | + /// worker, every retired one that has not returned yet, and the audio | |
| 1240 | + /// feeders still in the air. One for a session playing along quietly. | |
| 1241 | + /// | |
| 1242 | + /// The oracle a seek storm is judged by. `/proc/self/status` counts the | |
| 1243 | + /// *process*, and a suite decoding twenty files at once moves that number | |
| 1244 | + /// under a test that never touched them -- this counts only what the | |
| 1245 | + /// session in hand owns, so it says the same thing alone and in a crowd. | |
| 1246 | + #[doc(hidden)] | |
| 1247 | + pub fn live_workers(&self) -> usize { | |
| 1248 | + usize::from(!self.worker.is_finished()) | |
| 1249 | + + self.retired.iter().filter(|w| !w.is_finished()).count() | |
| 1250 | + + self.audio.as_ref().map_or(0, Audio::live_feeders) | |
| 1251 | + } | |
| 1252 | + | |
| 1222 | 1253 | /// Starts feeding whatever follows the current span on the timeline -- |
| 1223 | 1254 | /// another clip, or a gap, which is black frames from a worker that opens no |
| 1224 | 1255 | /// file. `false` past the end. The next timeline frame is derived rather |
| @@ -2958,6 +2989,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | ||
| 2958 | 2989 | epoch: Arc::new(AtomicU64::new(0)), |
| 2959 | 2990 | content_at: Arc::new(AtomicI64::new(-1)), |
| 2960 | 2991 | tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), |
| 2992 | + feeders: Arc::new(AtomicUsize::new(0)), | |
| 2961 | 2993 | }; |
| 2962 | 2994 | (audio.spawn_feeder(rx).then_some(audio), None) |
| 2963 | 2995 | } |
crates/engine/tests/backends.rsmodified+76 -5
| @@ -104,9 +104,9 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { | ||
| 104 | 104 | (Format::Mp4, "mp4"), |
| 105 | 105 | (Format::Av1, "mkv"), |
| 106 | 106 | (Format::Av1Mp4, "mp4"), |
| 107 | - // Both HEVC containers, whose seat is software whatever the box has: | |
| 108 | - // the plugin encodes H.264 and AV1 and no HEVC, so a card that offered | |
| 109 | - // a hardware seat here would be promising one that cannot exist. | |
| 107 | + // Both HEVC containers, whose seat is the plugin's where the picture | |
| 108 | + // clears the driver's floor and the software intra encoder where it does | |
| 109 | + // not -- which of the two is this box's business and never this test's. | |
| 110 | 110 | (Format::Hevc, "mkv"), |
| 111 | 111 | (Format::HevcMp4, "mp4"), |
| 112 | 112 | ] { |
| @@ -150,13 +150,84 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { | ||
| 150 | 150 | assert!(planned.contains("AAC"), "{ext}: {planned}"); |
| 151 | 151 | if matches!(format, Format::Hevc | Format::HevcMp4) { |
| 152 | 152 | assert!( |
| 153 | - planned.contains("oxideav-h265 intra"), | |
| 154 | - "{ext}: an HEVC job names the intra encoder that writes it: {planned}" | |
| 153 | + planned.contains("oxideav-h265 intra") || planned.contains("HW encode"), | |
| 154 | + "{ext}: an HEVC job names one of the two HEVC seats: {planned}" | |
| 155 | 155 | ); |
| 156 | 156 | } |
| 157 | 157 | } |
| 158 | 158 | } |
| 159 | 159 | |
| 160 | +/// The same pin, swept over the two things that *move* the seat under a user's | |
| 161 | +/// hand: the picture size (the plugin refuses HEVC below the driver's 384x384 | |
| 162 | +/// floor and the software intra encoder takes the file) and the software pin on | |
| 163 | +/// the card. The export card reads [`engine::export::planned_video`] for every | |
| 164 | +/// one of these combinations, so a size that flips the seat and a card that kept | |
| 165 | +/// the old line is the exact lie this sweep exists to catch. | |
| 166 | +/// | |
| 167 | +/// Not swept: the hardware AV1 seat. It is `VE_HW_AV1=1` opt-in because opening | |
| 168 | +/// it hung this box's GPU into a driver reset (2026-08-10), and a test suite is | |
| 169 | +/// not the place to find out whether that is fixed -- `av1.rs` keeps that one | |
| 170 | +/// `#[ignore]`d and by name. | |
| 171 | +#[test] | |
| 172 | +fn the_planned_seat_follows_the_size_and_the_pin() { | |
| 173 | + for (format, ext) in [ | |
| 174 | + (Format::Mp4, "mp4"), | |
| 175 | + (Format::Av1, "mkv"), | |
| 176 | + (Format::Av1Mp4, "mp4"), | |
| 177 | + (Format::Hevc, "mkv"), | |
| 178 | + (Format::HevcMp4, "mp4"), | |
| 179 | + ] { | |
| 180 | + for (width, height) in [(320, 180), (1280, 720), (1920, 1080)] { | |
| 181 | + for force_sw in [false, true] { | |
| 182 | + let settings = ExportSettings { | |
| 183 | + format, | |
| 184 | + force_sw, | |
| 185 | + ..ExportSettings::default() | |
| 186 | + }; | |
| 187 | + let mut session = | |
| 188 | + PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | |
| 189 | + // The project resolution is what an export writes, so this is | |
| 190 | + // the very size the card's probe is asked about. | |
| 191 | + session.set_resolution(width, height); | |
| 192 | + let planned = engine::export::planned_video(session.meta(), &settings) | |
| 193 | + .expect("these formats carry picture"); | |
| 194 | + // A pinned job is software by definition, whatever the machine | |
| 195 | + // has -- the one seat this file may assert outright. | |
| 196 | + if force_sw { | |
| 197 | + assert!( | |
| 198 | + planned.starts_with("SW encode"), | |
| 199 | + "{ext} {width}x{height}: a pinned job is software, got {planned}" | |
| 200 | + ); | |
| 201 | + } | |
| 202 | + let out = out_path("seat", ext); | |
| 203 | + let handle = session.export_to_with(&out, &settings); | |
| 204 | + let started = Instant::now(); | |
| 205 | + let opened = loop { | |
| 206 | + if let Some(line) = handle.encoders() { | |
| 207 | + break line; | |
| 208 | + } | |
| 209 | + assert!( | |
| 210 | + !handle.is_finished(), | |
| 211 | + "{ext} {width}x{height}: settled before an encoder opened: {:?}", | |
| 212 | + handle.result().map(|r| r.err()) | |
| 213 | + ); | |
| 214 | + assert!( | |
| 215 | + started.elapsed() < Duration::from_secs(60), | |
| 216 | + "no encoder was published" | |
| 217 | + ); | |
| 218 | + std::thread::sleep(Duration::from_millis(10)); | |
| 219 | + }; | |
| 220 | + handle.cancel(); | |
| 221 | + wind_down(&handle); | |
| 222 | + assert!( | |
| 223 | + opened.starts_with(planned), | |
| 224 | + "{ext} {width}x{height} force_sw={force_sw}: the card said {planned}, the job opened {opened}" | |
| 225 | + ); | |
| 226 | + } | |
| 227 | + } | |
| 228 | + } | |
| 229 | +} | |
| 230 | + | |
| 160 | 231 | /// A WAV job has no picture at all and still names what writes it, so an audio |
| 161 | 232 | /// export is not a progress line with nothing to say. |
| 162 | 233 | #[test] |
crates/engine/tests/playback.rsmodified+11 -20
| @@ -169,15 +169,6 @@ fn source_frame(path: &Path, index: u32) -> Vec<u8> { | ||
| 169 | 169 | frame.bgra |
| 170 | 170 | } |
| 171 | 171 | |
| 172 | -fn threads() -> usize { | |
| 173 | - std::fs::read_to_string("/proc/self/status") | |
| 174 | - .unwrap() | |
| 175 | - .lines() | |
| 176 | - .find_map(|l| l.strip_prefix("Threads:")) | |
| 177 | - .and_then(|n| n.trim().parse().ok()) | |
| 178 | - .expect("Threads: in /proc/self/status") | |
| 179 | -} | |
| 180 | - | |
| 181 | 172 | /// Wall-clock seek: no audio track, so this runs anywhere. |
| 182 | 173 | #[test] |
| 183 | 174 | fn seek_repositions_video_and_clock() { |
| @@ -250,7 +241,7 @@ fn rapid_seeks_settle_on_the_last_one() { | ||
| 250 | 241 | |
| 251 | 242 | session.play(); |
| 252 | 243 | run_for(&mut session, &mut last_index, Duration::from_millis(300)); |
| 253 | - let before = threads(); | |
| 244 | + let before = session.live_workers(); | |
| 254 | 245 | |
| 255 | 246 | for t in [4.0, 1.0, 3.5, 0.5, 2.0] { |
| 256 | 247 | session.seek(t); |
| @@ -261,11 +252,11 @@ fn rapid_seeks_settle_on_the_last_one() { | ||
| 261 | 252 | ); |
| 262 | 253 | |
| 263 | 254 | sleep(Duration::from_millis(500)); // abandoned workers exit within an AU |
| 264 | - let after = threads(); | |
| 265 | - eprintln!("rapid seeks: {before} threads -> {after}"); | |
| 255 | + let after = session.live_workers(); | |
| 256 | + eprintln!("rapid seeks: {before} workers -> {after}"); | |
| 266 | 257 | assert!( |
| 267 | 258 | after <= before + 3, |
| 268 | - "workers piled up: {before} threads -> {after}" | |
| 259 | + "workers piled up: {before} workers -> {after}" | |
| 269 | 260 | ); |
| 270 | 261 | } |
| 271 | 262 | |
| @@ -273,8 +264,8 @@ fn rapid_seeks_settle_on_the_last_one() { | ||
| 273 | 264 | /// Each one abandons a worker and starts another, and since the open moved onto |
| 274 | 265 | /// the worker (`DecodeSession::open_worker_deferred`) not one of them reads the |
| 275 | 266 | /// file on this thread -- so the whole storm is 40 thread spawns, the parked |
| 276 | -/// workers are still reaped as they go (the thread count says so), and the last | |
| 277 | -/// seek still decides what is on screen. | |
| 267 | +/// workers are still reaped as they go (the session's own count says so), and | |
| 268 | +/// the last seek still decides what is on screen. | |
| 278 | 269 | #[test] |
| 279 | 270 | fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() { |
| 280 | 271 | let mut session = open(asset("test_av.mp4")); |
| @@ -283,7 +274,7 @@ fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() { | ||
| 283 | 274 | |
| 284 | 275 | session.play(); |
| 285 | 276 | run_for(&mut session, &mut last_index, Duration::from_millis(300)); |
| 286 | - let before = threads(); | |
| 277 | + let before = session.live_workers(); | |
| 287 | 278 | |
| 288 | 279 | let storm = Instant::now(); |
| 289 | 280 | for i in 0..39 { |
| @@ -291,7 +282,7 @@ fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() { | ||
| 291 | 282 | } |
| 292 | 283 | session.seek(2.0); |
| 293 | 284 | let issued = storm.elapsed(); |
| 294 | - eprintln!("40 seeks issued in {issued:?} ({before} threads before)"); | |
| 285 | + eprintln!("40 seeks issued in {issued:?} ({before} workers before)"); | |
| 295 | 286 | assert!( |
| 296 | 287 | issued < Duration::from_secs(1), |
| 297 | 288 | "40 seeks cost the caller {issued:?} -- a seek is opening a file again" |
| @@ -303,11 +294,11 @@ fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() { | ||
| 303 | 294 | ); |
| 304 | 295 | |
| 305 | 296 | sleep(Duration::from_millis(500)); // abandoned workers exit within an AU |
| 306 | - let after = threads(); | |
| 307 | - eprintln!("seek storm: {before} threads -> {after}"); | |
| 297 | + let after = session.live_workers(); | |
| 298 | + eprintln!("seek storm: {before} workers -> {after}"); | |
| 308 | 299 | assert!( |
| 309 | 300 | after <= before + 3, |
| 310 | - "the retired list grew with the storm: {before} threads -> {after}" | |
| 301 | + "the retired list grew with the storm: {before} workers -> {after}" | |
| 311 | 302 | ); |
| 312 | 303 | } |
| 313 | 304 |
scripts/bench.shmodified+1 -1
| @@ -98,7 +98,7 @@ for file in "${files[@]}"; do | ||
| 98 | 98 | run 1800 "seek_ttff_${t}s" "$file" seek "$t" |
| 99 | 99 | done |
| 100 | 100 | run 3600 scrub "$file" scrub |
| 101 | - for seat in h264sw h264hw av1 hevc; do | |
| 101 | + for seat in h264sw h264hw av1 hevc hevchw; do | |
| 102 | 102 | run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR" |
| 103 | 103 | done |
| 104 | 104 | done |
vendor/cros-codecs/src/codec/h264/nalu_writer.rsmodified+9 -2
| @@ -24,8 +24,10 @@ impl<W: Write> EmulationPrevention<W> { | ||
| 24 | 24 | fn write_byte(&mut self, curr_byte: u8) -> std::io::Result<()> { |
| 25 | 25 | if self.prev_bytes[1] == Some(0x00) && self.prev_bytes[0] == Some(0x00) && curr_byte <= 0x03 |
| 26 | 26 | { |
| 27 | - self.out.write_all(&[0x00, 0x00, 0x03, curr_byte])?; | |
| 28 | - self.prev_bytes = [None; 2]; | |
| 27 | + self.out.write_all(&[0x00, 0x00, 0x03])?; | |
| 28 | + // `curr_byte` stays pending, so that a following `0x00 0x00` pair | |
| 29 | + // starting with it is escaped as well. | |
| 30 | + self.prev_bytes = [Some(curr_byte), None]; | |
| 29 | 31 | } else { |
| 30 | 32 | if let Some(byte) = self.prev_bytes[1] { |
| 31 | 33 | self.out.write_all(&[byte])?; |
| @@ -295,5 +297,10 @@ mod tests { | ||
| 295 | 297 | test(&[0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x01]); |
| 296 | 298 | test(&[0x00, 0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x00, 0x02]); |
| 297 | 299 | test(&[0x00, 0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x00, 0x03]); |
| 300 | + | |
| 301 | + // A run of zeroes must be escaped again every two bytes, i.e. the byte | |
| 302 | + // that followed an escape counts towards the next pair. | |
| 303 | + test(&[0x00; 5], &[0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00]); | |
| 304 | + test(&[0x00, 0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x01]); | |
| 298 | 305 | } |
| 299 | 306 | } |
vendor/cros-codecs/src/codec/h265.rsmodified+2 -0
| @@ -3,5 +3,7 @@ | ||
| 3 | 3 | // found in the LICENSE file. |
| 4 | 4 | |
| 5 | 5 | pub mod dpb; |
| 6 | +pub mod nalu_writer; | |
| 6 | 7 | pub mod parser; |
| 7 | 8 | pub mod picture; |
| 9 | +pub mod synthesizer; |
vendor/cros-codecs/src/codec/h265/nalu_writer.rsadded+335 -0
| @@ -0,0 +1,335 @@ | ||
| 1 | +// Copyright 2024 The ChromiumOS Authors | |
| 2 | +// Use of this source code is governed by a BSD-style license that can be | |
| 3 | +// found in the LICENSE file. | |
| 4 | +use std::fmt; | |
| 5 | +use std::io::Write; | |
| 6 | + | |
| 7 | +use crate::bitstream_utils::BitWriter; | |
| 8 | +use crate::bitstream_utils::BitWriterError; | |
| 9 | + | |
| 10 | +/// Internal wrapper over [`std::io::Write`] for possible emulation prevention | |
| 11 | +struct EmulationPrevention<W: Write> { | |
| 12 | + out: W, | |
| 13 | + prev_bytes: [Option<u8>; 2], | |
| 14 | + | |
| 15 | + /// Emulation prevention enabled. | |
| 16 | + ep_enabled: bool, | |
| 17 | +} | |
| 18 | + | |
| 19 | +impl<W: Write> EmulationPrevention<W> { | |
| 20 | + fn new(writer: W, ep_enabled: bool) -> Self { | |
| 21 | + Self { out: writer, prev_bytes: [None; 2], ep_enabled } | |
| 22 | + } | |
| 23 | + | |
| 24 | + fn write_byte(&mut self, curr_byte: u8) -> std::io::Result<()> { | |
| 25 | + if self.prev_bytes[1] == Some(0x00) && self.prev_bytes[0] == Some(0x00) && curr_byte <= 0x03 | |
| 26 | + { | |
| 27 | + self.out.write_all(&[0x00, 0x00, 0x03])?; | |
| 28 | + // `curr_byte` stays pending, so that a following `0x00 0x00` pair | |
| 29 | + // starting with it is escaped as well. | |
| 30 | + self.prev_bytes = [Some(curr_byte), None]; | |
| 31 | + } else { | |
| 32 | + if let Some(byte) = self.prev_bytes[1] { | |
| 33 | + self.out.write_all(&[byte])?; | |
| 34 | + } | |
| 35 | + | |
| 36 | + self.prev_bytes[1] = self.prev_bytes[0]; | |
| 37 | + self.prev_bytes[0] = Some(curr_byte); | |
| 38 | + } | |
| 39 | + | |
| 40 | + Ok(()) | |
| 41 | + } | |
| 42 | + | |
| 43 | + /// Writes a H.265 NALU header. See 7.3.1.2 | |
| 44 | + fn write_header( | |
| 45 | + &mut self, | |
| 46 | + nalu_type: u8, | |
| 47 | + nuh_layer_id: u8, | |
| 48 | + nuh_temporal_id_plus1: u8, | |
| 49 | + ) -> NaluWriterResult<()> { | |
| 50 | + // forbidden_zero_bit | nal_unit_type | first bit of nuh_layer_id | |
| 51 | + let byte0 = (nalu_type & 0b111111) << 1 | (nuh_layer_id >> 5) & 0b1; | |
| 52 | + // remaining bits of nuh_layer_id | nuh_temporal_id_plus1 | |
| 53 | + let byte1 = (nuh_layer_id & 0b11111) << 3 | (nuh_temporal_id_plus1 & 0b111); | |
| 54 | + | |
| 55 | + self.out.write_all(&[0x00, 0x00, 0x00, 0x01, byte0, byte1])?; | |
| 56 | + | |
| 57 | + Ok(()) | |
| 58 | + } | |
| 59 | + | |
| 60 | + fn has_data_pending(&self) -> bool { | |
| 61 | + self.prev_bytes[0].is_some() || self.prev_bytes[1].is_some() | |
| 62 | + } | |
| 63 | +} | |
| 64 | + | |
| 65 | +impl<W: Write> Write for EmulationPrevention<W> { | |
| 66 | + fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { | |
| 67 | + if !self.ep_enabled { | |
| 68 | + self.out.write_all(buf)?; | |
| 69 | + return Ok(buf.len()); | |
| 70 | + } | |
| 71 | + | |
| 72 | + for byte in buf { | |
| 73 | + self.write_byte(*byte)?; | |
| 74 | + } | |
| 75 | + | |
| 76 | + Ok(buf.len()) | |
| 77 | + } | |
| 78 | + | |
| 79 | + fn flush(&mut self) -> std::io::Result<()> { | |
| 80 | + if let Some(byte) = self.prev_bytes[1].take() { | |
| 81 | + self.out.write_all(&[byte])?; | |
| 82 | + } | |
| 83 | + | |
| 84 | + if let Some(byte) = self.prev_bytes[0].take() { | |
| 85 | + self.out.write_all(&[byte])?; | |
| 86 | + } | |
| 87 | + | |
| 88 | + self.out.flush() | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +impl<W: Write> Drop for EmulationPrevention<W> { | |
| 93 | + fn drop(&mut self) { | |
| 94 | + if let Err(e) = self.flush() { | |
| 95 | + log::error!("Unable to flush pending bytes {e:?}"); | |
| 96 | + } | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 100 | +#[derive(Debug)] | |
| 101 | +pub enum NaluWriterError { | |
| 102 | + Overflow, | |
| 103 | + Io(std::io::Error), | |
| 104 | + BitWriterError(BitWriterError), | |
| 105 | +} | |
| 106 | + | |
| 107 | +impl fmt::Display for NaluWriterError { | |
| 108 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
| 109 | + match self { | |
| 110 | + NaluWriterError::Overflow => write!(f, "value increment caused value overflow"), | |
| 111 | + NaluWriterError::Io(x) => write!(f, "{}", x.to_string()), | |
| 112 | + NaluWriterError::BitWriterError(x) => write!(f, "{}", x.to_string()), | |
| 113 | + } | |
| 114 | + } | |
| 115 | +} | |
| 116 | + | |
| 117 | +impl From<std::io::Error> for NaluWriterError { | |
| 118 | + fn from(err: std::io::Error) -> Self { | |
| 119 | + NaluWriterError::Io(err) | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +impl From<BitWriterError> for NaluWriterError { | |
| 124 | + fn from(err: BitWriterError) -> Self { | |
| 125 | + NaluWriterError::BitWriterError(err) | |
| 126 | + } | |
| 127 | +} | |
| 128 | + | |
| 129 | +pub type NaluWriterResult<T> = std::result::Result<T, NaluWriterError>; | |
| 130 | + | |
| 131 | +/// A writer for H.265 bitstream. It is capable of outputing bitstream with | |
| 132 | +/// emulation-prevention. | |
| 133 | +pub struct NaluWriter<W: Write>(BitWriter<EmulationPrevention<W>>); | |
| 134 | + | |
| 135 | +impl<W: Write> NaluWriter<W> { | |
| 136 | + pub fn new(writer: W, ep_enabled: bool) -> Self { | |
| 137 | + Self(BitWriter::new(EmulationPrevention::new(writer, ep_enabled))) | |
| 138 | + } | |
| 139 | + | |
| 140 | + /// Writes fixed bit size integer (up to 32 bit) output with emulation | |
| 141 | + /// prevention if enabled. Corresponds to `f(n)` in H.265 spec. | |
| 142 | + pub fn write_f<T: Into<u32>>(&mut self, bits: usize, value: T) -> NaluWriterResult<usize> { | |
| 143 | + self.0.write_f(bits, value).map_err(NaluWriterError::BitWriterError) | |
| 144 | + } | |
| 145 | + | |
| 146 | + /// An alias to [`Self::write_f`] Corresponds to `u(n)` in H.265 spec. | |
| 147 | + pub fn write_u<T: Into<u32>>(&mut self, bits: usize, value: T) -> NaluWriterResult<usize> { | |
| 148 | + self.write_f(bits, value) | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// Writes a number in exponential golumb format. | |
| 152 | + pub fn write_exp_golumb(&mut self, value: u32) -> NaluWriterResult<()> { | |
| 153 | + let value = value.checked_add(1).ok_or(NaluWriterError::Overflow)?; | |
| 154 | + let bits = 32 - value.leading_zeros() as usize; | |
| 155 | + let zeros = bits - 1; | |
| 156 | + | |
| 157 | + self.write_f(zeros, 0u32)?; | |
| 158 | + self.write_f(bits, value)?; | |
| 159 | + | |
| 160 | + Ok(()) | |
| 161 | + } | |
| 162 | + | |
| 163 | + /// Writes a unsigned integer in exponential golumb format. | |
| 164 | + /// Coresponds to `ue(v)` in H.265 spec. | |
| 165 | + pub fn write_ue<T: Into<u32>>(&mut self, value: T) -> NaluWriterResult<()> { | |
| 166 | + let value = value.into(); | |
| 167 | + | |
| 168 | + self.write_exp_golumb(value) | |
| 169 | + } | |
| 170 | + | |
| 171 | + /// Writes a signed integer in exponential golumb format. | |
| 172 | + /// Coresponds to `se(v)` in H.265 spec. | |
| 173 | + pub fn write_se<T: Into<i32>>(&mut self, value: T) -> NaluWriterResult<()> { | |
| 174 | + let value: i32 = value.into(); | |
| 175 | + let abs_value: u32 = value.unsigned_abs(); | |
| 176 | + | |
| 177 | + if value <= 0 { | |
| 178 | + self.write_ue(2 * abs_value) | |
| 179 | + } else { | |
| 180 | + self.write_ue(2 * abs_value - 1) | |
| 181 | + } | |
| 182 | + } | |
| 183 | + | |
| 184 | + /// Returns `true` if ['Self`] hold data that wasn't written to [`std::io::Write`] | |
| 185 | + pub fn has_data_pending(&self) -> bool { | |
| 186 | + self.0.has_data_pending() || self.0.inner().has_data_pending() | |
| 187 | + } | |
| 188 | + | |
| 189 | + /// Writes a H.265 NALU header. Unlike H.264, the header is two bytes long. | |
| 190 | + /// See 7.3.1.2. | |
| 191 | + pub fn write_header( | |
| 192 | + &mut self, | |
| 193 | + nalu_type: u8, | |
| 194 | + nuh_layer_id: u8, | |
| 195 | + nuh_temporal_id_plus1: u8, | |
| 196 | + ) -> NaluWriterResult<()> { | |
| 197 | + self.0.flush()?; | |
| 198 | + self.0.inner_mut().write_header(nalu_type, nuh_layer_id, nuh_temporal_id_plus1)?; | |
| 199 | + Ok(()) | |
| 200 | + } | |
| 201 | + | |
| 202 | + /// Returns `true` if next bits will be aligned to 8 | |
| 203 | + pub fn aligned(&self) -> bool { | |
| 204 | + !self.0.has_data_pending() | |
| 205 | + } | |
| 206 | +} | |
| 207 | + | |
| 208 | +#[cfg(test)] | |
| 209 | +mod tests { | |
| 210 | + use super::*; | |
| 211 | + use crate::bitstream_utils::BitReader; | |
| 212 | + use crate::codec::h264::nalu::Header; | |
| 213 | + use crate::codec::h265::parser::Nalu; | |
| 214 | + use crate::codec::h265::parser::NaluType; | |
| 215 | + use std::io::Cursor; | |
| 216 | + | |
| 217 | + #[test] | |
| 218 | + fn simple_bits() { | |
| 219 | + let mut buf = Vec::<u8>::new(); | |
| 220 | + { | |
| 221 | + let mut writer = NaluWriter::new(&mut buf, false); | |
| 222 | + writer.write_f(1, true).unwrap(); | |
| 223 | + writer.write_f(1, false).unwrap(); | |
| 224 | + writer.write_f(1, false).unwrap(); | |
| 225 | + writer.write_f(1, false).unwrap(); | |
| 226 | + writer.write_f(1, true).unwrap(); | |
| 227 | + writer.write_f(1, true).unwrap(); | |
| 228 | + writer.write_f(1, true).unwrap(); | |
| 229 | + writer.write_f(1, true).unwrap(); | |
| 230 | + } | |
| 231 | + assert_eq!(buf, vec![0b10001111u8]); | |
| 232 | + } | |
| 233 | + | |
| 234 | + #[test] | |
| 235 | + fn simple_first_few_ue() { | |
| 236 | + fn single_ue(value: u32) -> Vec<u8> { | |
| 237 | + let mut buf = Vec::<u8>::new(); | |
| 238 | + { | |
| 239 | + let mut writer = NaluWriter::new(&mut buf, false); | |
| 240 | + writer.write_ue(value).unwrap(); | |
| 241 | + } | |
| 242 | + buf | |
| 243 | + } | |
| 244 | + | |
| 245 | + assert_eq!(single_ue(0), vec![0b10000000u8]); | |
| 246 | + assert_eq!(single_ue(1), vec![0b01000000u8]); | |
| 247 | + assert_eq!(single_ue(2), vec![0b01100000u8]); | |
| 248 | + assert_eq!(single_ue(3), vec![0b00100000u8]); | |
| 249 | + assert_eq!(single_ue(4), vec![0b00101000u8]); | |
| 250 | + assert_eq!(single_ue(5), vec![0b00110000u8]); | |
| 251 | + assert_eq!(single_ue(6), vec![0b00111000u8]); | |
| 252 | + assert_eq!(single_ue(7), vec![0b00010000u8]); | |
| 253 | + assert_eq!(single_ue(8), vec![0b00010010u8]); | |
| 254 | + assert_eq!(single_ue(9), vec![0b00010100u8]); | |
| 255 | + } | |
| 256 | + | |
| 257 | + #[test] | |
| 258 | + fn writer_reader() { | |
| 259 | + let mut buf = Vec::<u8>::new(); | |
| 260 | + { | |
| 261 | + let mut writer = NaluWriter::new(&mut buf, false); | |
| 262 | + writer.write_ue(10u32).unwrap(); | |
| 263 | + writer.write_se(-42).unwrap(); | |
| 264 | + writer.write_se(3).unwrap(); | |
| 265 | + writer.write_ue(5u32).unwrap(); | |
| 266 | + } | |
| 267 | + | |
| 268 | + let mut reader = BitReader::new(&buf, true); | |
| 269 | + | |
| 270 | + assert_eq!(reader.read_ue::<u32>().unwrap(), 10); | |
| 271 | + assert_eq!(reader.read_se::<i32>().unwrap(), -42); | |
| 272 | + assert_eq!(reader.read_se::<i32>().unwrap(), 3); | |
| 273 | + assert_eq!(reader.read_ue::<u32>().unwrap(), 5); | |
| 274 | + } | |
| 275 | + | |
| 276 | + /// The two byte NALU header must be parsed back by the H.265 parser. | |
| 277 | + #[test] | |
| 278 | + fn writer_header() { | |
| 279 | + for (type_, layer_id, temporal_id_plus1) in | |
| 280 | + [(NaluType::VpsNut, 0u8, 1u8), (NaluType::TrailR, 63, 7), (NaluType::IdrWRadl, 1, 3)] | |
| 281 | + { | |
| 282 | + let mut buf = Vec::<u8>::new(); | |
| 283 | + { | |
| 284 | + let mut writer = NaluWriter::new(&mut buf, true); | |
| 285 | + writer.write_header(type_ as u8, layer_id, temporal_id_plus1).unwrap(); | |
| 286 | + // A minimal payload, as NALUs are found by looking for the | |
| 287 | + // start code of the *next* one. | |
| 288 | + writer.write_f(8, 0xffu8).unwrap(); | |
| 289 | + } | |
| 290 | + | |
| 291 | + let mut cursor = Cursor::new(&buf[..]); | |
| 292 | + let nalu = Nalu::next(&mut cursor).unwrap(); | |
| 293 | + | |
| 294 | + assert_eq!(nalu.header.type_, type_); | |
| 295 | + assert_eq!(nalu.header.nuh_layer_id, layer_id); | |
| 296 | + assert_eq!(nalu.header.nuh_temporal_id_plus1, temporal_id_plus1); | |
| 297 | + assert_eq!(nalu.header.len(), 2); | |
| 298 | + } | |
| 299 | + } | |
| 300 | + | |
| 301 | + #[test] | |
| 302 | + fn writer_emulation_prevention() { | |
| 303 | + fn test(input: &[u8], bitstream: &[u8]) { | |
| 304 | + let mut buf = Vec::<u8>::new(); | |
| 305 | + { | |
| 306 | + let mut writer = NaluWriter::new(&mut buf, true); | |
| 307 | + for byte in input { | |
| 308 | + writer.write_f(8, *byte).unwrap(); | |
| 309 | + } | |
| 310 | + } | |
| 311 | + assert_eq!(buf, bitstream); | |
| 312 | + { | |
| 313 | + let mut reader = BitReader::new(&buf, true); | |
| 314 | + for byte in input { | |
| 315 | + assert_eq!(*byte, reader.read_bits::<u8>(8).unwrap()); | |
| 316 | + } | |
| 317 | + } | |
| 318 | + } | |
| 319 | + | |
| 320 | + test(&[0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00]); | |
| 321 | + test(&[0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x01]); | |
| 322 | + test(&[0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x02]); | |
| 323 | + test(&[0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x03]); | |
| 324 | + | |
| 325 | + test(&[0x00, 0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00, 0x00]); | |
| 326 | + test(&[0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x01]); | |
| 327 | + test(&[0x00, 0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x00, 0x02]); | |
| 328 | + test(&[0x00, 0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x00, 0x03]); | |
| 329 | + | |
| 330 | + // A run of zeroes must be escaped again every two bytes, i.e. the byte | |
| 331 | + // that followed an escape counts towards the next pair. | |
| 332 | + test(&[0x00; 5], &[0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00]); | |
| 333 | + test(&[0x00, 0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x01]); | |
| 334 | + } | |
| 335 | +} |
vendor/cros-codecs/src/codec/h265/parser.rsmodified+659 -0
| @@ -496,6 +496,115 @@ impl Default for Vps { | ||
| 496 | 496 | } |
| 497 | 497 | } |
| 498 | 498 | |
| 499 | +/// A builder for a [`Vps`], covering the syntax elements an encoder is | |
| 500 | +/// expected to set. Anything else is left at its specification default. | |
| 501 | +pub struct VpsBuilder(Vps); | |
| 502 | + | |
| 503 | +impl VpsBuilder { | |
| 504 | + pub fn new() -> Self { | |
| 505 | + VpsBuilder(Vps { | |
| 506 | + base_layer_internal_flag: true, | |
| 507 | + base_layer_available_flag: true, | |
| 508 | + temporal_id_nesting_flag: true, | |
| 509 | + sub_layer_ordering_info_present_flag: true, | |
| 510 | + profile_tier_level: ProfileTierLevel { | |
| 511 | + general_progressive_source_flag: true, | |
| 512 | + general_frame_only_constraint_flag: true, | |
| 513 | + ..Default::default() | |
| 514 | + }, | |
| 515 | + ..Default::default() | |
| 516 | + }) | |
| 517 | + } | |
| 518 | + | |
| 519 | + pub fn video_parameter_set_id(mut self, value: u8) -> Self { | |
| 520 | + self.0.video_parameter_set_id = value; | |
| 521 | + self | |
| 522 | + } | |
| 523 | + | |
| 524 | + pub fn max_layers_minus1(mut self, value: u8) -> Self { | |
| 525 | + self.0.max_layers_minus1 = value; | |
| 526 | + self | |
| 527 | + } | |
| 528 | + | |
| 529 | + pub fn max_sub_layers_minus1(mut self, value: u8) -> Self { | |
| 530 | + self.0.max_sub_layers_minus1 = value; | |
| 531 | + self | |
| 532 | + } | |
| 533 | + | |
| 534 | + pub fn temporal_id_nesting_flag(mut self, value: bool) -> Self { | |
| 535 | + self.0.temporal_id_nesting_flag = value; | |
| 536 | + self | |
| 537 | + } | |
| 538 | + | |
| 539 | + pub fn general_profile(mut self, value: Profile) -> Self { | |
| 540 | + self.0.profile_tier_level.general_profile_idc = value as u8; | |
| 541 | + self.0.profile_tier_level.general_profile_compatibility_flag = [false; 32]; | |
| 542 | + self.0.profile_tier_level.general_profile_compatibility_flag[value as usize] = true; | |
| 543 | + self | |
| 544 | + } | |
| 545 | + | |
| 546 | + pub fn general_tier_flag(mut self, value: bool) -> Self { | |
| 547 | + self.0.profile_tier_level.general_tier_flag = value; | |
| 548 | + self | |
| 549 | + } | |
| 550 | + | |
| 551 | + pub fn general_level_idc(mut self, value: Level) -> Self { | |
| 552 | + self.0.profile_tier_level.general_level_idc = value; | |
| 553 | + self | |
| 554 | + } | |
| 555 | + | |
| 556 | + /// Sets `vps_max_dec_pic_buffering_minus1` for the highest sub-layer. | |
| 557 | + pub fn max_dec_pic_buffering_minus1(mut self, value: u32) -> Self { | |
| 558 | + self.0.max_dec_pic_buffering_minus1[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 559 | + self | |
| 560 | + } | |
| 561 | + | |
| 562 | + /// Sets `vps_max_num_reorder_pics` for the highest sub-layer. | |
| 563 | + pub fn max_num_reorder_pics(mut self, value: u32) -> Self { | |
| 564 | + self.0.max_num_reorder_pics[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 565 | + self | |
| 566 | + } | |
| 567 | + | |
| 568 | + /// Sets `vps_max_latency_increase_plus1` for the highest sub-layer. | |
| 569 | + pub fn max_latency_increase_plus1(mut self, value: u32) -> Self { | |
| 570 | + self.0.max_latency_increase_plus1[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 571 | + self | |
| 572 | + } | |
| 573 | + | |
| 574 | + pub fn sub_layer_ordering_info_present_flag(mut self, value: bool) -> Self { | |
| 575 | + self.0.sub_layer_ordering_info_present_flag = value; | |
| 576 | + self | |
| 577 | + } | |
| 578 | + | |
| 579 | + pub fn timing_info(mut self, num_units_in_tick: u32, time_scale: u32) -> Self { | |
| 580 | + self.0.timing_info_present_flag = true; | |
| 581 | + self.0.num_units_in_tick = num_units_in_tick; | |
| 582 | + self.0.time_scale = time_scale; | |
| 583 | + self | |
| 584 | + } | |
| 585 | + | |
| 586 | + pub fn build(mut self) -> Rc<Vps> { | |
| 587 | + // 7.4.3.1: when vps_sub_layer_ordering_info_present_flag is 0, the | |
| 588 | + // values for the highest sub-layer apply to all sub-layers. | |
| 589 | + if !self.0.sub_layer_ordering_info_present_flag { | |
| 590 | + let max = usize::from(self.0.max_sub_layers_minus1); | |
| 591 | + for i in 0..max { | |
| 592 | + self.0.max_dec_pic_buffering_minus1[i] = self.0.max_dec_pic_buffering_minus1[max]; | |
| 593 | + self.0.max_num_reorder_pics[i] = self.0.max_num_reorder_pics[max]; | |
| 594 | + self.0.max_latency_increase_plus1[i] = self.0.max_latency_increase_plus1[max]; | |
| 595 | + } | |
| 596 | + } | |
| 597 | + | |
| 598 | + Rc::new(self.0) | |
| 599 | + } | |
| 600 | +} | |
| 601 | + | |
| 602 | +impl Default for VpsBuilder { | |
| 603 | + fn default() -> Self { | |
| 604 | + Self::new() | |
| 605 | + } | |
| 606 | +} | |
| 607 | + | |
| 499 | 608 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 500 | 609 | pub struct ProfileTierLevel { |
| 501 | 610 | /// Specifies the context for the interpretation of general_profile_idc and |
| @@ -1003,6 +1112,325 @@ impl Sps { | ||
| 1003 | 1112 | } |
| 1004 | 1113 | } |
| 1005 | 1114 | |
| 1115 | +/// A builder for a [`Sps`], covering the syntax elements an encoder is expected | |
| 1116 | +/// to set. Anything else is left at its specification default. | |
| 1117 | +pub struct SpsBuilder(Sps); | |
| 1118 | + | |
| 1119 | +impl SpsBuilder { | |
| 1120 | + /// Starts a SPS referring to `vps`, inheriting its profile_tier_level() and | |
| 1121 | + /// its sub-layer configuration. | |
| 1122 | + pub fn new(vps: Rc<Vps>) -> Self { | |
| 1123 | + SpsBuilder(Sps { | |
| 1124 | + video_parameter_set_id: vps.video_parameter_set_id, | |
| 1125 | + max_sub_layers_minus1: vps.max_sub_layers_minus1, | |
| 1126 | + temporal_id_nesting_flag: vps.temporal_id_nesting_flag, | |
| 1127 | + profile_tier_level: vps.profile_tier_level.clone(), | |
| 1128 | + chroma_format_idc: 1, | |
| 1129 | + // MaxPicOrderCntLsb = 256. | |
| 1130 | + log2_max_pic_order_cnt_lsb_minus4: 4, | |
| 1131 | + sub_layer_ordering_info_present_flag: true, | |
| 1132 | + // MinCbSizeY = 8, CtbSizeY = 64. | |
| 1133 | + log2_min_luma_coding_block_size_minus3: 0, | |
| 1134 | + log2_diff_max_min_luma_coding_block_size: 3, | |
| 1135 | + // MinTbSizeY = 4, MaxTbSizeY = 32. | |
| 1136 | + log2_min_luma_transform_block_size_minus2: 0, | |
| 1137 | + log2_diff_max_min_luma_transform_block_size: 3, | |
| 1138 | + vps: Some(vps), | |
| 1139 | + ..Default::default() | |
| 1140 | + }) | |
| 1141 | + } | |
| 1142 | + | |
| 1143 | + pub fn seq_parameter_set_id(mut self, value: u8) -> Self { | |
| 1144 | + self.0.seq_parameter_set_id = value; | |
| 1145 | + self | |
| 1146 | + } | |
| 1147 | + | |
| 1148 | + pub fn general_profile(mut self, value: Profile) -> Self { | |
| 1149 | + self.0.profile_tier_level.general_profile_idc = value as u8; | |
| 1150 | + self.0.profile_tier_level.general_profile_compatibility_flag = [false; 32]; | |
| 1151 | + self.0.profile_tier_level.general_profile_compatibility_flag[value as usize] = true; | |
| 1152 | + self | |
| 1153 | + } | |
| 1154 | + | |
| 1155 | + pub fn general_tier_flag(mut self, value: bool) -> Self { | |
| 1156 | + self.0.profile_tier_level.general_tier_flag = value; | |
| 1157 | + self | |
| 1158 | + } | |
| 1159 | + | |
| 1160 | + pub fn general_level_idc(mut self, value: Level) -> Self { | |
| 1161 | + self.0.profile_tier_level.general_level_idc = value; | |
| 1162 | + self | |
| 1163 | + } | |
| 1164 | + | |
| 1165 | + pub fn chroma_format_idc(mut self, value: u8) -> Self { | |
| 1166 | + self.0.chroma_format_idc = value; | |
| 1167 | + self | |
| 1168 | + } | |
| 1169 | + | |
| 1170 | + pub fn separate_colour_plane_flag(mut self, value: bool) -> Self { | |
| 1171 | + self.0.separate_colour_plane_flag = value; | |
| 1172 | + self | |
| 1173 | + } | |
| 1174 | + | |
| 1175 | + pub fn bit_depth_luma_minus8(mut self, value: u8) -> Self { | |
| 1176 | + self.0.bit_depth_luma_minus8 = value; | |
| 1177 | + self | |
| 1178 | + } | |
| 1179 | + | |
| 1180 | + pub fn bit_depth_luma(self, value: u8) -> Self { | |
| 1181 | + self.bit_depth_luma_minus8(value - 8u8) | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | + pub fn bit_depth_chroma_minus8(mut self, value: u8) -> Self { | |
| 1185 | + self.0.bit_depth_chroma_minus8 = value; | |
| 1186 | + self | |
| 1187 | + } | |
| 1188 | + | |
| 1189 | + pub fn bit_depth_chroma(self, value: u8) -> Self { | |
| 1190 | + self.bit_depth_chroma_minus8(value - 8u8) | |
| 1191 | + } | |
| 1192 | + | |
| 1193 | + /// Sets the conformance cropping window. The offsets are given in luma | |
| 1194 | + /// samples and are converted to the units of clause 7.4.3.2.1, so | |
| 1195 | + /// [`Self::chroma_format_idc`] must be set beforehand. | |
| 1196 | + pub fn conformance_window(mut self, left: u32, right: u32, top: u32, bottom: u32) -> Self { | |
| 1197 | + // Table 6-1. | |
| 1198 | + let (sub_width_c, sub_height_c) = match self.0.chroma_format_idc { | |
| 1199 | + 1 => (2, 2), | |
| 1200 | + 2 => (2, 1), | |
| 1201 | + _ => (1, 1), | |
| 1202 | + }; | |
| 1203 | + | |
| 1204 | + self.0.conformance_window_flag = true; | |
| 1205 | + self.0.conf_win_left_offset = left / sub_width_c; | |
| 1206 | + self.0.conf_win_right_offset = right / sub_width_c; | |
| 1207 | + self.0.conf_win_top_offset = top / sub_height_c; | |
| 1208 | + self.0.conf_win_bottom_offset = bottom / sub_height_c; | |
| 1209 | + self | |
| 1210 | + } | |
| 1211 | + | |
| 1212 | + /// Sets the visible resolution. The coded resolution is aligned to | |
| 1213 | + /// MinCbSizeY, the difference being signalled through the conformance | |
| 1214 | + /// cropping window. | |
| 1215 | + pub fn resolution(mut self, width: u32, height: u32) -> Self { | |
| 1216 | + let min_cb_size = 1u32 << (self.0.log2_min_luma_coding_block_size_minus3 + 3); | |
| 1217 | + | |
| 1218 | + let coded_width = (width + min_cb_size - 1) / min_cb_size * min_cb_size; | |
| 1219 | + let coded_height = (height + min_cb_size - 1) / min_cb_size * min_cb_size; | |
| 1220 | + | |
| 1221 | + self.0.pic_width_in_luma_samples = coded_width as u16; | |
| 1222 | + self.0.pic_height_in_luma_samples = coded_height as u16; | |
| 1223 | + | |
| 1224 | + if coded_width != width || coded_height != height { | |
| 1225 | + self = self.conformance_window(0, coded_width - width, 0, coded_height - height); | |
| 1226 | + } | |
| 1227 | + | |
| 1228 | + self | |
| 1229 | + } | |
| 1230 | + | |
| 1231 | + pub fn log2_max_pic_order_cnt_lsb_minus4(mut self, value: u8) -> Self { | |
| 1232 | + self.0.log2_max_pic_order_cnt_lsb_minus4 = value; | |
| 1233 | + self | |
| 1234 | + } | |
| 1235 | + | |
| 1236 | + pub fn max_pic_order_cnt_lsb(self, value: u32) -> Self { | |
| 1237 | + self.log2_max_pic_order_cnt_lsb_minus4(value.ilog2() as u8 - 4u8) | |
| 1238 | + } | |
| 1239 | + | |
| 1240 | + pub fn sub_layer_ordering_info_present_flag(mut self, value: bool) -> Self { | |
| 1241 | + self.0.sub_layer_ordering_info_present_flag = value; | |
| 1242 | + self | |
| 1243 | + } | |
| 1244 | + | |
| 1245 | + /// Sets `sps_max_dec_pic_buffering_minus1` for the highest sub-layer. | |
| 1246 | + pub fn max_dec_pic_buffering_minus1(mut self, value: u8) -> Self { | |
| 1247 | + self.0.max_dec_pic_buffering_minus1[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 1248 | + self | |
| 1249 | + } | |
| 1250 | + | |
| 1251 | + /// Sets `sps_max_num_reorder_pics` for the highest sub-layer. | |
| 1252 | + pub fn max_num_reorder_pics(mut self, value: u8) -> Self { | |
| 1253 | + self.0.max_num_reorder_pics[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 1254 | + self | |
| 1255 | + } | |
| 1256 | + | |
| 1257 | + /// Sets `sps_max_latency_increase_plus1` for the highest sub-layer. | |
| 1258 | + pub fn max_latency_increase_plus1(mut self, value: u8) -> Self { | |
| 1259 | + self.0.max_latency_increase_plus1[usize::from(self.0.max_sub_layers_minus1)] = value; | |
| 1260 | + self | |
| 1261 | + } | |
| 1262 | + | |
| 1263 | + pub fn log2_min_luma_coding_block_size_minus3(mut self, value: u8) -> Self { | |
| 1264 | + self.0.log2_min_luma_coding_block_size_minus3 = value; | |
| 1265 | + self | |
| 1266 | + } | |
| 1267 | + | |
| 1268 | + pub fn log2_diff_max_min_luma_coding_block_size(mut self, value: u8) -> Self { | |
| 1269 | + self.0.log2_diff_max_min_luma_coding_block_size = value; | |
| 1270 | + self | |
| 1271 | + } | |
| 1272 | + | |
| 1273 | + pub fn log2_min_luma_transform_block_size_minus2(mut self, value: u8) -> Self { | |
| 1274 | + self.0.log2_min_luma_transform_block_size_minus2 = value; | |
| 1275 | + self | |
| 1276 | + } | |
| 1277 | + | |
| 1278 | + pub fn log2_diff_max_min_luma_transform_block_size(mut self, value: u8) -> Self { | |
| 1279 | + self.0.log2_diff_max_min_luma_transform_block_size = value; | |
| 1280 | + self | |
| 1281 | + } | |
| 1282 | + | |
| 1283 | + pub fn max_transform_hierarchy_depth_inter(mut self, value: u8) -> Self { | |
| 1284 | + self.0.max_transform_hierarchy_depth_inter = value; | |
| 1285 | + self | |
| 1286 | + } | |
| 1287 | + | |
| 1288 | + pub fn max_transform_hierarchy_depth_intra(mut self, value: u8) -> Self { | |
| 1289 | + self.0.max_transform_hierarchy_depth_intra = value; | |
| 1290 | + self | |
| 1291 | + } | |
| 1292 | + | |
| 1293 | + /// Enables `scaling_list_enabled_flag` and signals `value` in the SPS. | |
| 1294 | + pub fn scaling_list(mut self, value: ScalingLists) -> Self { | |
| 1295 | + self.0.scaling_list_enabled_flag = true; | |
| 1296 | + self.0.scaling_list_data_present_flag = true; | |
| 1297 | + self.0.scaling_list = value; | |
| 1298 | + self | |
| 1299 | + } | |
| 1300 | + | |
| 1301 | + pub fn scaling_list_enabled_flag(mut self, value: bool) -> Self { | |
| 1302 | + self.0.scaling_list_enabled_flag = value; | |
| 1303 | + self | |
| 1304 | + } | |
| 1305 | + | |
| 1306 | + pub fn amp_enabled_flag(mut self, value: bool) -> Self { | |
| 1307 | + self.0.amp_enabled_flag = value; | |
| 1308 | + self | |
| 1309 | + } | |
| 1310 | + | |
| 1311 | + pub fn sample_adaptive_offset_enabled_flag(mut self, value: bool) -> Self { | |
| 1312 | + self.0.sample_adaptive_offset_enabled_flag = value; | |
| 1313 | + self | |
| 1314 | + } | |
| 1315 | + | |
| 1316 | + /// Appends a st_ref_pic_set() to the SPS. Only sets that do not use inter | |
| 1317 | + /// RPS prediction can be synthesized. | |
| 1318 | + pub fn short_term_ref_pic_set(mut self, value: ShortTermRefPicSet) -> Self { | |
| 1319 | + self.0.short_term_ref_pic_set.push(value); | |
| 1320 | + self | |
| 1321 | + } | |
| 1322 | + | |
| 1323 | + pub fn long_term_ref_pics_present_flag(mut self, value: bool) -> Self { | |
| 1324 | + self.0.long_term_ref_pics_present_flag = value; | |
| 1325 | + self | |
| 1326 | + } | |
| 1327 | + | |
| 1328 | + pub fn temporal_mvp_enabled_flag(mut self, value: bool) -> Self { | |
| 1329 | + self.0.temporal_mvp_enabled_flag = value; | |
| 1330 | + self | |
| 1331 | + } | |
| 1332 | + | |
| 1333 | + pub fn strong_intra_smoothing_enabled_flag(mut self, value: bool) -> Self { | |
| 1334 | + self.0.strong_intra_smoothing_enabled_flag = value; | |
| 1335 | + self | |
| 1336 | + } | |
| 1337 | + | |
| 1338 | + pub fn vui_parameters_present(mut self) -> Self { | |
| 1339 | + self.0.vui_parameters_present_flag = true; | |
| 1340 | + self | |
| 1341 | + } | |
| 1342 | + | |
| 1343 | + pub fn timing_info( | |
| 1344 | + mut self, | |
| 1345 | + num_units_in_tick: u32, | |
| 1346 | + time_scale: u32, | |
| 1347 | + poc_proportional_to_timing_flag: bool, | |
| 1348 | + ) -> Self { | |
| 1349 | + self = self.vui_parameters_present(); | |
| 1350 | + self.0.vui_parameters.timing_info_present_flag = true; | |
| 1351 | + self.0.vui_parameters.num_units_in_tick = num_units_in_tick; | |
| 1352 | + self.0.vui_parameters.time_scale = time_scale; | |
| 1353 | + self.0.vui_parameters.poc_proportional_to_timing_flag = poc_proportional_to_timing_flag; | |
| 1354 | + self | |
| 1355 | + } | |
| 1356 | + | |
| 1357 | + pub fn video_signal_type(mut self, video_format: u8, video_full_range_flag: bool) -> Self { | |
| 1358 | + self = self.vui_parameters_present(); | |
| 1359 | + self.0.vui_parameters.video_signal_type_present_flag = true; | |
| 1360 | + self.0.vui_parameters.video_format = video_format; | |
| 1361 | + self.0.vui_parameters.video_full_range_flag = video_full_range_flag; | |
| 1362 | + self | |
| 1363 | + } | |
| 1364 | + | |
| 1365 | + pub fn colour_description( | |
| 1366 | + mut self, | |
| 1367 | + colour_primaries: u32, | |
| 1368 | + transfer_characteristics: u32, | |
| 1369 | + matrix_coeffs: u32, | |
| 1370 | + ) -> Self { | |
| 1371 | + let video_format = self.0.vui_parameters.video_format; | |
| 1372 | + let video_full_range_flag = self.0.vui_parameters.video_full_range_flag; | |
| 1373 | + | |
| 1374 | + self = self.video_signal_type(video_format, video_full_range_flag); | |
| 1375 | + self.0.vui_parameters.colour_description_present_flag = true; | |
| 1376 | + self.0.vui_parameters.colour_primaries = colour_primaries; | |
| 1377 | + self.0.vui_parameters.transfer_characteristics = transfer_characteristics; | |
| 1378 | + self.0.vui_parameters.matrix_coeffs = matrix_coeffs; | |
| 1379 | + self | |
| 1380 | + } | |
| 1381 | + | |
| 1382 | + pub fn build(mut self) -> Rc<Sps> { | |
| 1383 | + let sps = &mut self.0; | |
| 1384 | + | |
| 1385 | + sps.num_short_term_ref_pic_sets = sps.short_term_ref_pic_set.len() as u8; | |
| 1386 | + | |
| 1387 | + // The same derivations the parser performs, see parse_sps(). | |
| 1388 | + sps.chroma_array_type = | |
| 1389 | + if sps.separate_colour_plane_flag { 0 } else { sps.chroma_format_idc }; | |
| 1390 | + | |
| 1391 | + // (7-10) | |
| 1392 | + sps.min_cb_log2_size_y = u32::from(sps.log2_min_luma_coding_block_size_minus3 + 3); | |
| 1393 | + // (7-11) | |
| 1394 | + sps.ctb_log2_size_y = | |
| 1395 | + sps.min_cb_log2_size_y + u32::from(sps.log2_diff_max_min_luma_coding_block_size); | |
| 1396 | + // (7-12) | |
| 1397 | + sps.ctb_size_y = 1 << sps.ctb_log2_size_y; | |
| 1398 | + // (7-15) | |
| 1399 | + sps.pic_width_in_ctbs_y = | |
| 1400 | + (u32::from(sps.pic_width_in_luma_samples) + sps.ctb_size_y - 1) / sps.ctb_size_y; | |
| 1401 | + // (7-17) | |
| 1402 | + sps.pic_height_in_ctbs_y = | |
| 1403 | + (u32::from(sps.pic_height_in_luma_samples) + sps.ctb_size_y - 1) / sps.ctb_size_y; | |
| 1404 | + // (7-19) | |
| 1405 | + sps.pic_size_in_ctbs_y = sps.pic_width_in_ctbs_y * sps.pic_height_in_ctbs_y; | |
| 1406 | + | |
| 1407 | + sps.max_tb_log2_size_y = u32::from( | |
| 1408 | + sps.log2_min_luma_transform_block_size_minus2 | |
| 1409 | + + 2 | |
| 1410 | + + sps.log2_diff_max_min_luma_transform_block_size, | |
| 1411 | + ); | |
| 1412 | + | |
| 1413 | + sps.pic_size_in_samples_y = | |
| 1414 | + u32::from(sps.pic_width_in_luma_samples) * u32::from(sps.pic_height_in_luma_samples); | |
| 1415 | + | |
| 1416 | + let shift = if sps.range_extension.high_precision_offsets_enabled_flag { | |
| 1417 | + sps.bit_depth_luma_minus8 + 7 | |
| 1418 | + } else { | |
| 1419 | + 7 | |
| 1420 | + }; | |
| 1421 | + sps.wp_offset_half_range_y = 1 << shift; | |
| 1422 | + | |
| 1423 | + let shift = if sps.range_extension.high_precision_offsets_enabled_flag { | |
| 1424 | + sps.bit_depth_chroma_minus8 + 7 | |
| 1425 | + } else { | |
| 1426 | + 7 | |
| 1427 | + }; | |
| 1428 | + sps.wp_offset_half_range_c = 1 << shift; | |
| 1429 | + | |
| 1430 | + Rc::new(self.0) | |
| 1431 | + } | |
| 1432 | +} | |
| 1433 | + | |
| 1006 | 1434 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 1007 | 1435 | pub struct PpsSccExtension { |
| 1008 | 1436 | /// When set, specifies that a picture referring to the PPS may be included |
| @@ -1328,6 +1756,237 @@ pub struct Pps { | ||
| 1328 | 1756 | pub sps: Rc<Sps>, |
| 1329 | 1757 | } |
| 1330 | 1758 | |
| 1759 | +/// A builder for a [`Pps`], covering the syntax elements an encoder is expected | |
| 1760 | +/// to set. Anything else is left at its specification default. | |
| 1761 | +pub struct PpsBuilder(Pps); | |
| 1762 | + | |
| 1763 | +impl PpsBuilder { | |
| 1764 | + /// Starts a PPS referring to `sps`. | |
| 1765 | + pub fn new(sps: Rc<Sps>) -> Self { | |
| 1766 | + let mut scaling_list = ScalingLists::default(); | |
| 1767 | + | |
| 1768 | + // When pps_scaling_list_data_present_flag is not set and the SPS does | |
| 1769 | + // not signal scaling lists either, the default lists apply, see 7.4.5. | |
| 1770 | + for size_id in 0..4 { | |
| 1771 | + let mut matrix_id = 0; | |
| 1772 | + while matrix_id < 6 { | |
| 1773 | + Parser::fill_default_scaling_list(&mut scaling_list, size_id, matrix_id); | |
| 1774 | + matrix_id += if size_id == 3 { 3 } else { 1 }; | |
| 1775 | + } | |
| 1776 | + } | |
| 1777 | + | |
| 1778 | + PpsBuilder(Pps { | |
| 1779 | + pic_parameter_set_id: 0, | |
| 1780 | + seq_parameter_set_id: sps.seq_parameter_set_id, | |
| 1781 | + dependent_slice_segments_enabled_flag: false, | |
| 1782 | + output_flag_present_flag: false, | |
| 1783 | + num_extra_slice_header_bits: 0, | |
| 1784 | + sign_data_hiding_enabled_flag: false, | |
| 1785 | + cabac_init_present_flag: false, | |
| 1786 | + num_ref_idx_l0_default_active_minus1: 0, | |
| 1787 | + num_ref_idx_l1_default_active_minus1: 0, | |
| 1788 | + init_qp_minus26: 0, | |
| 1789 | + constrained_intra_pred_flag: false, | |
| 1790 | + transform_skip_enabled_flag: false, | |
| 1791 | + cu_qp_delta_enabled_flag: false, | |
| 1792 | + diff_cu_qp_delta_depth: 0, | |
| 1793 | + cb_qp_offset: 0, | |
| 1794 | + cr_qp_offset: 0, | |
| 1795 | + slice_chroma_qp_offsets_present_flag: false, | |
| 1796 | + weighted_pred_flag: false, | |
| 1797 | + weighted_bipred_flag: false, | |
| 1798 | + transquant_bypass_enabled_flag: false, | |
| 1799 | + tiles_enabled_flag: false, | |
| 1800 | + entropy_coding_sync_enabled_flag: false, | |
| 1801 | + num_tile_columns_minus1: 0, | |
| 1802 | + num_tile_rows_minus1: 0, | |
| 1803 | + uniform_spacing_flag: true, | |
| 1804 | + column_width_minus1: Default::default(), | |
| 1805 | + row_height_minus1: Default::default(), | |
| 1806 | + loop_filter_across_tiles_enabled_flag: true, | |
| 1807 | + loop_filter_across_slices_enabled_flag: false, | |
| 1808 | + deblocking_filter_control_present_flag: false, | |
| 1809 | + deblocking_filter_override_enabled_flag: false, | |
| 1810 | + deblocking_filter_disabled_flag: false, | |
| 1811 | + beta_offset_div2: 0, | |
| 1812 | + tc_offset_div2: 0, | |
| 1813 | + scaling_list_data_present_flag: false, | |
| 1814 | + scaling_list, | |
| 1815 | + lists_modification_present_flag: false, | |
| 1816 | + log2_parallel_merge_level_minus2: 0, | |
| 1817 | + slice_segment_header_extension_present_flag: false, | |
| 1818 | + extension_present_flag: false, | |
| 1819 | + range_extension_flag: false, | |
| 1820 | + range_extension: Default::default(), | |
| 1821 | + scc_extension_flag: false, | |
| 1822 | + scc_extension: Default::default(), | |
| 1823 | + // (7-5) | |
| 1824 | + qp_bd_offset_y: 6 * u32::from(sps.bit_depth_luma_minus8), | |
| 1825 | + sps, | |
| 1826 | + }) | |
| 1827 | + } | |
| 1828 | + | |
| 1829 | + pub fn pic_parameter_set_id(mut self, value: u8) -> Self { | |
| 1830 | + self.0.pic_parameter_set_id = value; | |
| 1831 | + self | |
| 1832 | + } | |
| 1833 | + | |
| 1834 | + pub fn dependent_slice_segments_enabled_flag(mut self, value: bool) -> Self { | |
| 1835 | + self.0.dependent_slice_segments_enabled_flag = value; | |
| 1836 | + self | |
| 1837 | + } | |
| 1838 | + | |
| 1839 | + pub fn output_flag_present_flag(mut self, value: bool) -> Self { | |
| 1840 | + self.0.output_flag_present_flag = value; | |
| 1841 | + self | |
| 1842 | + } | |
| 1843 | + | |
| 1844 | + pub fn num_extra_slice_header_bits(mut self, value: u8) -> Self { | |
| 1845 | + self.0.num_extra_slice_header_bits = value; | |
| 1846 | + self | |
| 1847 | + } | |
| 1848 | + | |
| 1849 | + pub fn sign_data_hiding_enabled_flag(mut self, value: bool) -> Self { | |
| 1850 | + self.0.sign_data_hiding_enabled_flag = value; | |
| 1851 | + self | |
| 1852 | + } | |
| 1853 | + | |
| 1854 | + pub fn cabac_init_present_flag(mut self, value: bool) -> Self { | |
| 1855 | + self.0.cabac_init_present_flag = value; | |
| 1856 | + self | |
| 1857 | + } | |
| 1858 | + | |
| 1859 | + pub fn num_ref_idx_l0_default_active_minus1(mut self, value: u8) -> Self { | |
| 1860 | + self.0.num_ref_idx_l0_default_active_minus1 = value; | |
| 1861 | + self | |
| 1862 | + } | |
| 1863 | + | |
| 1864 | + pub fn num_ref_idx_l1_default_active_minus1(mut self, value: u8) -> Self { | |
| 1865 | + self.0.num_ref_idx_l1_default_active_minus1 = value; | |
| 1866 | + self | |
| 1867 | + } | |
| 1868 | + | |
| 1869 | + pub fn init_qp_minus26(mut self, value: i8) -> Self { | |
| 1870 | + self.0.init_qp_minus26 = value; | |
| 1871 | + self | |
| 1872 | + } | |
| 1873 | + | |
| 1874 | + /// Sets `init_qp_minus26` from the initial SliceQpY value. | |
| 1875 | + pub fn init_qp(self, value: i8) -> Self { | |
| 1876 | + self.init_qp_minus26(value - 26) | |
| 1877 | + } | |
| 1878 | + | |
| 1879 | + pub fn constrained_intra_pred_flag(mut self, value: bool) -> Self { | |
| 1880 | + self.0.constrained_intra_pred_flag = value; | |
| 1881 | + self | |
| 1882 | + } | |
| 1883 | + | |
| 1884 | + pub fn transform_skip_enabled_flag(mut self, value: bool) -> Self { | |
| 1885 | + self.0.transform_skip_enabled_flag = value; | |
| 1886 | + self | |
| 1887 | + } | |
| 1888 | + | |
| 1889 | + pub fn cu_qp_delta_enabled_flag(mut self, value: bool) -> Self { | |
| 1890 | + self.0.cu_qp_delta_enabled_flag = value; | |
| 1891 | + self | |
| 1892 | + } | |
| 1893 | + | |
| 1894 | + pub fn diff_cu_qp_delta_depth(mut self, value: u8) -> Self { | |
| 1895 | + self.0.diff_cu_qp_delta_depth = value; | |
| 1896 | + self | |
| 1897 | + } | |
| 1898 | + | |
| 1899 | + pub fn cb_qp_offset(mut self, value: i8) -> Self { | |
| 1900 | + self.0.cb_qp_offset = value; | |
| 1901 | + self | |
| 1902 | + } | |
| 1903 | + | |
| 1904 | + pub fn cr_qp_offset(mut self, value: i8) -> Self { | |
| 1905 | + self.0.cr_qp_offset = value; | |
| 1906 | + self | |
| 1907 | + } | |
| 1908 | + | |
| 1909 | + pub fn slice_chroma_qp_offsets_present_flag(mut self, value: bool) -> Self { | |
| 1910 | + self.0.slice_chroma_qp_offsets_present_flag = value; | |
| 1911 | + self | |
| 1912 | + } | |
| 1913 | + | |
| 1914 | + pub fn weighted_pred_flag(mut self, value: bool) -> Self { | |
| 1915 | + self.0.weighted_pred_flag = value; | |
| 1916 | + self | |
| 1917 | + } | |
| 1918 | + | |
| 1919 | + pub fn weighted_bipred_flag(mut self, value: bool) -> Self { | |
| 1920 | + self.0.weighted_bipred_flag = value; | |
| 1921 | + self | |
| 1922 | + } | |
| 1923 | + | |
| 1924 | + pub fn transquant_bypass_enabled_flag(mut self, value: bool) -> Self { | |
| 1925 | + self.0.transquant_bypass_enabled_flag = value; | |
| 1926 | + self | |
| 1927 | + } | |
| 1928 | + | |
| 1929 | + pub fn entropy_coding_sync_enabled_flag(mut self, value: bool) -> Self { | |
| 1930 | + self.0.entropy_coding_sync_enabled_flag = value; | |
| 1931 | + self | |
| 1932 | + } | |
| 1933 | + | |
| 1934 | + pub fn loop_filter_across_slices_enabled_flag(mut self, value: bool) -> Self { | |
| 1935 | + self.0.loop_filter_across_slices_enabled_flag = value; | |
| 1936 | + self | |
| 1937 | + } | |
| 1938 | + | |
| 1939 | + pub fn deblocking_filter_control_present_flag(mut self, value: bool) -> Self { | |
| 1940 | + self.0.deblocking_filter_control_present_flag = value; | |
| 1941 | + self | |
| 1942 | + } | |
| 1943 | + | |
| 1944 | + pub fn deblocking_filter_override_enabled_flag(mut self, value: bool) -> Self { | |
| 1945 | + self.0.deblocking_filter_override_enabled_flag = value; | |
| 1946 | + self | |
| 1947 | + } | |
| 1948 | + | |
| 1949 | + pub fn deblocking_filter_disabled_flag(mut self, value: bool) -> Self { | |
| 1950 | + self.0.deblocking_filter_disabled_flag = value; | |
| 1951 | + self | |
| 1952 | + } | |
| 1953 | + | |
| 1954 | + /// Sets the default deblocking parameter offsets, which are only signalled | |
| 1955 | + /// when the deblocking filter is not disabled. | |
| 1956 | + pub fn deblocking_filter_offsets(mut self, beta_div2: i8, tc_div2: i8) -> Self { | |
| 1957 | + self.0.deblocking_filter_control_present_flag = true; | |
| 1958 | + self.0.beta_offset_div2 = beta_div2; | |
| 1959 | + self.0.tc_offset_div2 = tc_div2; | |
| 1960 | + self | |
| 1961 | + } | |
| 1962 | + | |
| 1963 | + /// Signals `value` in the PPS, overriding the scaling lists of the SPS. | |
| 1964 | + pub fn scaling_list(mut self, value: ScalingLists) -> Self { | |
| 1965 | + self.0.scaling_list_data_present_flag = true; | |
| 1966 | + self.0.scaling_list = value; | |
| 1967 | + self | |
| 1968 | + } | |
| 1969 | + | |
| 1970 | + pub fn lists_modification_present_flag(mut self, value: bool) -> Self { | |
| 1971 | + self.0.lists_modification_present_flag = value; | |
| 1972 | + self | |
| 1973 | + } | |
| 1974 | + | |
| 1975 | + pub fn log2_parallel_merge_level_minus2(mut self, value: u8) -> Self { | |
| 1976 | + self.0.log2_parallel_merge_level_minus2 = value; | |
| 1977 | + self | |
| 1978 | + } | |
| 1979 | + | |
| 1980 | + pub fn slice_segment_header_extension_present_flag(mut self, value: bool) -> Self { | |
| 1981 | + self.0.slice_segment_header_extension_present_flag = value; | |
| 1982 | + self | |
| 1983 | + } | |
| 1984 | + | |
| 1985 | + pub fn build(self) -> Rc<Pps> { | |
| 1986 | + Rc::new(self.0) | |
| 1987 | + } | |
| 1988 | +} | |
| 1989 | + | |
| 1331 | 1990 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 1332 | 1991 | pub struct ScalingLists { |
| 1333 | 1992 | /// plus 8 specifies the value of the variable `ScalingFactor[ 2 ][ matrixId |
vendor/cros-codecs/src/codec/h265/synthesizer.rsadded+1142 -0
| @@ -0,0 +1,1142 @@ | ||
| 1 | +// Copyright 2024 The ChromiumOS Authors | |
| 2 | +// Use of this source code is governed by a BSD-style license that can be | |
| 3 | +// found in the LICENSE file. | |
| 4 | +use std::fmt; | |
| 5 | +use std::io::Write; | |
| 6 | + | |
| 7 | +use crate::codec::h265::nalu_writer::NaluWriter; | |
| 8 | +use crate::codec::h265::nalu_writer::NaluWriterError; | |
| 9 | +use crate::codec::h265::parser::HrdParams; | |
| 10 | +use crate::codec::h265::parser::NaluType; | |
| 11 | +use crate::codec::h265::parser::Pps; | |
| 12 | +use crate::codec::h265::parser::ProfileTierLevel; | |
| 13 | +use crate::codec::h265::parser::ScalingLists; | |
| 14 | +use crate::codec::h265::parser::ShortTermRefPicSet; | |
| 15 | +use crate::codec::h265::parser::Sps; | |
| 16 | +use crate::codec::h265::parser::SublayerHrdParameters; | |
| 17 | +use crate::codec::h265::parser::Vps; | |
| 18 | + | |
| 19 | +mod private { | |
| 20 | + pub trait NaluStruct {} | |
| 21 | +} | |
| 22 | + | |
| 23 | +impl private::NaluStruct for Vps {} | |
| 24 | + | |
| 25 | +impl private::NaluStruct for Sps {} | |
| 26 | + | |
| 27 | +impl private::NaluStruct for Pps {} | |
| 28 | + | |
| 29 | +#[derive(Debug)] | |
| 30 | +pub enum SynthesizerError { | |
| 31 | + Unsupported, | |
| 32 | + NaluWriter(NaluWriterError), | |
| 33 | +} | |
| 34 | + | |
| 35 | +impl fmt::Display for SynthesizerError { | |
| 36 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
| 37 | + match self { | |
| 38 | + SynthesizerError::Unsupported => write!(f, "tried to synthesize unsupported settings"), | |
| 39 | + SynthesizerError::NaluWriter(x) => write!(f, "{}", x.to_string()), | |
| 40 | + } | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +impl From<NaluWriterError> for SynthesizerError { | |
| 45 | + fn from(err: NaluWriterError) -> Self { | |
| 46 | + SynthesizerError::NaluWriter(err) | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 50 | +pub type SynthesizerResult<T> = Result<T, SynthesizerError>; | |
| 51 | + | |
| 52 | +/// A helper to output typed NALUs to [`std::io::Write`] using [`NaluWriter`]. | |
| 53 | +pub struct Synthesizer<'n, N: private::NaluStruct, W: Write> { | |
| 54 | + writer: NaluWriter<W>, | |
| 55 | + nalu: &'n N, | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// Extended Sample Aspect Ratio - H.265 Table E.1 | |
| 59 | +const EXTENDED_SAR: u32 = 255; | |
| 60 | + | |
| 61 | +impl<N: private::NaluStruct, W: Write> Synthesizer<'_, N, W> { | |
| 62 | + fn u<T: Into<u32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { | |
| 63 | + self.writer.write_u(bits, value)?; | |
| 64 | + Ok(()) | |
| 65 | + } | |
| 66 | + | |
| 67 | + fn f<T: Into<u32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> { | |
| 68 | + self.writer.write_f(bits, value)?; | |
| 69 | + Ok(()) | |
| 70 | + } | |
| 71 | + | |
| 72 | + fn ue<T: Into<u32>>(&mut self, value: T) -> SynthesizerResult<()> { | |
| 73 | + self.writer.write_ue(value)?; | |
| 74 | + Ok(()) | |
| 75 | + } | |
| 76 | + | |
| 77 | + fn se<T: Into<i32>>(&mut self, value: T) -> SynthesizerResult<()> { | |
| 78 | + self.writer.write_se(value)?; | |
| 79 | + Ok(()) | |
| 80 | + } | |
| 81 | + | |
| 82 | + /// Writes `bits` zero bits, e.g. for the reserved fields of | |
| 83 | + /// profile_tier_level(). | |
| 84 | + fn reserved_zero_bits(&mut self, bits: usize) -> SynthesizerResult<()> { | |
| 85 | + for _ in 0..bits { | |
| 86 | + self.f(1, 0u32)?; | |
| 87 | + } | |
| 88 | + | |
| 89 | + Ok(()) | |
| 90 | + } | |
| 91 | + | |
| 92 | + fn profile_tier_level( | |
| 93 | + &mut self, | |
| 94 | + ptl: &ProfileTierLevel, | |
| 95 | + profile_present_flag: bool, | |
| 96 | + max_sub_layers_minus1: u8, | |
| 97 | + ) -> SynthesizerResult<()> { | |
| 98 | + // H.265 7.3.3 | |
| 99 | + if profile_present_flag { | |
| 100 | + self.u(2, ptl.general_profile_space)?; | |
| 101 | + self.u(1, ptl.general_tier_flag)?; | |
| 102 | + self.u(5, ptl.general_profile_idc)?; | |
| 103 | + | |
| 104 | + for i in 0..32 { | |
| 105 | + self.u(1, ptl.general_profile_compatibility_flag[i])?; | |
| 106 | + } | |
| 107 | + | |
| 108 | + self.u(1, ptl.general_progressive_source_flag)?; | |
| 109 | + self.u(1, ptl.general_interlaced_source_flag)?; | |
| 110 | + self.u(1, ptl.general_non_packed_constraint_flag)?; | |
| 111 | + self.u(1, ptl.general_frame_only_constraint_flag)?; | |
| 112 | + | |
| 113 | + if ptl.general_profile_idc == 4 | |
| 114 | + || ptl.general_profile_compatibility_flag[4] | |
| 115 | + || ptl.general_profile_idc == 5 | |
| 116 | + || ptl.general_profile_compatibility_flag[5] | |
| 117 | + || ptl.general_profile_idc == 6 | |
| 118 | + || ptl.general_profile_compatibility_flag[6] | |
| 119 | + || ptl.general_profile_idc == 7 | |
| 120 | + || ptl.general_profile_compatibility_flag[7] | |
| 121 | + || ptl.general_profile_idc == 8 | |
| 122 | + || ptl.general_profile_compatibility_flag[8] | |
| 123 | + || ptl.general_profile_idc == 9 | |
| 124 | + || ptl.general_profile_compatibility_flag[9] | |
| 125 | + || ptl.general_profile_idc == 10 | |
| 126 | + || ptl.general_profile_compatibility_flag[10] | |
| 127 | + || ptl.general_profile_idc == 11 | |
| 128 | + || ptl.general_profile_compatibility_flag[11] | |
| 129 | + { | |
| 130 | + self.u(1, ptl.general_max_12bit_constraint_flag)?; | |
| 131 | + self.u(1, ptl.general_max_10bit_constraint_flag)?; | |
| 132 | + self.u(1, ptl.general_max_8bit_constraint_flag)?; | |
| 133 | + self.u(1, ptl.general_max_422chroma_constraint_flag)?; | |
| 134 | + self.u(1, ptl.general_max_420chroma_constraint_flag)?; | |
| 135 | + self.u(1, ptl.general_max_monochrome_constraint_flag)?; | |
| 136 | + self.u(1, ptl.general_intra_constraint_flag)?; | |
| 137 | + self.u(1, ptl.general_one_picture_only_constraint_flag)?; | |
| 138 | + self.u(1, ptl.general_lower_bit_rate_constraint_flag)?; | |
| 139 | + | |
| 140 | + if ptl.general_profile_idc == 5 | |
| 141 | + || ptl.general_profile_compatibility_flag[5] | |
| 142 | + || ptl.general_profile_idc == 9 | |
| 143 | + || ptl.general_profile_compatibility_flag[9] | |
| 144 | + || ptl.general_profile_idc == 10 | |
| 145 | + || ptl.general_profile_compatibility_flag[10] | |
| 146 | + || ptl.general_profile_idc == 11 | |
| 147 | + || ptl.general_profile_compatibility_flag[11] | |
| 148 | + { | |
| 149 | + self.u(1, ptl.general_max_14bit_constraint_flag)?; | |
| 150 | + // general_reserved_zero_33bits | |
| 151 | + self.reserved_zero_bits(33)?; | |
| 152 | + } else { | |
| 153 | + // general_reserved_zero_34bits | |
| 154 | + self.reserved_zero_bits(34)?; | |
| 155 | + } | |
| 156 | + } else if ptl.general_profile_idc == 2 || ptl.general_profile_compatibility_flag[2] { | |
| 157 | + // general_reserved_zero_7bits | |
| 158 | + self.reserved_zero_bits(7)?; | |
| 159 | + self.u(1, ptl.general_one_picture_only_constraint_flag)?; | |
| 160 | + // general_reserved_zero_35bits | |
| 161 | + self.reserved_zero_bits(35)?; | |
| 162 | + } else { | |
| 163 | + // general_reserved_zero_43bits | |
| 164 | + self.reserved_zero_bits(43)?; | |
| 165 | + } | |
| 166 | + | |
| 167 | + if ptl.general_profile_idc == 1 | |
| 168 | + || ptl.general_profile_compatibility_flag[1] | |
| 169 | + || ptl.general_profile_idc == 2 | |
| 170 | + || ptl.general_profile_compatibility_flag[2] | |
| 171 | + || ptl.general_profile_idc == 3 | |
| 172 | + || ptl.general_profile_compatibility_flag[3] | |
| 173 | + || ptl.general_profile_idc == 4 | |
| 174 | + || ptl.general_profile_compatibility_flag[4] | |
| 175 | + || ptl.general_profile_idc == 5 | |
| 176 | + || ptl.general_profile_compatibility_flag[5] | |
| 177 | + || ptl.general_profile_idc == 9 | |
| 178 | + || ptl.general_profile_compatibility_flag[9] | |
| 179 | + || ptl.general_profile_idc == 11 | |
| 180 | + || ptl.general_profile_compatibility_flag[11] | |
| 181 | + { | |
| 182 | + self.u(1, ptl.general_inbld_flag)?; | |
| 183 | + } else { | |
| 184 | + // general_reserved_zero_bit | |
| 185 | + self.reserved_zero_bits(1)?; | |
| 186 | + } | |
| 187 | + } | |
| 188 | + | |
| 189 | + self.u(8, ptl.general_level_idc as u8)?; | |
| 190 | + | |
| 191 | + // Sub-layer profile and level information is not synthesized: the | |
| 192 | + // parser gates the whole sub-layer profile section on | |
| 193 | + // sub_layer_level_present_flag, so a round-trip is only possible for | |
| 194 | + // the single sub-layer case. | |
| 195 | + if max_sub_layers_minus1 > 0 { | |
| 196 | + return Err(SynthesizerError::Unsupported); | |
| 197 | + } | |
| 198 | + | |
| 199 | + Ok(()) | |
| 200 | + } | |
| 201 | + | |
| 202 | + /// Writes a single scaling list, always signalling it explicitly, i.e. with | |
| 203 | + /// `scaling_list_pred_mode_flag` equal to 1. See H.265 7.3.4. | |
| 204 | + fn scaling_list(&mut self, list: &[u8], dc_coef_minus8: Option<i16>) -> SynthesizerResult<()> { | |
| 205 | + self.u(1, /* scaling_list_pred_mode_flag */ true)?; | |
| 206 | + | |
| 207 | + let mut next_coef = 8i32; | |
| 208 | + | |
| 209 | + if let Some(dc_coef_minus8) = dc_coef_minus8 { | |
| 210 | + self.se(dc_coef_minus8)?; | |
| 211 | + next_coef = i32::from(dc_coef_minus8) + 8; | |
| 212 | + } | |
| 213 | + | |
| 214 | + for coef in list { | |
| 215 | + let coef = i32::from(*coef); | |
| 216 | + // The decoding process is (7-42), i.e. modulo 256 arithmetic, so | |
| 217 | + // the delta is normalized into the [-128, 127] range. | |
| 218 | + let delta = (coef - next_coef + 128).rem_euclid(256) - 128; | |
| 219 | + self.se(delta)?; | |
| 220 | + next_coef = coef; | |
| 221 | + } | |
| 222 | + | |
| 223 | + Ok(()) | |
| 224 | + } | |
| 225 | + | |
| 226 | + fn scaling_list_data(&mut self, sl: &ScalingLists) -> SynthesizerResult<()> { | |
| 227 | + // H.265 7.3.4 | |
| 228 | + for size_id in 0..4 { | |
| 229 | + let mut matrix_id = 0usize; | |
| 230 | + while matrix_id < 6 { | |
| 231 | + match size_id { | |
| 232 | + 0 => self.scaling_list(&sl.scaling_list_4x4[matrix_id], None)?, | |
| 233 | + 1 => self.scaling_list(&sl.scaling_list_8x8[matrix_id], None)?, | |
| 234 | + 2 => self.scaling_list( | |
| 235 | + &sl.scaling_list_16x16[matrix_id], | |
| 236 | + Some(sl.scaling_list_dc_coef_minus8_16x16[matrix_id]), | |
| 237 | + )?, | |
| 238 | + _ => self.scaling_list( | |
| 239 | + &sl.scaling_list_32x32[matrix_id], | |
| 240 | + Some(sl.scaling_list_dc_coef_minus8_32x32[matrix_id]), | |
| 241 | + )?, | |
| 242 | + } | |
| 243 | + | |
| 244 | + matrix_id += if size_id == 3 { 3 } else { 1 }; | |
| 245 | + } | |
| 246 | + } | |
| 247 | + | |
| 248 | + Ok(()) | |
| 249 | + } | |
| 250 | + | |
| 251 | + /// Writes a `st_ref_pic_set()` as an explicit list of deltas, i.e. with | |
| 252 | + /// `inter_ref_pic_set_prediction_flag` equal to 0. See H.265 7.3.7. | |
| 253 | + fn short_term_ref_pic_set( | |
| 254 | + &mut self, | |
| 255 | + st: &ShortTermRefPicSet, | |
| 256 | + st_rps_idx: u8, | |
| 257 | + ) -> SynthesizerResult<()> { | |
| 258 | + if st.inter_ref_pic_set_prediction_flag { | |
| 259 | + // The parser resolves inter RPS prediction into absolute values, so | |
| 260 | + // the original syntax elements cannot be recovered. | |
| 261 | + return Err(SynthesizerError::Unsupported); | |
| 262 | + } | |
| 263 | + | |
| 264 | + if st_rps_idx != 0 { | |
| 265 | + self.u(1, /* inter_ref_pic_set_prediction_flag */ false)?; | |
| 266 | + } | |
| 267 | + | |
| 268 | + self.ue(st.num_negative_pics)?; | |
| 269 | + self.ue(st.num_positive_pics)?; | |
| 270 | + | |
| 271 | + for i in 0..usize::from(st.num_negative_pics) { | |
| 272 | + let prev = if i == 0 { 0 } else { st.delta_poc_s0[i - 1] }; | |
| 273 | + // (7-67): DeltaPocS0[i] = DeltaPocS0[i - 1] - | |
| 274 | + // (delta_poc_s0_minus1[i] + 1) | |
| 275 | + let delta_poc_s0_minus1 = prev - st.delta_poc_s0[i] - 1; | |
| 276 | + if delta_poc_s0_minus1 < 0 { | |
| 277 | + return Err(SynthesizerError::Unsupported); | |
| 278 | + } | |
| 279 | + self.ue(delta_poc_s0_minus1 as u32)?; | |
| 280 | + self.u(1, st.used_by_curr_pic_s0[i])?; | |
| 281 | + } | |
| 282 | + | |
| 283 | + for i in 0..usize::from(st.num_positive_pics) { | |
| 284 | + let prev = if i == 0 { 0 } else { st.delta_poc_s1[i - 1] }; | |
| 285 | + // (7-68): DeltaPocS1[i] = DeltaPocS1[i - 1] + | |
| 286 | + // (delta_poc_s1_minus1[i] + 1) | |
| 287 | + let delta_poc_s1_minus1 = st.delta_poc_s1[i] - prev - 1; | |
| 288 | + if delta_poc_s1_minus1 < 0 { | |
| 289 | + return Err(SynthesizerError::Unsupported); | |
| 290 | + } | |
| 291 | + self.ue(delta_poc_s1_minus1 as u32)?; | |
| 292 | + self.u(1, st.used_by_curr_pic_s1[i])?; | |
| 293 | + } | |
| 294 | + | |
| 295 | + Ok(()) | |
| 296 | + } | |
| 297 | + | |
| 298 | + fn sub_layer_hrd_parameters( | |
| 299 | + &mut self, | |
| 300 | + hrd: &SublayerHrdParameters, | |
| 301 | + cpb_cnt: u32, | |
| 302 | + sub_pic_hrd_params_present_flag: bool, | |
| 303 | + ) -> SynthesizerResult<()> { | |
| 304 | + // H.265 E.2.3 | |
| 305 | + for i in 0..cpb_cnt as usize { | |
| 306 | + self.ue(hrd.bit_rate_value_minus1[i])?; | |
| 307 | + self.ue(hrd.cpb_size_value_minus1[i])?; | |
| 308 | + if sub_pic_hrd_params_present_flag { | |
| 309 | + self.ue(hrd.cpb_size_du_value_minus1[i])?; | |
| 310 | + self.ue(hrd.bit_rate_du_value_minus1[i])?; | |
| 311 | + } | |
| 312 | + | |
| 313 | + self.u(1, hrd.cbr_flag[i])?; | |
| 314 | + } | |
| 315 | + | |
| 316 | + Ok(()) | |
| 317 | + } | |
| 318 | + | |
| 319 | + fn hrd_parameters( | |
| 320 | + &mut self, | |
| 321 | + hrd: &HrdParams, | |
| 322 | + common_inf_present_flag: bool, | |
| 323 | + max_num_sublayers_minus1: u8, | |
| 324 | + ) -> SynthesizerResult<()> { | |
| 325 | + // H.265 E.2.2 | |
| 326 | + if common_inf_present_flag { | |
| 327 | + self.u(1, hrd.nal_hrd_parameters_present_flag)?; | |
| 328 | + self.u(1, hrd.vcl_hrd_parameters_present_flag)?; | |
| 329 | + | |
| 330 | + if hrd.nal_hrd_parameters_present_flag || hrd.vcl_hrd_parameters_present_flag { | |
| 331 | + self.u(1, hrd.sub_pic_hrd_params_present_flag)?; | |
| 332 | + if hrd.sub_pic_hrd_params_present_flag { | |
| 333 | + self.u(8, hrd.tick_divisor_minus2)?; | |
| 334 | + self.u(5, hrd.du_cpb_removal_delay_increment_length_minus1)?; | |
| 335 | + self.u(1, hrd.sub_pic_cpb_params_in_pic_timing_sei_flag)?; | |
| 336 | + self.u(5, hrd.dpb_output_delay_du_length_minus1)?; | |
| 337 | + } | |
| 338 | + | |
| 339 | + self.u(4, hrd.bit_rate_scale)?; | |
| 340 | + self.u(4, hrd.cpb_size_scale)?; | |
| 341 | + if hrd.sub_pic_hrd_params_present_flag { | |
| 342 | + self.u(4, hrd.cpb_size_du_scale)?; | |
| 343 | + } | |
| 344 | + | |
| 345 | + self.u(5, hrd.initial_cpb_removal_delay_length_minus1)?; | |
| 346 | + self.u(5, hrd.au_cpb_removal_delay_length_minus1)?; | |
| 347 | + self.u(5, hrd.dpb_output_delay_length_minus1)?; | |
| 348 | + } | |
| 349 | + } | |
| 350 | + | |
| 351 | + for i in 0..=usize::from(max_num_sublayers_minus1) { | |
| 352 | + self.u(1, hrd.fixed_pic_rate_general_flag[i])?; | |
| 353 | + if !hrd.fixed_pic_rate_general_flag[i] { | |
| 354 | + self.u(1, hrd.fixed_pic_rate_within_cvs_flag[i])?; | |
| 355 | + } | |
| 356 | + | |
| 357 | + if hrd.fixed_pic_rate_within_cvs_flag[i] { | |
| 358 | + self.ue(hrd.elemental_duration_in_tc_minus1[i])?; | |
| 359 | + } else { | |
| 360 | + self.u(1, hrd.low_delay_hrd_flag[i])?; | |
| 361 | + } | |
| 362 | + | |
| 363 | + if !hrd.low_delay_hrd_flag[i] { | |
| 364 | + self.ue(hrd.cpb_cnt_minus1[i])?; | |
| 365 | + } | |
| 366 | + | |
| 367 | + if hrd.nal_hrd_parameters_present_flag { | |
| 368 | + self.sub_layer_hrd_parameters( | |
| 369 | + &hrd.nal_hrd[i], | |
| 370 | + hrd.cpb_cnt_minus1[i] + 1, | |
| 371 | + hrd.sub_pic_hrd_params_present_flag, | |
| 372 | + )?; | |
| 373 | + } | |
| 374 | + | |
| 375 | + if hrd.vcl_hrd_parameters_present_flag { | |
| 376 | + self.sub_layer_hrd_parameters( | |
| 377 | + &hrd.vcl_hrd[i], | |
| 378 | + hrd.cpb_cnt_minus1[i] + 1, | |
| 379 | + hrd.sub_pic_hrd_params_present_flag, | |
| 380 | + )?; | |
| 381 | + } | |
| 382 | + } | |
| 383 | + | |
| 384 | + Ok(()) | |
| 385 | + } | |
| 386 | + | |
| 387 | + fn rbsp_trailing_bits(&mut self) -> SynthesizerResult<()> { | |
| 388 | + self.f(1, 1u32)?; | |
| 389 | + | |
| 390 | + while !self.writer.aligned() { | |
| 391 | + self.f(1, 0u32)?; | |
| 392 | + } | |
| 393 | + | |
| 394 | + Ok(()) | |
| 395 | + } | |
| 396 | +} | |
| 397 | + | |
| 398 | +impl<'n, W: Write> Synthesizer<'n, Vps, W> { | |
| 399 | + /// Writes a VPS NALU with the given `nuh_temporal_id_plus1`. `nuh_layer_id` | |
| 400 | + /// is always zero, as multi-layer coding is not supported. | |
| 401 | + pub fn synthesize( | |
| 402 | + nuh_temporal_id_plus1: u8, | |
| 403 | + vps: &'n Vps, | |
| 404 | + writer: W, | |
| 405 | + ep_enabled: bool, | |
| 406 | + ) -> SynthesizerResult<()> { | |
| 407 | + let mut s = Self { writer: NaluWriter::<W>::new(writer, ep_enabled), nalu: vps }; | |
| 408 | + | |
| 409 | + s.writer.write_header(NaluType::VpsNut as u8, 0, nuh_temporal_id_plus1)?; | |
| 410 | + s.video_parameter_set_rbsp()?; | |
| 411 | + s.rbsp_trailing_bits() | |
| 412 | + } | |
| 413 | + | |
| 414 | + fn video_parameter_set_rbsp(&mut self) -> SynthesizerResult<()> { | |
| 415 | + // H.265 7.3.2.1 | |
| 416 | + self.u(4, self.nalu.video_parameter_set_id)?; | |
| 417 | + self.u(1, self.nalu.base_layer_internal_flag)?; | |
| 418 | + self.u(1, self.nalu.base_layer_available_flag)?; | |
| 419 | + self.u(6, self.nalu.max_layers_minus1)?; | |
| 420 | + self.u(3, self.nalu.max_sub_layers_minus1)?; | |
| 421 | + self.u(1, self.nalu.temporal_id_nesting_flag)?; | |
| 422 | + self.f(16, /* vps_reserved_0xffff_16bits */ 0xffffu32)?; | |
| 423 | + | |
| 424 | + self.profile_tier_level( | |
| 425 | + &self.nalu.profile_tier_level, | |
| 426 | + true, | |
| 427 | + self.nalu.max_sub_layers_minus1, | |
| 428 | + )?; | |
| 429 | + | |
| 430 | + self.u(1, self.nalu.sub_layer_ordering_info_present_flag)?; | |
| 431 | + | |
| 432 | + let start = if self.nalu.sub_layer_ordering_info_present_flag { | |
| 433 | + 0 | |
| 434 | + } else { | |
| 435 | + self.nalu.max_sub_layers_minus1 | |
| 436 | + }; | |
| 437 | + | |
| 438 | + for i in usize::from(start)..=usize::from(self.nalu.max_sub_layers_minus1) { | |
| 439 | + self.ue(self.nalu.max_dec_pic_buffering_minus1[i])?; | |
| 440 | + self.ue(self.nalu.max_num_reorder_pics[i])?; | |
| 441 | + self.ue(self.nalu.max_latency_increase_plus1[i])?; | |
| 442 | + } | |
| 443 | + | |
| 444 | + self.u(6, self.nalu.max_layer_id)?; | |
| 445 | + self.ue(self.nalu.num_layer_sets_minus1)?; | |
| 446 | + | |
| 447 | + for _ in 1..=self.nalu.num_layer_sets_minus1 { | |
| 448 | + for _ in 0..=self.nalu.max_layer_id { | |
| 449 | + // The parser discards layer_id_included_flag[i][j]. | |
| 450 | + self.u(1, /* layer_id_included_flag */ false)?; | |
| 451 | + } | |
| 452 | + } | |
| 453 | + | |
| 454 | + self.u(1, self.nalu.timing_info_present_flag)?; | |
| 455 | + if self.nalu.timing_info_present_flag { | |
| 456 | + self.u(32, self.nalu.num_units_in_tick)?; | |
| 457 | + self.u(32, self.nalu.time_scale)?; | |
| 458 | + | |
| 459 | + self.u(1, self.nalu.poc_proportional_to_timing_flag)?; | |
| 460 | + if self.nalu.poc_proportional_to_timing_flag { | |
| 461 | + self.ue(self.nalu.num_ticks_poc_diff_one_minus1)?; | |
| 462 | + } | |
| 463 | + | |
| 464 | + self.ue(self.nalu.num_hrd_parameters)?; | |
| 465 | + | |
| 466 | + for i in 0..self.nalu.num_hrd_parameters as usize { | |
| 467 | + self.ue(self.nalu.hrd_layer_set_idx[i])?; | |
| 468 | + if i > 0 { | |
| 469 | + self.u(1, self.nalu.cprms_present_flag[i])?; | |
| 470 | + } | |
| 471 | + | |
| 472 | + self.hrd_parameters( | |
| 473 | + &self.nalu.hrd_parameters[i], | |
| 474 | + self.nalu.cprms_present_flag[i], | |
| 475 | + self.nalu.max_sub_layers_minus1, | |
| 476 | + )?; | |
| 477 | + } | |
| 478 | + } | |
| 479 | + | |
| 480 | + if self.nalu.extension_flag { | |
| 481 | + // vps_extension_data_flag is not retained by the parser. | |
| 482 | + return Err(SynthesizerError::Unsupported); | |
| 483 | + } | |
| 484 | + | |
| 485 | + self.u(1, /* vps_extension_flag */ false)?; | |
| 486 | + | |
| 487 | + Ok(()) | |
| 488 | + } | |
| 489 | +} | |
| 490 | + | |
| 491 | +impl<'n, W: Write> Synthesizer<'n, Sps, W> { | |
| 492 | + /// Writes a SPS NALU with the given `nuh_temporal_id_plus1`. `nuh_layer_id` | |
| 493 | + /// is always zero, as multi-layer coding is not supported. | |
| 494 | + pub fn synthesize( | |
| 495 | + nuh_temporal_id_plus1: u8, | |
| 496 | + sps: &'n Sps, | |
| 497 | + writer: W, | |
| 498 | + ep_enabled: bool, | |
| 499 | + ) -> SynthesizerResult<()> { | |
| 500 | + let mut s = Self { writer: NaluWriter::<W>::new(writer, ep_enabled), nalu: sps }; | |
| 501 | + | |
| 502 | + s.writer.write_header(NaluType::SpsNut as u8, 0, nuh_temporal_id_plus1)?; | |
| 503 | + s.seq_parameter_set_rbsp()?; | |
| 504 | + s.rbsp_trailing_bits() | |
| 505 | + } | |
| 506 | + | |
| 507 | + fn vui_parameters(&mut self) -> SynthesizerResult<()> { | |
| 508 | + // H.265 E.2.1 | |
| 509 | + let vui = &self.nalu.vui_parameters; | |
| 510 | + | |
| 511 | + self.u(1, vui.aspect_ratio_info_present_flag)?; | |
| 512 | + if vui.aspect_ratio_info_present_flag { | |
| 513 | + self.u(8, vui.aspect_ratio_idc)?; | |
| 514 | + if vui.aspect_ratio_idc == EXTENDED_SAR { | |
| 515 | + self.u(16, vui.sar_width)?; | |
| 516 | + self.u(16, vui.sar_height)?; | |
| 517 | + } | |
| 518 | + } | |
| 519 | + | |
| 520 | + self.u(1, vui.overscan_info_present_flag)?; | |
| 521 | + if vui.overscan_info_present_flag { | |
| 522 | + self.u(1, vui.overscan_appropriate_flag)?; | |
| 523 | + } | |
| 524 | + | |
| 525 | + self.u(1, vui.video_signal_type_present_flag)?; | |
| 526 | + if vui.video_signal_type_present_flag { | |
| 527 | + self.u(3, vui.video_format)?; | |
| 528 | + self.u(1, vui.video_full_range_flag)?; | |
| 529 | + self.u(1, vui.colour_description_present_flag)?; | |
| 530 | + if vui.colour_description_present_flag { | |
| 531 | + self.u(8, vui.colour_primaries)?; | |
| 532 | + self.u(8, vui.transfer_characteristics)?; | |
| 533 | + self.u(8, vui.matrix_coeffs)?; | |
| 534 | + } | |
| 535 | + } | |
| 536 | + | |
| 537 | + self.u(1, vui.chroma_loc_info_present_flag)?; | |
| 538 | + if vui.chroma_loc_info_present_flag { | |
| 539 | + self.ue(vui.chroma_sample_loc_type_top_field)?; | |
| 540 | + self.ue(vui.chroma_sample_loc_type_bottom_field)?; | |
| 541 | + } | |
| 542 | + | |
| 543 | + self.u(1, vui.neutral_chroma_indication_flag)?; | |
| 544 | + self.u(1, vui.field_seq_flag)?; | |
| 545 | + self.u(1, vui.frame_field_info_present_flag)?; | |
| 546 | + | |
| 547 | + self.u(1, vui.default_display_window_flag)?; | |
| 548 | + if vui.default_display_window_flag { | |
| 549 | + self.ue(vui.def_disp_win_left_offset)?; | |
| 550 | + self.ue(vui.def_disp_win_right_offset)?; | |
| 551 | + self.ue(vui.def_disp_win_top_offset)?; | |
| 552 | + self.ue(vui.def_disp_win_bottom_offset)?; | |
| 553 | + } | |
| 554 | + | |
| 555 | + self.u(1, vui.timing_info_present_flag)?; | |
| 556 | + if vui.timing_info_present_flag { | |
| 557 | + self.u(32, vui.num_units_in_tick)?; | |
| 558 | + self.u(32, vui.time_scale)?; | |
| 559 | + | |
| 560 | + self.u(1, vui.poc_proportional_to_timing_flag)?; | |
| 561 | + if vui.poc_proportional_to_timing_flag { | |
| 562 | + self.ue(vui.num_ticks_poc_diff_one_minus1)?; | |
| 563 | + } | |
| 564 | + | |
| 565 | + self.u(1, vui.hrd_parameters_present_flag)?; | |
| 566 | + if vui.hrd_parameters_present_flag { | |
| 567 | + self.hrd_parameters(&vui.hrd, true, self.nalu.max_sub_layers_minus1)?; | |
| 568 | + } | |
| 569 | + } | |
| 570 | + | |
| 571 | + self.u(1, vui.bitstream_restriction_flag)?; | |
| 572 | + if vui.bitstream_restriction_flag { | |
| 573 | + self.u(1, vui.tiles_fixed_structure_flag)?; | |
| 574 | + self.u(1, vui.motion_vectors_over_pic_boundaries_flag)?; | |
| 575 | + self.u(1, vui.restricted_ref_pic_lists_flag)?; | |
| 576 | + self.ue(vui.min_spatial_segmentation_idc)?; | |
| 577 | + self.ue(vui.max_bytes_per_pic_denom)?; | |
| 578 | + self.ue(vui.max_bits_per_min_cu_denom)?; | |
| 579 | + self.ue(vui.log2_max_mv_length_horizontal)?; | |
| 580 | + self.ue(vui.log2_max_mv_length_vertical)?; | |
| 581 | + } | |
| 582 | + | |
| 583 | + Ok(()) | |
| 584 | + } | |
| 585 | + | |
| 586 | + fn sps_range_extension(&mut self) -> SynthesizerResult<()> { | |
| 587 | + // H.265 7.3.2.2.2 | |
| 588 | + let ext = &self.nalu.range_extension; | |
| 589 | + | |
| 590 | + self.u(1, ext.transform_skip_rotation_enabled_flag)?; | |
| 591 | + self.u(1, ext.transform_skip_context_enabled_flag)?; | |
| 592 | + self.u(1, ext.implicit_rdpcm_enabled_flag)?; | |
| 593 | + self.u(1, ext.explicit_rdpcm_enabled_flag)?; | |
| 594 | + self.u(1, ext.extended_precision_processing_flag)?; | |
| 595 | + self.u(1, ext.intra_smoothing_disabled_flag)?; | |
| 596 | + self.u(1, ext.high_precision_offsets_enabled_flag)?; | |
| 597 | + self.u(1, ext.persistent_rice_adaptation_enabled_flag)?; | |
| 598 | + self.u(1, ext.cabac_bypass_alignment_enabled_flag)?; | |
| 599 | + | |
| 600 | + Ok(()) | |
| 601 | + } | |
| 602 | + | |
| 603 | + fn seq_parameter_set_rbsp(&mut self) -> SynthesizerResult<()> { | |
| 604 | + // H.265 7.3.2.2.1 | |
| 605 | + self.u(4, self.nalu.video_parameter_set_id)?; | |
| 606 | + self.u(3, self.nalu.max_sub_layers_minus1)?; | |
| 607 | + self.u(1, self.nalu.temporal_id_nesting_flag)?; | |
| 608 | + | |
| 609 | + self.profile_tier_level( | |
| 610 | + &self.nalu.profile_tier_level, | |
| 611 | + true, | |
| 612 | + self.nalu.max_sub_layers_minus1, | |
| 613 | + )?; | |
| 614 | + | |
| 615 | + self.ue(self.nalu.seq_parameter_set_id)?; | |
| 616 | + self.ue(self.nalu.chroma_format_idc)?; | |
| 617 | + if self.nalu.chroma_format_idc == 3 { | |
| 618 | + self.u(1, self.nalu.separate_colour_plane_flag)?; | |
| 619 | + } | |
| 620 | + | |
| 621 | + self.ue(self.nalu.pic_width_in_luma_samples)?; | |
| 622 | + self.ue(self.nalu.pic_height_in_luma_samples)?; | |
| 623 | + | |
| 624 | + self.u(1, self.nalu.conformance_window_flag)?; | |
| 625 | + if self.nalu.conformance_window_flag { | |
| 626 | + self.ue(self.nalu.conf_win_left_offset)?; | |
| 627 | + self.ue(self.nalu.conf_win_right_offset)?; | |
| 628 | + self.ue(self.nalu.conf_win_top_offset)?; | |
| 629 | + self.ue(self.nalu.conf_win_bottom_offset)?; | |
| 630 | + } | |
| 631 | + | |
| 632 | + self.ue(self.nalu.bit_depth_luma_minus8)?; | |
| 633 | + self.ue(self.nalu.bit_depth_chroma_minus8)?; | |
| 634 | + self.ue(self.nalu.log2_max_pic_order_cnt_lsb_minus4)?; | |
| 635 | + | |
| 636 | + self.u(1, self.nalu.sub_layer_ordering_info_present_flag)?; | |
| 637 | + | |
| 638 | + let start = if self.nalu.sub_layer_ordering_info_present_flag { | |
| 639 | + 0 | |
| 640 | + } else { | |
| 641 | + self.nalu.max_sub_layers_minus1 | |
| 642 | + }; | |
| 643 | + | |
| 644 | + for i in usize::from(start)..=usize::from(self.nalu.max_sub_layers_minus1) { | |
| 645 | + self.ue(self.nalu.max_dec_pic_buffering_minus1[i])?; | |
| 646 | + self.ue(self.nalu.max_num_reorder_pics[i])?; | |
| 647 | + self.ue(self.nalu.max_latency_increase_plus1[i])?; | |
| 648 | + } | |
| 649 | + | |
| 650 | + self.ue(self.nalu.log2_min_luma_coding_block_size_minus3)?; | |
| 651 | + self.ue(self.nalu.log2_diff_max_min_luma_coding_block_size)?; | |
| 652 | + self.ue(self.nalu.log2_min_luma_transform_block_size_minus2)?; | |
| 653 | + self.ue(self.nalu.log2_diff_max_min_luma_transform_block_size)?; | |
| 654 | + self.ue(self.nalu.max_transform_hierarchy_depth_inter)?; | |
| 655 | + self.ue(self.nalu.max_transform_hierarchy_depth_intra)?; | |
| 656 | + | |
| 657 | + self.u(1, self.nalu.scaling_list_enabled_flag)?; | |
| 658 | + if self.nalu.scaling_list_enabled_flag { | |
| 659 | + self.u(1, self.nalu.scaling_list_data_present_flag)?; | |
| 660 | + if self.nalu.scaling_list_data_present_flag { | |
| 661 | + self.scaling_list_data(&self.nalu.scaling_list)?; | |
| 662 | + } | |
| 663 | + } | |
| 664 | + | |
| 665 | + self.u(1, self.nalu.amp_enabled_flag)?; | |
| 666 | + self.u(1, self.nalu.sample_adaptive_offset_enabled_flag)?; | |
| 667 | + | |
| 668 | + self.u(1, self.nalu.pcm_enabled_flag)?; | |
| 669 | + if self.nalu.pcm_enabled_flag { | |
| 670 | + self.u(4, self.nalu.pcm_sample_bit_depth_luma_minus1)?; | |
| 671 | + self.u(4, self.nalu.pcm_sample_bit_depth_chroma_minus1)?; | |
| 672 | + self.ue(self.nalu.log2_min_pcm_luma_coding_block_size_minus3)?; | |
| 673 | + self.ue(self.nalu.log2_diff_max_min_pcm_luma_coding_block_size)?; | |
| 674 | + self.u(1, self.nalu.pcm_loop_filter_disabled_flag)?; | |
| 675 | + } | |
| 676 | + | |
| 677 | + self.ue(self.nalu.num_short_term_ref_pic_sets)?; | |
| 678 | + for i in 0..usize::from(self.nalu.num_short_term_ref_pic_sets) { | |
| 679 | + let st = | |
| 680 | + self.nalu.short_term_ref_pic_set.get(i).ok_or(SynthesizerError::Unsupported)?; | |
| 681 | + self.short_term_ref_pic_set(st, i as u8)?; | |
| 682 | + } | |
| 683 | + | |
| 684 | + self.u(1, self.nalu.long_term_ref_pics_present_flag)?; | |
| 685 | + if self.nalu.long_term_ref_pics_present_flag { | |
| 686 | + self.ue(self.nalu.num_long_term_ref_pics_sps)?; | |
| 687 | + | |
| 688 | + let bits = usize::from(self.nalu.log2_max_pic_order_cnt_lsb_minus4) + 4; | |
| 689 | + for i in 0..usize::from(self.nalu.num_long_term_ref_pics_sps) { | |
| 690 | + self.u(bits, self.nalu.lt_ref_pic_poc_lsb_sps[i])?; | |
| 691 | + self.u(1, self.nalu.used_by_curr_pic_lt_sps_flag[i])?; | |
| 692 | + } | |
| 693 | + } | |
| 694 | + | |
| 695 | + self.u(1, self.nalu.temporal_mvp_enabled_flag)?; | |
| 696 | + self.u(1, self.nalu.strong_intra_smoothing_enabled_flag)?; | |
| 697 | + | |
| 698 | + self.u(1, self.nalu.vui_parameters_present_flag)?; | |
| 699 | + if self.nalu.vui_parameters_present_flag { | |
| 700 | + self.vui_parameters()?; | |
| 701 | + } | |
| 702 | + | |
| 703 | + self.u(1, self.nalu.extension_present_flag)?; | |
| 704 | + if self.nalu.extension_present_flag { | |
| 705 | + if self.nalu.scc_extension_flag { | |
| 706 | + // The screen content coding extension is out of scope. | |
| 707 | + return Err(SynthesizerError::Unsupported); | |
| 708 | + } | |
| 709 | + | |
| 710 | + self.u(1, self.nalu.range_extension_flag)?; | |
| 711 | + if self.nalu.range_extension_flag { | |
| 712 | + self.sps_range_extension()?; | |
| 713 | + } | |
| 714 | + | |
| 715 | + self.u(1, /* sps_multilayer_extension_flag */ false)?; | |
| 716 | + self.u(1, /* sps_3d_extension_flag */ false)?; | |
| 717 | + self.u(1, /* sps_scc_extension_flag */ false)?; | |
| 718 | + self.u(4, /* sps_extension_4bits */ 0u32)?; | |
| 719 | + } | |
| 720 | + | |
| 721 | + Ok(()) | |
| 722 | + } | |
| 723 | +} | |
| 724 | + | |
| 725 | +impl<'n, W: Write> Synthesizer<'n, Pps, W> { | |
| 726 | + /// Writes a PPS NALU with the given `nuh_temporal_id_plus1`. `nuh_layer_id` | |
| 727 | + /// is always zero, as multi-layer coding is not supported. | |
| 728 | + pub fn synthesize( | |
| 729 | + nuh_temporal_id_plus1: u8, | |
| 730 | + pps: &'n Pps, | |
| 731 | + writer: W, | |
| 732 | + ep_enabled: bool, | |
| 733 | + ) -> SynthesizerResult<()> { | |
| 734 | + let mut s = Self { writer: NaluWriter::<W>::new(writer, ep_enabled), nalu: pps }; | |
| 735 | + | |
| 736 | + s.writer.write_header(NaluType::PpsNut as u8, 0, nuh_temporal_id_plus1)?; | |
| 737 | + s.pic_parameter_set_rbsp()?; | |
| 738 | + s.rbsp_trailing_bits() | |
| 739 | + } | |
| 740 | + | |
| 741 | + fn pps_range_extension(&mut self) -> SynthesizerResult<()> { | |
| 742 | + // H.265 7.3.2.3.2 | |
| 743 | + let ext = &self.nalu.range_extension; | |
| 744 | + | |
| 745 | + if self.nalu.transform_skip_enabled_flag { | |
| 746 | + self.ue(ext.log2_max_transform_skip_block_size_minus2)?; | |
| 747 | + } | |
| 748 | + | |
| 749 | + self.u(1, ext.cross_component_prediction_enabled_flag)?; | |
| 750 | + self.u(1, ext.chroma_qp_offset_list_enabled_flag)?; | |
| 751 | + if ext.chroma_qp_offset_list_enabled_flag { | |
| 752 | + self.ue(ext.diff_cu_chroma_qp_offset_depth)?; | |
| 753 | + self.ue(ext.chroma_qp_offset_list_len_minus1)?; | |
| 754 | + for i in 0..=ext.chroma_qp_offset_list_len_minus1 as usize { | |
| 755 | + self.se(ext.cb_qp_offset_list[i])?; | |
| 756 | + self.se(ext.cr_qp_offset_list[i])?; | |
| 757 | + } | |
| 758 | + } | |
| 759 | + | |
| 760 | + self.ue(ext.log2_sao_offset_scale_luma)?; | |
| 761 | + self.ue(ext.log2_sao_offset_scale_chroma)?; | |
| 762 | + | |
| 763 | + Ok(()) | |
| 764 | + } | |
| 765 | + | |
| 766 | + fn pic_parameter_set_rbsp(&mut self) -> SynthesizerResult<()> { | |
| 767 | + // H.265 7.3.2.3.1 | |
| 768 | + self.ue(self.nalu.pic_parameter_set_id)?; | |
| 769 | + self.ue(self.nalu.seq_parameter_set_id)?; | |
| 770 | + self.u(1, self.nalu.dependent_slice_segments_enabled_flag)?; | |
| 771 | + self.u(1, self.nalu.output_flag_present_flag)?; | |
| 772 | + self.u(3, self.nalu.num_extra_slice_header_bits)?; | |
| 773 | + self.u(1, self.nalu.sign_data_hiding_enabled_flag)?; | |
| 774 | + self.u(1, self.nalu.cabac_init_present_flag)?; | |
| 775 | + self.ue(self.nalu.num_ref_idx_l0_default_active_minus1)?; | |
| 776 | + self.ue(self.nalu.num_ref_idx_l1_default_active_minus1)?; | |
| 777 | + self.se(self.nalu.init_qp_minus26)?; | |
| 778 | + self.u(1, self.nalu.constrained_intra_pred_flag)?; | |
| 779 | + self.u(1, self.nalu.transform_skip_enabled_flag)?; | |
| 780 | + | |
| 781 | + self.u(1, self.nalu.cu_qp_delta_enabled_flag)?; | |
| 782 | + if self.nalu.cu_qp_delta_enabled_flag { | |
| 783 | + self.ue(self.nalu.diff_cu_qp_delta_depth)?; | |
| 784 | + } | |
| 785 | + | |
| 786 | + self.se(self.nalu.cb_qp_offset)?; | |
| 787 | + self.se(self.nalu.cr_qp_offset)?; | |
| 788 | + self.u(1, self.nalu.slice_chroma_qp_offsets_present_flag)?; | |
| 789 | + self.u(1, self.nalu.weighted_pred_flag)?; | |
| 790 | + self.u(1, self.nalu.weighted_bipred_flag)?; | |
| 791 | + self.u(1, self.nalu.transquant_bypass_enabled_flag)?; | |
| 792 | + self.u(1, self.nalu.tiles_enabled_flag)?; | |
| 793 | + self.u(1, self.nalu.entropy_coding_sync_enabled_flag)?; | |
| 794 | + | |
| 795 | + if self.nalu.tiles_enabled_flag { | |
| 796 | + if !self.nalu.uniform_spacing_flag { | |
| 797 | + // The parser consumes column_width_minus1 and row_height_minus1 | |
| 798 | + // to derive the tile layout, so the original values cannot be | |
| 799 | + // recovered. | |
| 800 | + return Err(SynthesizerError::Unsupported); | |
| 801 | + } | |
| 802 | + | |
| 803 | + self.ue(self.nalu.num_tile_columns_minus1)?; | |
| 804 | + self.ue(self.nalu.num_tile_rows_minus1)?; | |
| 805 | + self.u(1, /* uniform_spacing_flag */ true)?; | |
| 806 | + self.u(1, self.nalu.loop_filter_across_tiles_enabled_flag)?; | |
| 807 | + } | |
| 808 | + | |
| 809 | + self.u(1, self.nalu.loop_filter_across_slices_enabled_flag)?; | |
| 810 | + | |
| 811 | + self.u(1, self.nalu.deblocking_filter_control_present_flag)?; | |
| 812 | + if self.nalu.deblocking_filter_control_present_flag { | |
| 813 | + self.u(1, self.nalu.deblocking_filter_override_enabled_flag)?; | |
| 814 | + self.u(1, self.nalu.deblocking_filter_disabled_flag)?; | |
| 815 | + if !self.nalu.deblocking_filter_disabled_flag { | |
| 816 | + self.se(self.nalu.beta_offset_div2)?; | |
| 817 | + self.se(self.nalu.tc_offset_div2)?; | |
| 818 | + } | |
| 819 | + } | |
| 820 | + | |
| 821 | + self.u(1, self.nalu.scaling_list_data_present_flag)?; | |
| 822 | + if self.nalu.scaling_list_data_present_flag { | |
| 823 | + self.scaling_list_data(&self.nalu.scaling_list)?; | |
| 824 | + } | |
| 825 | + | |
| 826 | + self.u(1, self.nalu.lists_modification_present_flag)?; | |
| 827 | + self.ue(self.nalu.log2_parallel_merge_level_minus2)?; | |
| 828 | + self.u(1, self.nalu.slice_segment_header_extension_present_flag)?; | |
| 829 | + | |
| 830 | + self.u(1, self.nalu.extension_present_flag)?; | |
| 831 | + if self.nalu.extension_present_flag { | |
| 832 | + if self.nalu.scc_extension_flag { | |
| 833 | + // The screen content coding extension is out of scope. | |
| 834 | + return Err(SynthesizerError::Unsupported); | |
| 835 | + } | |
| 836 | + | |
| 837 | + self.u(1, self.nalu.range_extension_flag)?; | |
| 838 | + if self.nalu.range_extension_flag { | |
| 839 | + self.pps_range_extension()?; | |
| 840 | + } | |
| 841 | + | |
| 842 | + self.u(1, /* pps_multilayer_extension_flag */ false)?; | |
| 843 | + self.u(1, /* pps_3d_extension_flag */ false)?; | |
| 844 | + self.u(1, /* pps_scc_extension_flag */ false)?; | |
| 845 | + self.u(4, /* pps_extension_4bits */ 0u32)?; | |
| 846 | + } | |
| 847 | + | |
| 848 | + Ok(()) | |
| 849 | + } | |
| 850 | +} | |
| 851 | + | |
| 852 | +#[cfg(test)] | |
| 853 | +mod tests { | |
| 854 | + use std::io::Cursor; | |
| 855 | + use std::rc::Rc; | |
| 856 | + | |
| 857 | + use super::*; | |
| 858 | + use crate::codec::h265::parser::Level; | |
| 859 | + use crate::codec::h265::parser::Nalu; | |
| 860 | + use crate::codec::h265::parser::Parser; | |
| 861 | + use crate::codec::h265::parser::PpsBuilder; | |
| 862 | + use crate::codec::h265::parser::Profile; | |
| 863 | + use crate::codec::h265::parser::ShortTermRefPicSet; | |
| 864 | + use crate::codec::h265::parser::SpsBuilder; | |
| 865 | + use crate::codec::h265::parser::VpsBuilder; | |
| 866 | + | |
| 867 | + /// Synthesizes `vps`, `sps` and `pps` into a single Annex B buffer, parses | |
| 868 | + /// it back and returns the parsed structures. | |
| 869 | + fn roundtrip( | |
| 870 | + vps: &Vps, | |
| 871 | + sps: &Sps, | |
| 872 | + pps: &Pps, | |
| 873 | + ep_enabled: bool, | |
| 874 | + ) -> (Vec<u8>, Rc<Vps>, Rc<Sps>, Rc<Pps>) { | |
| 875 | + let mut buf = Vec::<u8>::new(); | |
| 876 | + | |
| 877 | + Synthesizer::<'_, Vps, _>::synthesize(1, vps, &mut buf, ep_enabled).unwrap(); | |
| 878 | + Synthesizer::<'_, Sps, _>::synthesize(1, sps, &mut buf, ep_enabled).unwrap(); | |
| 879 | + Synthesizer::<'_, Pps, _>::synthesize(1, pps, &mut buf, ep_enabled).unwrap(); | |
| 880 | + | |
| 881 | + let mut cursor = Cursor::new(&buf[..]); | |
| 882 | + let mut parser = Parser::default(); | |
| 883 | + | |
| 884 | + let nalu = Nalu::next(&mut cursor).unwrap(); | |
| 885 | + let vps = Rc::new(parser.parse_vps(&nalu).unwrap().clone()); | |
| 886 | + | |
| 887 | + let nalu = Nalu::next(&mut cursor).unwrap(); | |
| 888 | + let sps = Rc::new(parser.parse_sps(&nalu).unwrap().clone()); | |
| 889 | + | |
| 890 | + let nalu = Nalu::next(&mut cursor).unwrap(); | |
| 891 | + let pps = Rc::new(parser.parse_pps(&nalu).unwrap().clone()); | |
| 892 | + | |
| 893 | + (buf, vps, sps, pps) | |
| 894 | + } | |
| 895 | + | |
| 896 | + fn default_vps() -> Rc<Vps> { | |
| 897 | + VpsBuilder::new() | |
| 898 | + .video_parameter_set_id(0) | |
| 899 | + .general_profile(Profile::Main) | |
| 900 | + .general_level_idc(Level::L4) | |
| 901 | + .max_dec_pic_buffering_minus1(1) | |
| 902 | + .max_num_reorder_pics(0) | |
| 903 | + .build() | |
| 904 | + } | |
| 905 | + | |
| 906 | + fn default_sps(vps: Rc<Vps>) -> Rc<Sps> { | |
| 907 | + SpsBuilder::new(vps) | |
| 908 | + .seq_parameter_set_id(0) | |
| 909 | + .resolution(1920, 1080) | |
| 910 | + .max_dec_pic_buffering_minus1(1) | |
| 911 | + .max_num_reorder_pics(0) | |
| 912 | + .amp_enabled_flag(true) | |
| 913 | + .sample_adaptive_offset_enabled_flag(true) | |
| 914 | + .temporal_mvp_enabled_flag(true) | |
| 915 | + .strong_intra_smoothing_enabled_flag(true) | |
| 916 | + .build() | |
| 917 | + } | |
| 918 | + | |
| 919 | + #[test] | |
| 920 | + fn synthesize_vps_sps_pps() { | |
| 921 | + let vps = default_vps(); | |
| 922 | + let sps = default_sps(Rc::clone(&vps)); | |
| 923 | + let pps = PpsBuilder::new(Rc::clone(&sps)) | |
| 924 | + .pic_parameter_set_id(0) | |
| 925 | + .init_qp_minus26(0) | |
| 926 | + .cu_qp_delta_enabled_flag(true) | |
| 927 | + .deblocking_filter_control_present_flag(true) | |
| 928 | + .build(); | |
| 929 | + | |
| 930 | + let (_, vps2, sps2, pps2) = roundtrip(&vps, &sps, &pps, true); | |
| 931 | + | |
| 932 | + assert_eq!(*vps, *vps2); | |
| 933 | + assert_eq!(*sps, *sps2); | |
| 934 | + assert_eq!(*pps, *pps2); | |
| 935 | + } | |
| 936 | + | |
| 937 | + /// The conformance window must compensate for the coded size being aligned | |
| 938 | + /// to the minimum coding block size. | |
| 939 | + #[test] | |
| 940 | + fn synthesize_sps_conformance_window() { | |
| 941 | + let vps = default_vps(); | |
| 942 | + let sps = SpsBuilder::new(Rc::clone(&vps)).resolution(1920, 1082).build(); | |
| 943 | + | |
| 944 | + assert_eq!(sps.pic_height_in_luma_samples, 1088); | |
| 945 | + assert!(sps.conformance_window_flag); | |
| 946 | + assert_eq!(sps.visible_rectangle().max.y, 1082); | |
| 947 | + | |
| 948 | + let pps = PpsBuilder::new(Rc::clone(&sps)).build(); | |
| 949 | + let (_, _, sps2, _) = roundtrip(&vps, &sps, &pps, true); | |
| 950 | + | |
| 951 | + assert_eq!(*sps, *sps2); | |
| 952 | + assert_eq!(sps2.visible_rectangle().max.y, 1082); | |
| 953 | + } | |
| 954 | + | |
| 955 | + /// A SPS carrying VUI timing information, a long term reference picture set | |
| 956 | + /// and a short term reference picture set list. | |
| 957 | + #[test] | |
| 958 | + fn synthesize_sps_ref_pic_sets_and_vui() { | |
| 959 | + let vps = default_vps(); | |
| 960 | + | |
| 961 | + let mut st = ShortTermRefPicSet { num_negative_pics: 1, ..Default::default() }; | |
| 962 | + st.delta_poc_s0[0] = -1; | |
| 963 | + st.used_by_curr_pic_s0[0] = true; | |
| 964 | + st.num_delta_pocs = 1; | |
| 965 | + | |
| 966 | + let sps = SpsBuilder::new(Rc::clone(&vps)) | |
| 967 | + .resolution(320, 240) | |
| 968 | + .max_dec_pic_buffering_minus1(2) | |
| 969 | + .short_term_ref_pic_set(st.clone()) | |
| 970 | + .long_term_ref_pics_present_flag(true) | |
| 971 | + .timing_info(1, 60, true) | |
| 972 | + .build(); | |
| 973 | + | |
| 974 | + assert_eq!(sps.num_short_term_ref_pic_sets, 1); | |
| 975 | + | |
| 976 | + let pps = PpsBuilder::new(Rc::clone(&sps)).build(); | |
| 977 | + let (_, _, sps2, _) = roundtrip(&vps, &sps, &pps, true); | |
| 978 | + | |
| 979 | + assert_eq!(*sps, *sps2); | |
| 980 | + assert_eq!(sps2.short_term_ref_pic_set[0], st); | |
| 981 | + assert_eq!(sps2.vui_parameters.num_units_in_tick, 1); | |
| 982 | + assert_eq!(sps2.vui_parameters.time_scale, 60); | |
| 983 | + } | |
| 984 | + | |
| 985 | + /// A VPS carrying timing information, which contains long runs of zero | |
| 986 | + /// bits, so that emulation prevention bytes are actually emitted. | |
| 987 | + #[test] | |
| 988 | + fn synthesize_emulation_prevention() { | |
| 989 | + let vps = VpsBuilder::new() | |
| 990 | + .general_profile(Profile::Main) | |
| 991 | + .general_level_idc(Level::L4) | |
| 992 | + .max_dec_pic_buffering_minus1(1) | |
| 993 | + .timing_info(1, 60) | |
| 994 | + .build(); | |
| 995 | + let sps = default_sps(Rc::clone(&vps)); | |
| 996 | + let pps = PpsBuilder::new(Rc::clone(&sps)).build(); | |
| 997 | + | |
| 998 | + let (buf, vps2, sps2, pps2) = roundtrip(&vps, &sps, &pps, true); | |
| 999 | + | |
| 1000 | + // Emulation prevention bytes were actually needed here, otherwise this | |
| 1001 | + // test would not be testing anything. | |
| 1002 | + assert!(buf.windows(3).any(|w| w == [0x00, 0x00, 0x03])); | |
| 1003 | + | |
| 1004 | + assert_eq!(*vps, *vps2); | |
| 1005 | + assert_eq!(*sps, *sps2); | |
| 1006 | + assert_eq!(*pps, *pps2); | |
| 1007 | + } | |
| 1008 | + | |
| 1009 | + #[test] | |
| 1010 | + fn synthesize_scaling_lists() { | |
| 1011 | + let vps = default_vps(); | |
| 1012 | + let mut scaling_list = ScalingLists::default(); | |
| 1013 | + | |
| 1014 | + for (i, list) in scaling_list.scaling_list_4x4.iter_mut().enumerate() { | |
| 1015 | + for (j, coef) in list.iter_mut().enumerate() { | |
| 1016 | + *coef = (16 + i + j) as u8; | |
| 1017 | + } | |
| 1018 | + } | |
| 1019 | + | |
| 1020 | + for (i, list) in scaling_list.scaling_list_16x16.iter_mut().enumerate() { | |
| 1021 | + for (j, coef) in list.iter_mut().enumerate() { | |
| 1022 | + *coef = (16 + i * j) as u8; | |
| 1023 | + } | |
| 1024 | + scaling_list.scaling_list_dc_coef_minus8_16x16[i] = i as i16; | |
| 1025 | + } | |
| 1026 | + | |
| 1027 | + let sps = SpsBuilder::new(Rc::clone(&vps)) | |
| 1028 | + .resolution(320, 240) | |
| 1029 | + .scaling_list(scaling_list.clone()) | |
| 1030 | + .build(); | |
| 1031 | + let pps = PpsBuilder::new(Rc::clone(&sps)).scaling_list(scaling_list.clone()).build(); | |
| 1032 | + | |
| 1033 | + let (_, _, sps2, pps2) = roundtrip(&vps, &sps, &pps, true); | |
| 1034 | + | |
| 1035 | + assert_eq!(sps2.scaling_list, scaling_list); | |
| 1036 | + assert_eq!(pps2.scaling_list, scaling_list); | |
| 1037 | + assert_eq!(*sps, *sps2); | |
| 1038 | + assert_eq!(*pps, *pps2); | |
| 1039 | + } | |
| 1040 | + | |
| 1041 | + /// Re-synthesizing the parameter sets of a real bitstream must produce the | |
| 1042 | + /// exact same NALUs, which checks the synthesizer against streams that were | |
| 1043 | + /// not produced by this crate. | |
| 1044 | + #[test] | |
| 1045 | + fn synthesize_parameter_sets_from_stream() { | |
| 1046 | + const STREAM_BEAR: &[u8] = include_bytes!("test_data/bear.h265"); | |
| 1047 | + const STREAM_TEST25FPS: &[u8] = include_bytes!("test_data/test-25fps.h265"); | |
| 1048 | + const STREAM_BBB: &[u8] = include_bytes!("test_data/bbb.h265"); | |
| 1049 | + | |
| 1050 | + for stream in [STREAM_BEAR, STREAM_TEST25FPS, STREAM_BBB] { | |
| 1051 | + let mut cursor = Cursor::new(stream); | |
| 1052 | + let mut parser = Parser::default(); | |
| 1053 | + let mut num_checked = 0; | |
| 1054 | + | |
| 1055 | + while let Ok(nalu) = Nalu::next(&mut cursor) { | |
| 1056 | + let mut buf = Vec::<u8>::new(); | |
| 1057 | + let temporal_id_plus1 = nalu.header.nuh_temporal_id_plus1; | |
| 1058 | + | |
| 1059 | + match nalu.header.type_ { | |
| 1060 | + NaluType::VpsNut => { | |
| 1061 | + let vps = parser.parse_vps(&nalu).unwrap(); | |
| 1062 | + Synthesizer::<'_, Vps, _>::synthesize( | |
| 1063 | + temporal_id_plus1, | |
| 1064 | + vps, | |
| 1065 | + &mut buf, | |
| 1066 | + true, | |
| 1067 | + ) | |
| 1068 | + .unwrap(); | |
| 1069 | + } | |
| 1070 | + NaluType::SpsNut => { | |
| 1071 | + let sps = parser.parse_sps(&nalu).unwrap(); | |
| 1072 | + Synthesizer::<'_, Sps, _>::synthesize( | |
| 1073 | + temporal_id_plus1, | |
| 1074 | + sps, | |
| 1075 | + &mut buf, | |
| 1076 | + true, | |
| 1077 | + ) | |
| 1078 | + .unwrap(); | |
| 1079 | + } | |
| 1080 | + NaluType::PpsNut => { | |
| 1081 | + let pps = parser.parse_pps(&nalu).unwrap(); | |
| 1082 | + Synthesizer::<'_, Pps, _>::synthesize( | |
| 1083 | + temporal_id_plus1, | |
| 1084 | + pps, | |
| 1085 | + &mut buf, | |
| 1086 | + true, | |
| 1087 | + ) | |
| 1088 | + .unwrap(); | |
| 1089 | + } | |
| 1090 | + _ => continue, | |
| 1091 | + } | |
| 1092 | + | |
| 1093 | + // Skip the start code, which may be three bytes long in the | |
| 1094 | + // original stream. | |
| 1095 | + assert_eq!(&buf[4..], nalu.as_ref(), "{:?} mismatch", nalu.header.type_); | |
| 1096 | + num_checked += 1; | |
| 1097 | + } | |
| 1098 | + | |
| 1099 | + assert!(num_checked >= 3); | |
| 1100 | + } | |
| 1101 | + } | |
| 1102 | + | |
| 1103 | + /// A PPS exercising every field a CQP/CBR encoder is likely to set. | |
| 1104 | + #[test] | |
| 1105 | + fn synthesize_pps_fields() { | |
| 1106 | + let vps = default_vps(); | |
| 1107 | + let sps = default_sps(Rc::clone(&vps)); | |
| 1108 | + let pps = PpsBuilder::new(Rc::clone(&sps)) | |
| 1109 | + .pic_parameter_set_id(3) | |
| 1110 | + .dependent_slice_segments_enabled_flag(true) | |
| 1111 | + .output_flag_present_flag(true) | |
| 1112 | + .num_extra_slice_header_bits(2) | |
| 1113 | + .sign_data_hiding_enabled_flag(true) | |
| 1114 | + .cabac_init_present_flag(true) | |
| 1115 | + .num_ref_idx_l0_default_active_minus1(1) | |
| 1116 | + .num_ref_idx_l1_default_active_minus1(2) | |
| 1117 | + .init_qp_minus26(-4) | |
| 1118 | + .constrained_intra_pred_flag(true) | |
| 1119 | + .transform_skip_enabled_flag(true) | |
| 1120 | + .cu_qp_delta_enabled_flag(true) | |
| 1121 | + .diff_cu_qp_delta_depth(2) | |
| 1122 | + .cb_qp_offset(-3) | |
| 1123 | + .cr_qp_offset(5) | |
| 1124 | + .slice_chroma_qp_offsets_present_flag(true) | |
| 1125 | + .weighted_pred_flag(true) | |
| 1126 | + .weighted_bipred_flag(true) | |
| 1127 | + .transquant_bypass_enabled_flag(true) | |
| 1128 | + .entropy_coding_sync_enabled_flag(true) | |
| 1129 | + .loop_filter_across_slices_enabled_flag(true) | |
| 1130 | + .deblocking_filter_control_present_flag(true) | |
| 1131 | + .deblocking_filter_override_enabled_flag(true) | |
| 1132 | + .deblocking_filter_offsets(-2, 3) | |
| 1133 | + .lists_modification_present_flag(true) | |
| 1134 | + .log2_parallel_merge_level_minus2(1) | |
| 1135 | + .slice_segment_header_extension_present_flag(true) | |
| 1136 | + .build(); | |
| 1137 | + | |
| 1138 | + let (_, _, _, pps2) = roundtrip(&vps, &sps, &pps, true); | |
| 1139 | + | |
| 1140 | + assert_eq!(*pps, *pps2); | |
| 1141 | + } | |
| 1142 | +} |
vendor/cros-codecs/src/encoder.rsmodified+9 -0
| @@ -15,6 +15,7 @@ pub mod stateless; | ||
| 15 | 15 | |
| 16 | 16 | use crate::codec::av1::synthesizer::SynthesizerError as AV1SynthesizerError; |
| 17 | 17 | use crate::codec::h264::synthesizer::SynthesizerError as H264SynthesizerError; |
| 18 | +use crate::codec::h265::synthesizer::SynthesizerError as H265SynthesizerError; | |
| 18 | 19 | use crate::encoder::stateful::StatefulBackendError; |
| 19 | 20 | use crate::encoder::stateless::StatelessBackendError; |
| 20 | 21 | use crate::FrameLayout; |
| @@ -113,6 +114,7 @@ pub enum EncodeError { | ||
| 113 | 114 | StatelessBackendError(StatelessBackendError), |
| 114 | 115 | StatefulBackendError(StatefulBackendError), |
| 115 | 116 | H264SynthesizerError(H264SynthesizerError), |
| 117 | + H265SynthesizerError(H265SynthesizerError), | |
| 116 | 118 | AV1SynthesizerError(AV1SynthesizerError), |
| 117 | 119 | } |
| 118 | 120 | |
| @@ -126,6 +128,7 @@ impl fmt::Display for EncodeError { | ||
| 126 | 128 | EncodeError::StatelessBackendError(x) => write!(f, "{}", x.to_string()), |
| 127 | 129 | EncodeError::StatefulBackendError(x) => write!(f, "{}", x.to_string()), |
| 128 | 130 | EncodeError::H264SynthesizerError(x) => write!(f, "{}", x.to_string()), |
| 131 | + EncodeError::H265SynthesizerError(x) => write!(f, "{}", x.to_string()), | |
| 129 | 132 | EncodeError::AV1SynthesizerError(x) => write!(f, "{}", x.to_string()), |
| 130 | 133 | } |
| 131 | 134 | } |
| @@ -149,6 +152,12 @@ impl From<H264SynthesizerError> for EncodeError { | ||
| 149 | 152 | } |
| 150 | 153 | } |
| 151 | 154 | |
| 155 | +impl From<H265SynthesizerError> for EncodeError { | |
| 156 | + fn from(err: H265SynthesizerError) -> Self { | |
| 157 | + EncodeError::H265SynthesizerError(err) | |
| 158 | + } | |
| 159 | +} | |
| 160 | + | |
| 152 | 161 | impl From<AV1SynthesizerError> for EncodeError { |
| 153 | 162 | fn from(err: AV1SynthesizerError) -> Self { |
| 154 | 163 | EncodeError::AV1SynthesizerError(err) |
vendor/cros-codecs/src/encoder/h265.rsmodified+4 -0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | use crate::codec::h265::parser::Level; |
| 6 | 6 | use crate::codec::h265::parser::Profile; |
| 7 | 7 | use crate::encoder::PredictionStructure; |
| 8 | +use crate::encoder::Tunings; | |
| 8 | 9 | use crate::Resolution; |
| 9 | 10 | |
| 10 | 11 | pub struct H265; |
| @@ -15,6 +16,8 @@ pub struct EncoderConfig { | ||
| 15 | 16 | pub profile: Profile, |
| 16 | 17 | pub level: Level, |
| 17 | 18 | pub pred_structure: PredictionStructure, |
| 19 | + /// Initial tunings values | |
| 20 | + pub initial_tunings: Tunings, | |
| 18 | 21 | } |
| 19 | 22 | |
| 20 | 23 | impl Default for EncoderConfig { |
| @@ -25,6 +28,7 @@ impl Default for EncoderConfig { | ||
| 25 | 28 | profile: Profile::Main, |
| 26 | 29 | level: Level::L4, |
| 27 | 30 | pred_structure: PredictionStructure::LowDelay { limit: 2048 }, |
| 31 | + initial_tunings: Default::default(), | |
| 28 | 32 | } |
| 29 | 33 | } |
| 30 | 34 | } |
vendor/cros-codecs/src/encoder/stateless.rsmodified+2 -0
| @@ -19,6 +19,8 @@ pub mod av1; | ||
| 19 | 19 | #[cfg(feature = "vaapi")] |
| 20 | 20 | pub mod h264; |
| 21 | 21 | #[cfg(feature = "vaapi")] |
| 22 | +pub mod h265; | |
| 23 | +#[cfg(feature = "vaapi")] | |
| 22 | 24 | pub(crate) mod predictor; |
| 23 | 25 | #[cfg(feature = "vaapi")] |
| 24 | 26 | pub mod vp9; |
vendor/cros-codecs/src/encoder/stateless/h265.rsadded+205 -0
| @@ -0,0 +1,205 @@ | ||
| 1 | +// Copyright 2024 The ChromiumOS Authors | |
| 2 | +// Use of this source code is governed by a BSD-style license that can be | |
| 3 | +// found in the LICENSE file. | |
| 4 | + | |
| 5 | +use std::rc::Rc; | |
| 6 | + | |
| 7 | +use crate::codec::h265::parser::Pps; | |
| 8 | +use crate::codec::h265::parser::SliceType; | |
| 9 | +use crate::codec::h265::parser::Sps; | |
| 10 | +use crate::encoder::h265::EncoderConfig; | |
| 11 | +use crate::encoder::h265::H265; | |
| 12 | +use crate::encoder::stateless::h265::predictor::LowDelayH265; | |
| 13 | +use crate::encoder::stateless::BackendPromise; | |
| 14 | +use crate::encoder::stateless::BitstreamPromise; | |
| 15 | +use crate::encoder::stateless::FrameMetadata; | |
| 16 | +use crate::encoder::stateless::Predictor; | |
| 17 | +use crate::encoder::stateless::StatelessBackendResult; | |
| 18 | +use crate::encoder::stateless::StatelessCodec; | |
| 19 | +use crate::encoder::stateless::StatelessEncoderBackendImport; | |
| 20 | +use crate::encoder::stateless::StatelessEncoderExecute; | |
| 21 | +use crate::encoder::stateless::StatelessVideoEncoderBackend; | |
| 22 | +use crate::encoder::EncodeResult; | |
| 23 | +use crate::encoder::PredictionStructure; | |
| 24 | +use crate::encoder::Tunings; | |
| 25 | +use crate::BlockingMode; | |
| 26 | + | |
| 27 | +mod predictor; | |
| 28 | + | |
| 29 | +#[cfg(feature = "vaapi")] | |
| 30 | +pub mod vaapi; | |
| 31 | + | |
| 32 | +/// `nuh_temporal_id_plus1` of every NALU the encoder emits. The encoder uses a single temporal | |
| 33 | +/// sub-layer, hence `TemporalId` is always zero. See H.265 7.4.2.2. | |
| 34 | +pub(crate) const NUH_TEMPORAL_ID_PLUS1: u8 = 1; | |
| 35 | + | |
| 36 | +#[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
| 37 | +pub enum IsReference { | |
| 38 | + No, | |
| 39 | + ShortTerm, | |
| 40 | + LongTerm, | |
| 41 | +} | |
| 42 | + | |
| 43 | +#[derive(Clone, Debug)] | |
| 44 | +pub struct DpbEntryMeta { | |
| 45 | + /// Picture order count. Unlike H.264 this is a full PicOrderCntVal, the encoder never uses | |
| 46 | + /// more than one temporal sub-layer, therefore the value is never negative. | |
| 47 | + poc: i32, | |
| 48 | + is_reference: IsReference, | |
| 49 | +} | |
| 50 | + | |
| 51 | +/// Frame structure used in the backend representing currently encoded frame or references used | |
| 52 | +/// for its encoding. | |
| 53 | +pub struct DpbEntry<R> { | |
| 54 | + /// Reconstructed picture | |
| 55 | + recon_pic: R, | |
| 56 | + /// Decoded picture buffer entry metadata | |
| 57 | + meta: DpbEntryMeta, | |
| 58 | +} | |
| 59 | + | |
| 60 | +/// Stateless H.265 encoder backend input. | |
| 61 | +pub struct BackendRequest<P, R> { | |
| 62 | + sps: Rc<Sps>, | |
| 63 | + pps: Rc<Pps>, | |
| 64 | + | |
| 65 | + /// Type of the single slice segment covering the whole picture. H.265 has no | |
| 66 | + /// `SliceHeaderBuilder` counterpart yet, therefore the backend derives the remaining slice | |
| 67 | + /// segment header syntax elements from `sps`, `pps` and the reference lists. | |
| 68 | + slice_type: SliceType, | |
| 69 | + | |
| 70 | + /// Input frame to be encoded | |
| 71 | + input: P, | |
| 72 | + | |
| 73 | + /// Input frame metadata | |
| 74 | + input_meta: FrameMetadata, | |
| 75 | + | |
| 76 | + /// DPB entry metadata | |
| 77 | + dpb_meta: DpbEntryMeta, | |
| 78 | + | |
| 79 | + /// Reference lists | |
| 80 | + ref_list_0: Vec<Rc<DpbEntry<R>>>, | |
| 81 | + ref_list_1: Vec<Rc<DpbEntry<R>>>, | |
| 82 | + | |
| 83 | + /// Period between intra frames | |
| 84 | + intra_period: u32, | |
| 85 | + | |
| 86 | + /// Period between intra frame and P frame | |
| 87 | + ip_period: u32, | |
| 88 | + | |
| 89 | + /// Number of coding tree units to be encoded in slice | |
| 90 | + num_ctus: usize, | |
| 91 | + | |
| 92 | + /// True whenever the result is IDR | |
| 93 | + is_idr: bool, | |
| 94 | + | |
| 95 | + /// [`Tunings`] for the frame | |
| 96 | + tunings: Tunings, | |
| 97 | + | |
| 98 | + /// Container for the request output. [`StatelessH265EncoderBackend`] impl shall move it and | |
| 99 | + /// append the slice data to it. This prevents unnecessary copying of bitstream around. | |
| 100 | + coded_output: Vec<u8>, | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// Wrapper type for [`BackendPromise<Output = R>`], with additional | |
| 104 | +/// metadata. | |
| 105 | +pub struct ReferencePromise<P> | |
| 106 | +where | |
| 107 | + P: BackendPromise, | |
| 108 | +{ | |
| 109 | + /// Slice data and reconstructed surface promise | |
| 110 | + recon: P, | |
| 111 | + | |
| 112 | + /// [`DpbEntryMeta`] of reconstructed surface | |
| 113 | + dpb_meta: DpbEntryMeta, | |
| 114 | +} | |
| 115 | + | |
| 116 | +impl<P> BackendPromise for ReferencePromise<P> | |
| 117 | +where | |
| 118 | + P: BackendPromise, | |
| 119 | +{ | |
| 120 | + type Output = DpbEntry<P::Output>; | |
| 121 | + | |
| 122 | + fn is_ready(&self) -> bool { | |
| 123 | + self.recon.is_ready() | |
| 124 | + } | |
| 125 | + | |
| 126 | + fn sync(self) -> StatelessBackendResult<Self::Output> { | |
| 127 | + let recon_pic = self.recon.sync()?; | |
| 128 | + | |
| 129 | + log::trace!("synced recon picture poc={}", self.dpb_meta.poc); | |
| 130 | + | |
| 131 | + Ok(DpbEntry { recon_pic, meta: self.dpb_meta }) | |
| 132 | + } | |
| 133 | +} | |
| 134 | + | |
| 135 | +impl<Backend> StatelessCodec<Backend> for H265 | |
| 136 | +where | |
| 137 | + Backend: StatelessVideoEncoderBackend<H265>, | |
| 138 | +{ | |
| 139 | + type Reference = DpbEntry<Backend::Reconstructed>; | |
| 140 | + | |
| 141 | + type Request = BackendRequest<Backend::Picture, Backend::Reconstructed>; | |
| 142 | + | |
| 143 | + type CodedPromise = BitstreamPromise<Backend::CodedPromise>; | |
| 144 | + | |
| 145 | + type ReferencePromise = ReferencePromise<Backend::ReconPromise>; | |
| 146 | +} | |
| 147 | + | |
| 148 | +/// Trait for stateless encoder backend for H.265 | |
| 149 | +pub trait StatelessH265EncoderBackend: StatelessVideoEncoderBackend<H265> { | |
| 150 | + /// Submit a [`BackendRequest`] to the backend. This operation returns both a | |
| 151 | + /// [`StatelessVideoEncoderBackend::CodedPromise`] and a | |
| 152 | + /// [`StatelessVideoEncoderBackend::ReconPromise`] with resulting slice data. | |
| 153 | + fn encode_slice( | |
| 154 | + &mut self, | |
| 155 | + request: BackendRequest<Self::Picture, Self::Reconstructed>, | |
| 156 | + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)>; | |
| 157 | +} | |
| 158 | + | |
| 159 | +pub type StatelessEncoder<Handle, Backend> = | |
| 160 | + crate::encoder::stateless::StatelessEncoder<H265, Handle, Backend>; | |
| 161 | + | |
| 162 | +impl<Handle, Backend> StatelessEncoderExecute<H265, Handle, Backend> | |
| 163 | + for StatelessEncoder<Handle, Backend> | |
| 164 | +where | |
| 165 | + Backend: StatelessH265EncoderBackend, | |
| 166 | +{ | |
| 167 | + fn execute( | |
| 168 | + &mut self, | |
| 169 | + request: BackendRequest<Backend::Picture, Backend::Reconstructed>, | |
| 170 | + ) -> EncodeResult<()> { | |
| 171 | + let meta = request.input_meta.clone(); | |
| 172 | + let dpb_meta = request.dpb_meta.clone(); | |
| 173 | + | |
| 174 | + // The [`BackendRequest`] has a frame from predictor. Decreasing internal counter. | |
| 175 | + self.predictor_frame_count -= 1; | |
| 176 | + | |
| 177 | + log::trace!("submitting new request"); | |
| 178 | + let (recon, bitstream) = self.backend.encode_slice(request)?; | |
| 179 | + | |
| 180 | + // Wrap promise from backend with headers and metadata | |
| 181 | + let slice_promise = BitstreamPromise { bitstream, meta }; | |
| 182 | + | |
| 183 | + self.output_queue.add_promise(slice_promise); | |
| 184 | + | |
| 185 | + let ref_promise = ReferencePromise { recon, dpb_meta }; | |
| 186 | + | |
| 187 | + self.recon_queue.add_promise(ref_promise); | |
| 188 | + | |
| 189 | + Ok(()) | |
| 190 | + } | |
| 191 | +} | |
| 192 | + | |
| 193 | +impl<Handle, Backend> StatelessEncoder<Handle, Backend> | |
| 194 | +where | |
| 195 | + Backend: StatelessH265EncoderBackend, | |
| 196 | + Backend: StatelessEncoderBackendImport<Handle, Backend::Picture>, | |
| 197 | +{ | |
| 198 | + fn new_h265(backend: Backend, config: EncoderConfig, mode: BlockingMode) -> EncodeResult<Self> { | |
| 199 | + let predictor: Box<dyn Predictor<_, _, _>> = match config.pred_structure { | |
| 200 | + PredictionStructure::LowDelay { limit } => Box::new(LowDelayH265::new(config, limit)), | |
| 201 | + }; | |
| 202 | + | |
| 203 | + Self::new(backend, mode, predictor) | |
| 204 | + } | |
| 205 | +} |
vendor/cros-codecs/src/encoder/stateless/h265/predictor.rsadded+288 -0
| @@ -0,0 +1,288 @@ | ||
| 1 | +// Copyright 2024 The ChromiumOS Authors | |
| 2 | +// Use of this source code is governed by a BSD-style license that can be | |
| 3 | +// found in the LICENSE file. | |
| 4 | + | |
| 5 | +use std::rc::Rc; | |
| 6 | + | |
| 7 | +use log::trace; | |
| 8 | + | |
| 9 | +use crate::codec::h265::parser::Pps; | |
| 10 | +use crate::codec::h265::parser::PpsBuilder; | |
| 11 | +use crate::codec::h265::parser::ShortTermRefPicSet; | |
| 12 | +use crate::codec::h265::parser::SliceType; | |
| 13 | +use crate::codec::h265::parser::Sps; | |
| 14 | +use crate::codec::h265::parser::SpsBuilder; | |
| 15 | +use crate::codec::h265::parser::Vps; | |
| 16 | +use crate::codec::h265::parser::VpsBuilder; | |
| 17 | +use crate::codec::h265::synthesizer::Synthesizer; | |
| 18 | +use crate::encoder::stateless::h265::BackendRequest; | |
| 19 | +use crate::encoder::stateless::h265::DpbEntry; | |
| 20 | +use crate::encoder::stateless::h265::DpbEntryMeta; | |
| 21 | +use crate::encoder::stateless::h265::EncoderConfig; | |
| 22 | +use crate::encoder::stateless::h265::IsReference; | |
| 23 | +use crate::encoder::stateless::h265::NUH_TEMPORAL_ID_PLUS1; | |
| 24 | +use crate::encoder::stateless::predictor::LowDelay; | |
| 25 | +use crate::encoder::stateless::predictor::LowDelayDelegate; | |
| 26 | +use crate::encoder::stateless::FrameMetadata; | |
| 27 | +use crate::encoder::EncodeError; | |
| 28 | +use crate::encoder::EncodeResult; | |
| 29 | +use crate::encoder::RateControl; | |
| 30 | +use crate::encoder::Tunings; | |
| 31 | + | |
| 32 | +pub(crate) const MIN_QP: u8 = 1; | |
| 33 | +pub(crate) const MAX_QP: u8 = 51; | |
| 34 | + | |
| 35 | +/// The encoder never reorders and keeps at most one reference picture, therefore the DPB holds | |
| 36 | +/// no more than one picture besides the currently decoded one. Note that this value must not be | |
| 37 | +/// lower than `NumNegativePics` of any short term reference picture set, see H.265 7.4.3.2.1. | |
| 38 | +const MAX_DEC_PIC_BUFFERING_MINUS1: u8 = 1; | |
| 39 | + | |
| 40 | +pub(crate) struct LowDelayH265Delegate { | |
| 41 | + /// Current sequence VPS | |
| 42 | + vps: Option<Rc<Vps>>, | |
| 43 | + /// Current sequence SPS | |
| 44 | + sps: Option<Rc<Sps>>, | |
| 45 | + /// Current sequence PPS | |
| 46 | + pps: Option<Rc<Pps>>, | |
| 47 | + | |
| 48 | + // True if VPS, SPS or PPS changed and should reappear in the bitstream | |
| 49 | + update_params_sets: bool, | |
| 50 | + | |
| 51 | + /// Encoder config | |
| 52 | + config: EncoderConfig, | |
| 53 | +} | |
| 54 | + | |
| 55 | +pub(crate) type LowDelayH265<Picture, Reference> = LowDelay< | |
| 56 | + Picture, | |
| 57 | + DpbEntry<Reference>, | |
| 58 | + LowDelayH265Delegate, | |
| 59 | + BackendRequest<Picture, Reference>, | |
| 60 | +>; | |
| 61 | + | |
| 62 | +impl<Picture, Reference> LowDelayH265<Picture, Reference> { | |
| 63 | + pub(super) fn new(config: EncoderConfig, limit: u16) -> Self { | |
| 64 | + Self { | |
| 65 | + queue: Default::default(), | |
| 66 | + references: Default::default(), | |
| 67 | + counter: 0, | |
| 68 | + limit, | |
| 69 | + tunings: config.initial_tunings.clone(), | |
| 70 | + delegate: LowDelayH265Delegate { | |
| 71 | + config, | |
| 72 | + update_params_sets: false, | |
| 73 | + vps: None, | |
| 74 | + sps: None, | |
| 75 | + pps: None, | |
| 76 | + }, | |
| 77 | + tunings_queue: Default::default(), | |
| 78 | + _phantom: Default::default(), | |
| 79 | + } | |
| 80 | + } | |
| 81 | + | |
| 82 | + fn new_sequence(&mut self) { | |
| 83 | + trace!("beginning new sequence"); | |
| 84 | + let config = &self.delegate.config; | |
| 85 | + | |
| 86 | + let vps = VpsBuilder::new() | |
| 87 | + .video_parameter_set_id(0) | |
| 88 | + .max_layers_minus1(0) | |
| 89 | + // A single temporal sub-layer. The synthesizer does not support more. | |
| 90 | + .max_sub_layers_minus1(0) | |
| 91 | + .general_profile(config.profile) | |
| 92 | + .general_level_idc(config.level) | |
| 93 | + .max_dec_pic_buffering_minus1(MAX_DEC_PIC_BUFFERING_MINUS1 as u32) | |
| 94 | + // Output order is the coding order, there is no reordering nor latency. | |
| 95 | + .max_num_reorder_pics(0) | |
| 96 | + .max_latency_increase_plus1(0) | |
| 97 | + .timing_info(1, self.tunings.framerate) | |
| 98 | + .build(); | |
| 99 | + | |
| 100 | + // The only reference an inter frame ever uses is the picture that immediately precedes | |
| 101 | + // it, ie. `DeltaPocS0[0]` is -1 and the set is used by the current picture. Backends | |
| 102 | + // write the slice segment headers themselves and refer to this set by index, therefore | |
| 103 | + // it has to be signalled in the SPS. See H.265 7.4.8. | |
| 104 | + let mut short_term_ref_pic_set = | |
| 105 | + ShortTermRefPicSet { num_negative_pics: 1, num_delta_pocs: 1, ..Default::default() }; | |
| 106 | + short_term_ref_pic_set.delta_poc_s0[0] = -1; | |
| 107 | + short_term_ref_pic_set.used_by_curr_pic_s0[0] = true; | |
| 108 | + | |
| 109 | + // H.265 Table 6-1, the encoder only supports 4:2:0 subsampling. Must be set before | |
| 110 | + // `resolution()`, which derives the conformance window from it. | |
| 111 | + let sps = SpsBuilder::new(Rc::clone(&vps)) | |
| 112 | + .seq_parameter_set_id(0) | |
| 113 | + .chroma_format_idc(1) | |
| 114 | + .resolution(config.resolution.width, config.resolution.height) | |
| 115 | + .bit_depth_luma(8) | |
| 116 | + .bit_depth_chroma(8) | |
| 117 | + .max_dec_pic_buffering_minus1(MAX_DEC_PIC_BUFFERING_MINUS1) | |
| 118 | + .max_num_reorder_pics(0) | |
| 119 | + .max_latency_increase_plus1(0) | |
| 120 | + .short_term_ref_pic_set(short_term_ref_pic_set) | |
| 121 | + .long_term_ref_pics_present_flag(false) | |
| 122 | + .timing_info(1, self.tunings.framerate, false) | |
| 123 | + .build(); | |
| 124 | + | |
| 125 | + let min_qp = self.tunings.min_quality.max(MIN_QP as u32); | |
| 126 | + let max_qp = self.tunings.max_quality.min(MAX_QP as u32); | |
| 127 | + | |
| 128 | + let init_qp = if let RateControl::ConstantQuality(init_qp) = self.tunings.rate_control { | |
| 129 | + // Limit QP to valid values | |
| 130 | + init_qp.clamp(min_qp, max_qp) as u8 | |
| 131 | + } else { | |
| 132 | + // Pick middle QP for default qp | |
| 133 | + ((min_qp + max_qp) / 2) as u8 | |
| 134 | + }; | |
| 135 | + | |
| 136 | + let pps = PpsBuilder::new(Rc::clone(&sps)) | |
| 137 | + .pic_parameter_set_id(0) | |
| 138 | + .init_qp(init_qp as i8) | |
| 139 | + .deblocking_filter_control_present_flag(true) | |
| 140 | + .num_ref_idx_l0_default_active_minus1(0) | |
| 141 | + // Unused, P slices rely only on list0 | |
| 142 | + .num_ref_idx_l1_default_active_minus1(0) | |
| 143 | + .build(); | |
| 144 | + | |
| 145 | + self.delegate.vps = Some(vps); | |
| 146 | + self.delegate.sps = Some(sps); | |
| 147 | + self.delegate.pps = Some(pps); | |
| 148 | + self.delegate.update_params_sets = true; | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// Synthesizes the active parameter sets into `headers` if they have not been written since | |
| 152 | + /// they were last changed. | |
| 153 | + fn synthesize_parameter_sets( | |
| 154 | + &mut self, | |
| 155 | + force: bool, | |
| 156 | + headers: &mut Vec<u8>, | |
| 157 | + ) -> EncodeResult<()> { | |
| 158 | + if !force && !self.delegate.update_params_sets { | |
| 159 | + return Ok(()); | |
| 160 | + } | |
| 161 | + | |
| 162 | + let vps = self.delegate.vps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 163 | + let sps = self.delegate.sps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 164 | + let pps = self.delegate.pps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 165 | + | |
| 166 | + Synthesizer::<Vps, &mut Vec<u8>>::synthesize(NUH_TEMPORAL_ID_PLUS1, &vps, headers, true)?; | |
| 167 | + Synthesizer::<Sps, &mut Vec<u8>>::synthesize(NUH_TEMPORAL_ID_PLUS1, &sps, headers, true)?; | |
| 168 | + Synthesizer::<Pps, &mut Vec<u8>>::synthesize(NUH_TEMPORAL_ID_PLUS1, &pps, headers, true)?; | |
| 169 | + | |
| 170 | + self.delegate.update_params_sets = false; | |
| 171 | + | |
| 172 | + Ok(()) | |
| 173 | + } | |
| 174 | +} | |
| 175 | + | |
| 176 | +impl<Picture, Reference> | |
| 177 | + LowDelayDelegate<Picture, DpbEntry<Reference>, BackendRequest<Picture, Reference>> | |
| 178 | + for LowDelayH265<Picture, Reference> | |
| 179 | +{ | |
| 180 | + fn request_keyframe( | |
| 181 | + &mut self, | |
| 182 | + input: Picture, | |
| 183 | + input_meta: FrameMetadata, | |
| 184 | + idr: bool, | |
| 185 | + ) -> EncodeResult<BackendRequest<Picture, Reference>> { | |
| 186 | + if idr { | |
| 187 | + // Begin new sequence and start with I frame and no references. | |
| 188 | + self.new_sequence(); | |
| 189 | + } | |
| 190 | + | |
| 191 | + let mut headers = vec![]; | |
| 192 | + self.synthesize_parameter_sets(idr, &mut headers)?; | |
| 193 | + | |
| 194 | + let sps = self.delegate.sps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 195 | + let pps = self.delegate.pps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 196 | + | |
| 197 | + let dpb_meta = | |
| 198 | + DpbEntryMeta { poc: self.counter as i32, is_reference: IsReference::ShortTerm }; | |
| 199 | + | |
| 200 | + let num_ctus = sps.pic_size_in_ctbs_y as usize; | |
| 201 | + | |
| 202 | + let request = BackendRequest { | |
| 203 | + sps, | |
| 204 | + pps, | |
| 205 | + slice_type: SliceType::I, | |
| 206 | + input, | |
| 207 | + input_meta, | |
| 208 | + dpb_meta, | |
| 209 | + // This frame is a random access point, therefore it has no references | |
| 210 | + ref_list_0: vec![], | |
| 211 | + ref_list_1: vec![], | |
| 212 | + | |
| 213 | + // I frame is every `self.limit` is requested | |
| 214 | + intra_period: self.limit as u32, | |
| 215 | + // There is no B frames between I and P frames | |
| 216 | + ip_period: 1, | |
| 217 | + | |
| 218 | + num_ctus, | |
| 219 | + | |
| 220 | + is_idr: idr, | |
| 221 | + tunings: self.tunings.clone(), | |
| 222 | + | |
| 223 | + coded_output: headers, | |
| 224 | + }; | |
| 225 | + | |
| 226 | + Ok(request) | |
| 227 | + } | |
| 228 | + | |
| 229 | + fn request_interframe( | |
| 230 | + &mut self, | |
| 231 | + input: Picture, | |
| 232 | + input_meta: FrameMetadata, | |
| 233 | + ) -> EncodeResult<BackendRequest<Picture, Reference>> { | |
| 234 | + let mut ref_list_0 = vec![]; | |
| 235 | + | |
| 236 | + // Use all avaiable reference frames in DPB. Their number is limited by the parameter | |
| 237 | + for reference in self.references.iter().rev() { | |
| 238 | + ref_list_0.push(Rc::clone(reference)); | |
| 239 | + } | |
| 240 | + | |
| 241 | + let mut headers = Vec::new(); | |
| 242 | + self.synthesize_parameter_sets(false, &mut headers)?; | |
| 243 | + | |
| 244 | + let sps = self.delegate.sps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 245 | + let pps = self.delegate.pps.clone().ok_or(EncodeError::InvalidInternalState)?; | |
| 246 | + | |
| 247 | + let dpb_meta = | |
| 248 | + DpbEntryMeta { poc: self.counter as i32, is_reference: IsReference::ShortTerm }; | |
| 249 | + | |
| 250 | + let num_ctus = sps.pic_size_in_ctbs_y as usize; | |
| 251 | + | |
| 252 | + let request = BackendRequest { | |
| 253 | + sps, | |
| 254 | + pps, | |
| 255 | + slice_type: SliceType::P, | |
| 256 | + input, | |
| 257 | + input_meta, | |
| 258 | + dpb_meta, | |
| 259 | + ref_list_0, | |
| 260 | + ref_list_1: vec![], // No future references | |
| 261 | + | |
| 262 | + // I frame is every `self.limit` is requested | |
| 263 | + intra_period: self.limit as u32, | |
| 264 | + // There is no B frames between I and P frames | |
| 265 | + ip_period: 1, | |
| 266 | + | |
| 267 | + num_ctus, | |
| 268 | + | |
| 269 | + is_idr: false, | |
| 270 | + tunings: self.tunings.clone(), | |
| 271 | + | |
| 272 | + coded_output: headers, | |
| 273 | + }; | |
| 274 | + | |
| 275 | + self.references.clear(); | |
| 276 | + | |
| 277 | + Ok(request) | |
| 278 | + } | |
| 279 | + | |
| 280 | + fn try_tunings(&self, _tunings: &Tunings) -> EncodeResult<()> { | |
| 281 | + Ok(()) | |
| 282 | + } | |
| 283 | + | |
| 284 | + fn apply_tunings(&mut self, _tunings: &Tunings) -> EncodeResult<()> { | |
| 285 | + self.new_sequence(); | |
| 286 | + Ok(()) | |
| 287 | + } | |
| 288 | +} |
vendor/cros-codecs/src/encoder/stateless/h265/vaapi.rsadded+725 -0
| @@ -0,0 +1,725 @@ | ||
| 1 | +// Copyright 2024 The ChromiumOS Authors | |
| 2 | +// Use of this source code is governed by a BSD-style license that can be | |
| 3 | +// found in the LICENSE file. | |
| 4 | + | |
| 5 | +use std::any::Any; | |
| 6 | +use std::borrow::Borrow; | |
| 7 | +use std::rc::Rc; | |
| 8 | + | |
| 9 | +use anyhow::Context; | |
| 10 | +use libva::BufferType; | |
| 11 | +use libva::Display; | |
| 12 | +use libva::EncCodedBuffer; | |
| 13 | +use libva::EncPictureParameter; | |
| 14 | +use libva::EncPictureParameterBufferHEVC; | |
| 15 | +use libva::EncSequenceParameter; | |
| 16 | +use libva::EncSequenceParameterBufferHEVC; | |
| 17 | +use libva::EncSliceParameter; | |
| 18 | +use libva::EncSliceParameterBufferHEVC; | |
| 19 | +use libva::HEVCEncPicFields; | |
| 20 | +use libva::HEVCEncSeqFields; | |
| 21 | +use libva::HevcEncPicSccFields; | |
| 22 | +use libva::HevcEncSeqSccFields; | |
| 23 | +use libva::HevcEncSliceFields; | |
| 24 | +use libva::HevcEncVuiFields; | |
| 25 | +use libva::Picture; | |
| 26 | +use libva::PictureHEVC; | |
| 27 | +use libva::Surface; | |
| 28 | +use libva::SurfaceMemoryDescriptor; | |
| 29 | +use libva::VAProfile; | |
| 30 | +use libva::VA_INVALID_ID; | |
| 31 | +use libva::VA_PICTURE_HEVC_INVALID; | |
| 32 | +use libva::VA_PICTURE_HEVC_LONG_TERM_REFERENCE; | |
| 33 | + | |
| 34 | +use crate::backend::vaapi::encoder::tunings_to_libva_rc; | |
| 35 | +use crate::backend::vaapi::encoder::CodedOutputPromise; | |
| 36 | +use crate::backend::vaapi::encoder::Reconstructed; | |
| 37 | +use crate::backend::vaapi::encoder::VaapiBackend; | |
| 38 | +use crate::codec::h265::parser::NaluType; | |
| 39 | +use crate::codec::h265::parser::Pps; | |
| 40 | +use crate::codec::h265::parser::Profile; | |
| 41 | +use crate::codec::h265::parser::SliceType; | |
| 42 | +use crate::codec::h265::parser::Sps; | |
| 43 | +use crate::encoder::h265::EncoderConfig; | |
| 44 | +use crate::encoder::h265::H265; | |
| 45 | +use crate::encoder::stateless::h265::predictor::MAX_QP; | |
| 46 | +use crate::encoder::stateless::h265::predictor::MIN_QP; | |
| 47 | +use crate::encoder::stateless::h265::BackendRequest; | |
| 48 | +use crate::encoder::stateless::h265::DpbEntry; | |
| 49 | +use crate::encoder::stateless::h265::DpbEntryMeta; | |
| 50 | +use crate::encoder::stateless::h265::IsReference; | |
| 51 | +use crate::encoder::stateless::h265::StatelessEncoder; | |
| 52 | +use crate::encoder::stateless::h265::StatelessH265EncoderBackend; | |
| 53 | +use crate::encoder::stateless::ReadyPromise; | |
| 54 | +use crate::encoder::stateless::StatelessBackendError; | |
| 55 | +use crate::encoder::stateless::StatelessBackendResult; | |
| 56 | +use crate::encoder::stateless::StatelessVideoEncoderBackend; | |
| 57 | +use crate::encoder::EncodeResult; | |
| 58 | +use crate::encoder::RateControl; | |
| 59 | +use crate::video_frame::VideoFrame; | |
| 60 | +use crate::BlockingMode; | |
| 61 | +use crate::Fourcc; | |
| 62 | +use crate::Resolution; | |
| 63 | + | |
| 64 | +/// Size of `VAEncPictureParameterBufferHEVC::reference_frames` and of the slice parameter | |
| 65 | +/// reference picture lists. | |
| 66 | +const MAX_REFERENCE_FRAMES: usize = 15; | |
| 67 | + | |
| 68 | +/// `VAEncPictureParameterBufferHEVC::coding_type` for an I picture. See va_enc_hevc.h. | |
| 69 | +const CODING_TYPE_I: u32 = 1; | |
| 70 | +/// `VAEncPictureParameterBufferHEVC::coding_type` for a P picture. See va_enc_hevc.h. | |
| 71 | +const CODING_TYPE_P: u32 = 2; | |
| 72 | + | |
| 73 | +/// `VAEncPictureParameterBufferHEVC::collocated_ref_pic_index` value meaning that no collocated | |
| 74 | +/// reference picture is used, ie. `slice_temporal_mvp_enabled_flag` is zero. See va_enc_hevc.h. | |
| 75 | +const NO_COLLOCATED_REF_PIC: u8 = 0xff; | |
| 76 | + | |
| 77 | +/// Value of `five_minus_max_num_merge_cand` subtracted from five, ie. the maximum number of | |
| 78 | +/// merging motion vector prediction candidates. See H.265 7.4.7.1. | |
| 79 | +const MAX_NUM_MERGE_CAND: u8 = 5; | |
| 80 | + | |
| 81 | +type Request<'l, H> = BackendRequest<H, Reconstructed>; | |
| 82 | + | |
| 83 | +impl<M, H> StatelessVideoEncoderBackend<H265> for VaapiBackend<M, H> | |
| 84 | +where | |
| 85 | + M: SurfaceMemoryDescriptor, | |
| 86 | + H: std::borrow::Borrow<Surface<M>> + 'static, | |
| 87 | +{ | |
| 88 | + type Picture = H; | |
| 89 | + type Reconstructed = Reconstructed; | |
| 90 | + type CodedPromise = CodedOutputPromise<M, H>; | |
| 91 | + type ReconPromise = ReadyPromise<Self::Reconstructed>; | |
| 92 | +} | |
| 93 | + | |
| 94 | +/// Builds an invalid [`libva::PictureHEVC`]. This is usually a place | |
| 95 | +/// holder to fill staticly sized array. | |
| 96 | +fn build_invalid_va_h265_pic_enc() -> PictureHEVC { | |
| 97 | + PictureHEVC::new(VA_INVALID_ID, 0, VA_PICTURE_HEVC_INVALID) | |
| 98 | +} | |
| 99 | + | |
| 100 | +/// Builds [`libva::PictureHEVC`] from `surface` and its `meta`. | |
| 101 | +fn build_h265_pic(surface: &Reconstructed, meta: &DpbEntryMeta) -> PictureHEVC { | |
| 102 | + let flags = match meta.is_reference { | |
| 103 | + IsReference::No | IsReference::ShortTerm => 0, | |
| 104 | + IsReference::LongTerm => VA_PICTURE_HEVC_LONG_TERM_REFERENCE, | |
| 105 | + }; | |
| 106 | + | |
| 107 | + PictureHEVC::new(surface.surface_id(), meta.poc, flags) | |
| 108 | +} | |
| 109 | + | |
| 110 | +/// Fills a reference picture list of [`MAX_REFERENCE_FRAMES`] entries with `refs`, padding | |
| 111 | +/// the remaining slots with invalid pictures. | |
| 112 | +fn build_va_ref_pic_list<'e>( | |
| 113 | + refs: impl Iterator<Item = &'e Rc<DpbEntry<Reconstructed>>>, | |
| 114 | +) -> [PictureHEVC; MAX_REFERENCE_FRAMES] { | |
| 115 | + let mut list: [PictureHEVC; MAX_REFERENCE_FRAMES] = (0..MAX_REFERENCE_FRAMES) | |
| 116 | + .map(|_| build_invalid_va_h265_pic_enc()) | |
| 117 | + .collect::<Vec<_>>() | |
| 118 | + .try_into() | |
| 119 | + .unwrap_or_else(|_| panic!()); | |
| 120 | + | |
| 121 | + for (idx, ref_frame) in refs.enumerate().take(MAX_REFERENCE_FRAMES) { | |
| 122 | + list[idx] = build_h265_pic(&ref_frame.recon_pic, &ref_frame.meta); | |
| 123 | + } | |
| 124 | + | |
| 125 | + list | |
| 126 | +} | |
| 127 | + | |
| 128 | +/// Builds [`BufferType::EncSequenceParameter`] from `sps` | |
| 129 | +fn build_enc_seq_param( | |
| 130 | + sps: &Sps, | |
| 131 | + bits_per_second: u32, | |
| 132 | + intra_period: u32, | |
| 133 | + ip_period: u32, | |
| 134 | +) -> BufferType { | |
| 135 | + let intra_idr_period = intra_period; | |
| 136 | + | |
| 137 | + let seq_fields = HEVCEncSeqFields::new( | |
| 138 | + sps.chroma_format_idc as u32, | |
| 139 | + sps.separate_colour_plane_flag as u32, | |
| 140 | + sps.bit_depth_luma_minus8 as u32, | |
| 141 | + sps.bit_depth_chroma_minus8 as u32, | |
| 142 | + sps.scaling_list_enabled_flag as u32, | |
| 143 | + sps.strong_intra_smoothing_enabled_flag as u32, | |
| 144 | + sps.amp_enabled_flag as u32, | |
| 145 | + sps.sample_adaptive_offset_enabled_flag as u32, | |
| 146 | + sps.pcm_enabled_flag as u32, | |
| 147 | + sps.pcm_loop_filter_disabled_flag as u32, | |
| 148 | + sps.temporal_mvp_enabled_flag as u32, | |
| 149 | + // The prediction structure never references a picture that follows in output order. | |
| 150 | + true as u32, | |
| 151 | + // No hierarchical prediction structure is used. | |
| 152 | + false as u32, | |
| 153 | + ); | |
| 154 | + | |
| 155 | + let vui = &sps.vui_parameters; | |
| 156 | + let vui_fields = if sps.vui_parameters_present_flag { | |
| 157 | + Some(HevcEncVuiFields::new( | |
| 158 | + vui.aspect_ratio_info_present_flag as u32, | |
| 159 | + vui.neutral_chroma_indication_flag as u32, | |
| 160 | + vui.field_seq_flag as u32, | |
| 161 | + vui.timing_info_present_flag as u32, | |
| 162 | + vui.bitstream_restriction_flag as u32, | |
| 163 | + vui.tiles_fixed_structure_flag as u32, | |
| 164 | + vui.motion_vectors_over_pic_boundaries_flag as u32, | |
| 165 | + vui.restricted_ref_pic_lists_flag as u32, | |
| 166 | + vui.log2_max_mv_length_horizontal, | |
| 167 | + vui.log2_max_mv_length_vertical, | |
| 168 | + )) | |
| 169 | + } else { | |
| 170 | + None | |
| 171 | + }; | |
| 172 | + | |
| 173 | + // The encoder never enables the palette mode of the screen content coding extension. | |
| 174 | + let scc_fields = HevcEncSeqSccFields::new(false as u32); | |
| 175 | + | |
| 176 | + BufferType::EncSequenceParameter(EncSequenceParameter::HEVC( | |
| 177 | + EncSequenceParameterBufferHEVC::new( | |
| 178 | + sps.profile_tier_level.general_profile_idc, | |
| 179 | + sps.profile_tier_level.general_level_idc as u8, | |
| 180 | + sps.profile_tier_level.general_tier_flag as u8, | |
| 181 | + intra_period, | |
| 182 | + intra_idr_period, | |
| 183 | + ip_period, | |
| 184 | + bits_per_second, | |
| 185 | + sps.pic_width_in_luma_samples, | |
| 186 | + sps.pic_height_in_luma_samples, | |
| 187 | + &seq_fields, | |
| 188 | + sps.log2_min_luma_coding_block_size_minus3, | |
| 189 | + sps.log2_diff_max_min_luma_coding_block_size, | |
| 190 | + sps.log2_min_luma_transform_block_size_minus2, | |
| 191 | + sps.log2_diff_max_min_luma_transform_block_size, | |
| 192 | + sps.max_transform_hierarchy_depth_inter, | |
| 193 | + sps.max_transform_hierarchy_depth_intra, | |
| 194 | + sps.pcm_sample_bit_depth_luma_minus1 as u32, | |
| 195 | + sps.pcm_sample_bit_depth_chroma_minus1 as u32, | |
| 196 | + sps.log2_min_pcm_luma_coding_block_size_minus3 as u32, | |
| 197 | + (sps.log2_min_pcm_luma_coding_block_size_minus3 | |
| 198 | + + sps.log2_diff_max_min_pcm_luma_coding_block_size) as u32, | |
| 199 | + vui_fields, | |
| 200 | + vui.aspect_ratio_idc as u8, | |
| 201 | + vui.sar_width, | |
| 202 | + vui.sar_height, | |
| 203 | + vui.num_units_in_tick, | |
| 204 | + vui.time_scale, | |
| 205 | + vui.min_spatial_segmentation_idc as u16, | |
| 206 | + vui.max_bytes_per_pic_denom as u8, | |
| 207 | + vui.max_bits_per_min_cu_denom as u8, | |
| 208 | + &scc_fields, | |
| 209 | + ), | |
| 210 | + )) | |
| 211 | +} | |
| 212 | + | |
| 213 | +/// H.265 Table 7-1. A non IDR key frame is coded as a trailing picture, because the prediction | |
| 214 | +/// structure never emits leading pictures. | |
| 215 | +fn nal_unit_type(is_idr: bool) -> NaluType { | |
| 216 | + if is_idr { | |
| 217 | + NaluType::IdrWRadl | |
| 218 | + } else { | |
| 219 | + NaluType::TrailR | |
| 220 | + } | |
| 221 | +} | |
| 222 | + | |
| 223 | +/// Builds [`BufferType::EncPictureParameter`] from [`Request`] and sets bitstream | |
| 224 | +/// output to `coded_buf`. | |
| 225 | +fn build_enc_pic_param<H>( | |
| 226 | + request: &Request<'_, H>, | |
| 227 | + coded_buf: &EncCodedBuffer, | |
| 228 | + recon: &Reconstructed, | |
| 229 | +) -> BufferType { | |
| 230 | + let pps = &request.pps; | |
| 231 | + | |
| 232 | + let coding_type = match request.slice_type { | |
| 233 | + SliceType::I => CODING_TYPE_I, | |
| 234 | + _ => CODING_TYPE_P, | |
| 235 | + }; | |
| 236 | + | |
| 237 | + let pic_fields = HEVCEncPicFields::new( | |
| 238 | + request.is_idr as u32, | |
| 239 | + coding_type, | |
| 240 | + (request.dpb_meta.is_reference != IsReference::No) as u32, | |
| 241 | + pps.dependent_slice_segments_enabled_flag as u32, | |
| 242 | + pps.sign_data_hiding_enabled_flag as u32, | |
| 243 | + pps.constrained_intra_pred_flag as u32, | |
| 244 | + pps.transform_skip_enabled_flag as u32, | |
| 245 | + pps.cu_qp_delta_enabled_flag as u32, | |
| 246 | + pps.weighted_pred_flag as u32, | |
| 247 | + pps.weighted_bipred_flag as u32, | |
| 248 | + pps.transquant_bypass_enabled_flag as u32, | |
| 249 | + pps.tiles_enabled_flag as u32, | |
| 250 | + pps.entropy_coding_sync_enabled_flag as u32, | |
| 251 | + pps.loop_filter_across_tiles_enabled_flag as u32, | |
| 252 | + pps.loop_filter_across_slices_enabled_flag as u32, | |
| 253 | + pps.scaling_list_data_present_flag as u32, | |
| 254 | + // Screen content tools and GPU weighted prediction are not used. | |
| 255 | + false as u32, | |
| 256 | + false as u32, | |
| 257 | + // H.265 7.4.7.1: only meaningful for an IRAP picture, and the encoder never needs | |
| 258 | + // the decoder to discard already decoded pictures. | |
| 259 | + false as u32, | |
| 260 | + ); | |
| 261 | + | |
| 262 | + let curr_pic = build_h265_pic(recon, &request.dpb_meta); | |
| 263 | + | |
| 264 | + assert!(request.ref_list_0.len() + request.ref_list_1.len() <= MAX_REFERENCE_FRAMES); | |
| 265 | + | |
| 266 | + let reference_frames = | |
| 267 | + build_va_ref_pic_list(request.ref_list_0.iter().chain(request.ref_list_1.iter())); | |
| 268 | + | |
| 269 | + let nal_unit_type = nal_unit_type(request.is_idr); | |
| 270 | + | |
| 271 | + // The encoder never enables the palette mode of the screen content coding extension. | |
| 272 | + let scc_fields = HevcEncPicSccFields::new(false as u16); | |
| 273 | + | |
| 274 | + BufferType::EncPictureParameter(EncPictureParameter::HEVC(EncPictureParameterBufferHEVC::new( | |
| 275 | + curr_pic, | |
| 276 | + reference_frames, | |
| 277 | + coded_buf.id(), | |
| 278 | + NO_COLLOCATED_REF_PIC, | |
| 279 | + 0, // last_picture, don't append EOS | |
| 280 | + (pps.init_qp_minus26 + 26) as u8, | |
| 281 | + pps.diff_cu_qp_delta_depth, | |
| 282 | + pps.cb_qp_offset, | |
| 283 | + pps.cr_qp_offset, | |
| 284 | + pps.num_tile_columns_minus1, | |
| 285 | + pps.num_tile_rows_minus1, | |
| 286 | + // A single tile spans the whole picture, the tile sizes are not signalled. | |
| 287 | + [0; 19], | |
| 288 | + [0; 21], | |
| 289 | + pps.log2_parallel_merge_level_minus2, | |
| 290 | + // No limit on the size of a coded coding tree unit. | |
| 291 | + 0, | |
| 292 | + pps.num_ref_idx_l0_default_active_minus1, | |
| 293 | + pps.num_ref_idx_l1_default_active_minus1, | |
| 294 | + pps.pic_parameter_set_id, | |
| 295 | + nal_unit_type as u8, | |
| 296 | + &pic_fields, | |
| 297 | + // No hierarchical prediction structure is used. | |
| 298 | + 0, | |
| 299 | + 0, | |
| 300 | + &scc_fields, | |
| 301 | + ))) | |
| 302 | +} | |
| 303 | + | |
| 304 | +/// Builds [`BufferType::EncSliceParameter`] for the single slice segment covering the whole | |
| 305 | +/// picture. | |
| 306 | +fn build_enc_slice_param( | |
| 307 | + pps: &Pps, | |
| 308 | + slice_type: SliceType, | |
| 309 | + ref_list_0: &[Rc<DpbEntry<Reconstructed>>], | |
| 310 | + ref_list_1: &[Rc<DpbEntry<Reconstructed>>], | |
| 311 | + num_ctus: u32, | |
| 312 | +) -> BufferType { | |
| 313 | + let ref_pic_list0 = build_va_ref_pic_list(ref_list_0.iter()); | |
| 314 | + let ref_pic_list1 = build_va_ref_pic_list(ref_list_1.iter()); | |
| 315 | + | |
| 316 | + // The reference lists hold every available reference, therefore their length may differ | |
| 317 | + // from the PPS defaults and has to be overridden in the slice segment header. | |
| 318 | + let num_ref_idx_l0_active_minus1 = ref_list_0.len().saturating_sub(1) as u8; | |
| 319 | + let num_ref_idx_l1_active_minus1 = ref_list_1.len().saturating_sub(1) as u8; | |
| 320 | + | |
| 321 | + let slice_fields = HevcEncSliceFields::new( | |
| 322 | + // The single slice segment covers the whole picture. | |
| 323 | + true as u32, | |
| 324 | + false as u32, | |
| 325 | + 0, | |
| 326 | + // Temporal motion vector prediction and SAO are disabled in the SPS. | |
| 327 | + false as u32, | |
| 328 | + false as u32, | |
| 329 | + false as u32, | |
| 330 | + true as u32, | |
| 331 | + // No B slices are produced, list1 is never used. | |
| 332 | + false as u32, | |
| 333 | + false as u32, | |
| 334 | + pps.deblocking_filter_disabled_flag as u32, | |
| 335 | + pps.loop_filter_across_slices_enabled_flag as u32, | |
| 336 | + // Only meaningful with temporal motion vector prediction enabled. | |
| 337 | + true as u32, | |
| 338 | + ); | |
| 339 | + | |
| 340 | + BufferType::EncSliceParameter(EncSliceParameter::HEVC(EncSliceParameterBufferHEVC::new( | |
| 341 | + // The single slice segment starts at the first coding tree block. | |
| 342 | + 0, | |
| 343 | + num_ctus, | |
| 344 | + slice_type as u8, | |
| 345 | + pps.pic_parameter_set_id, | |
| 346 | + num_ref_idx_l0_active_minus1, | |
| 347 | + num_ref_idx_l1_active_minus1, | |
| 348 | + ref_pic_list0, | |
| 349 | + ref_pic_list1, | |
| 350 | + // Weighted prediction is disabled in the PPS, the tables are not signalled. | |
| 351 | + 0, | |
| 352 | + 0, | |
| 353 | + [0; MAX_REFERENCE_FRAMES], | |
| 354 | + [0; MAX_REFERENCE_FRAMES], | |
| 355 | + [[0; 2]; MAX_REFERENCE_FRAMES], | |
| 356 | + [[0; 2]; MAX_REFERENCE_FRAMES], | |
| 357 | + [0; MAX_REFERENCE_FRAMES], | |
| 358 | + [0; MAX_REFERENCE_FRAMES], | |
| 359 | + [[0; 2]; MAX_REFERENCE_FRAMES], | |
| 360 | + [[0; 2]; MAX_REFERENCE_FRAMES], | |
| 361 | + MAX_NUM_MERGE_CAND, | |
| 362 | + // SliceQpY is the PPS initial QP, the rate controller adjusts it on its own. | |
| 363 | + 0, | |
| 364 | + pps.cb_qp_offset, | |
| 365 | + pps.cr_qp_offset, | |
| 366 | + pps.beta_offset_div2, | |
| 367 | + pps.tc_offset_div2, | |
| 368 | + &slice_fields, | |
| 369 | + 0, | |
| 370 | + 0, | |
| 371 | + ))) | |
| 372 | +} | |
| 373 | + | |
| 374 | +impl<M, H> StatelessH265EncoderBackend for VaapiBackend<M, H> | |
| 375 | +where | |
| 376 | + M: SurfaceMemoryDescriptor, | |
| 377 | + H: Borrow<Surface<M>> + 'static, | |
| 378 | +{ | |
| 379 | + /// The slice segment headers are left to the driver, as the H.264 backend does. Note that | |
| 380 | + /// H.265 cannot fully express a slice segment header through VA-API: | |
| 381 | + /// `VAEncSequenceParameterBufferHEVC` carries neither `log2_max_pic_order_cnt_lsb_minus4` | |
| 382 | + /// nor the short term reference picture sets, and `VAEncPictureParameterBufferHEVC` has no | |
| 383 | + /// picture order count of its own, so a driver's slice segment headers may disagree with the | |
| 384 | + /// parameter sets synthesized here. On AMD VCN the driver writes a constant | |
| 385 | + /// `slice_pic_order_cnt_lsb`, which leaves intra only streams decodable but inter pictures | |
| 386 | + /// not. Supplying a packed slice segment header instead would remove that dependency on | |
| 387 | + /// driver behaviour - `VAConfigAttribEncPackedHeaders` advertises | |
| 388 | + /// `VA_ENC_PACKED_HEADER_SLICE` there - but a first attempt at it hung the encode ring, so | |
| 389 | + /// it needs its own investigation. | |
| 390 | + fn encode_slice( | |
| 391 | + &mut self, | |
| 392 | + request: Request<'_, H>, | |
| 393 | + ) -> StatelessBackendResult<(Self::ReconPromise, Self::CodedPromise)> { | |
| 394 | + let coded_buf = self.new_coded_buffer(&request.tunings.rate_control)?; | |
| 395 | + let recon = self.new_scratch_picture()?; | |
| 396 | + | |
| 397 | + // Use bitrate from RateControl or ask driver to ignore | |
| 398 | + let bits_per_second = request.tunings.rate_control.bitrate_target().unwrap_or(0) as u32; | |
| 399 | + let seq_param = build_enc_seq_param( | |
| 400 | + &request.sps, | |
| 401 | + bits_per_second, | |
| 402 | + request.intra_period, | |
| 403 | + request.ip_period, | |
| 404 | + ); | |
| 405 | + | |
| 406 | + let pic_param = build_enc_pic_param(&request, &coded_buf, &recon); | |
| 407 | + let slice_param = build_enc_slice_param( | |
| 408 | + &request.pps, | |
| 409 | + request.slice_type, | |
| 410 | + &request.ref_list_0, | |
| 411 | + &request.ref_list_1, | |
| 412 | + request.num_ctus as u32, | |
| 413 | + ); | |
| 414 | + | |
| 415 | + // Clone reference frames | |
| 416 | + let references: Vec<Rc<dyn Any>> = request | |
| 417 | + .ref_list_0 | |
| 418 | + .iter() | |
| 419 | + .cloned() | |
| 420 | + .chain(request.ref_list_1.iter().cloned()) | |
| 421 | + .map(|entry| entry as Rc<dyn Any>) | |
| 422 | + .collect(); | |
| 423 | + | |
| 424 | + // Clone picture using [`Picture::new_from_same_surface`] to avoid | |
| 425 | + // creatig a shared cell picture between its references and processed | |
| 426 | + // picture. | |
| 427 | + let mut picture = | |
| 428 | + Picture::new(request.input_meta.timestamp, Rc::clone(self.context()), request.input); | |
| 429 | + | |
| 430 | + let rc_param = | |
| 431 | + tunings_to_libva_rc::<{ MIN_QP as u32 }, { MAX_QP as u32 }>(&request.tunings)?; | |
| 432 | + let rc_param = BufferType::EncMiscParameter(libva::EncMiscParameter::RateControl(rc_param)); | |
| 433 | + | |
| 434 | + let framerate_param = BufferType::EncMiscParameter(libva::EncMiscParameter::FrameRate( | |
| 435 | + libva::EncMiscParameterFrameRate::new(request.tunings.framerate, 0), | |
| 436 | + )); | |
| 437 | + | |
| 438 | + picture.add_buffer(self.context().create_buffer(seq_param)?); | |
| 439 | + picture.add_buffer(self.context().create_buffer(pic_param)?); | |
| 440 | + picture.add_buffer(self.context().create_buffer(slice_param)?); | |
| 441 | + picture.add_buffer(self.context().create_buffer(rc_param)?); | |
| 442 | + picture.add_buffer(self.context().create_buffer(framerate_param)?); | |
| 443 | + | |
| 444 | + // Start processing the picture encoding | |
| 445 | + let picture = picture.begin().context("picture begin")?; | |
| 446 | + let picture = picture.render().context("picture render")?; | |
| 447 | + let picture = picture.end().context("picture end")?; | |
| 448 | + | |
| 449 | + // libva will handle the synchronization of reconstructed surface with implicit fences. | |
| 450 | + // Therefore return the reconstructed frame immediately. | |
| 451 | + let reference_promise = ReadyPromise::from(recon); | |
| 452 | + | |
| 453 | + let bitstream_promise = | |
| 454 | + CodedOutputPromise::new(picture, references, coded_buf, request.coded_output); | |
| 455 | + | |
| 456 | + Ok((reference_promise, bitstream_promise)) | |
| 457 | + } | |
| 458 | +} | |
| 459 | + | |
| 460 | +impl<V: VideoFrame> StatelessEncoder<V, VaapiBackend<V::MemDescriptor, Surface<V::MemDescriptor>>> { | |
| 461 | + pub fn new_vaapi( | |
| 462 | + display: Rc<Display>, | |
| 463 | + config: EncoderConfig, | |
| 464 | + fourcc: Fourcc, | |
| 465 | + coded_size: Resolution, | |
| 466 | + low_power: bool, | |
| 467 | + blocking_mode: BlockingMode, | |
| 468 | + ) -> EncodeResult<Self> { | |
| 469 | + let va_profile = match config.profile { | |
| 470 | + Profile::Main => VAProfile::VAProfileHEVCMain, | |
| 471 | + Profile::Main10 => VAProfile::VAProfileHEVCMain10, | |
| 472 | + _ => return Err(StatelessBackendError::UnsupportedProfile.into()), | |
| 473 | + }; | |
| 474 | + | |
| 475 | + let bitrate_control = match config.initial_tunings.rate_control { | |
| 476 | + RateControl::ConstantBitrate(_) => libva::VA_RC_CBR, | |
| 477 | + RateControl::ConstantQuality(_) => libva::VA_RC_CQP, | |
| 478 | + }; | |
| 479 | + | |
| 480 | + let backend = | |
| 481 | + VaapiBackend::new(display, va_profile, fourcc, coded_size, bitrate_control, low_power)?; | |
| 482 | + | |
| 483 | + Self::new_h265(backend, config, blocking_mode) | |
| 484 | + } | |
| 485 | +} | |
| 486 | + | |
| 487 | +#[cfg(test)] | |
| 488 | +pub(super) mod tests { | |
| 489 | + use libva::Display; | |
| 490 | + use libva::UsageHint; | |
| 491 | + use libva::VAEntrypoint::VAEntrypointEncSliceLP; | |
| 492 | + use libva::VAProfile::VAProfileHEVCMain; | |
| 493 | + use libva::VA_RT_FORMAT_YUV420; | |
| 494 | + | |
| 495 | + use super::*; | |
| 496 | + use crate::backend::vaapi::encoder::tests::upload_test_frame_nv12; | |
| 497 | + use crate::backend::vaapi::encoder::tests::TestFrameGenerator; | |
| 498 | + use crate::backend::vaapi::surface_pool::PooledVaSurface; | |
| 499 | + use crate::backend::vaapi::surface_pool::VaSurfacePool; | |
| 500 | + use crate::codec::h265::parser::Level; | |
| 501 | + use crate::codec::h265::parser::PpsBuilder; | |
| 502 | + use crate::codec::h265::parser::Profile; | |
| 503 | + use crate::codec::h265::parser::SpsBuilder; | |
| 504 | + use crate::codec::h265::parser::Vps; | |
| 505 | + use crate::codec::h265::parser::VpsBuilder; | |
| 506 | + use crate::codec::h265::synthesizer::Synthesizer; | |
| 507 | + use crate::decoder::FramePool; | |
| 508 | + use crate::encoder::simple_encode_loop; | |
| 509 | + use crate::encoder::stateless::h265::BackendRequest; | |
| 510 | + use crate::encoder::stateless::h265::EncoderConfig; | |
| 511 | + use crate::encoder::stateless::h265::StatelessEncoder; | |
| 512 | + use crate::encoder::stateless::BackendPromise; | |
| 513 | + use crate::encoder::stateless::StatelessEncoderBackendImport; | |
| 514 | + use crate::encoder::FrameMetadata; | |
| 515 | + use crate::encoder::Tunings; | |
| 516 | + use crate::FrameLayout; | |
| 517 | + use crate::PlaneLayout; | |
| 518 | + use crate::Resolution; | |
| 519 | + | |
| 520 | + #[test] | |
| 521 | + // Ignore this test by default as it requires libva-compatible hardware. | |
| 522 | + #[ignore] | |
| 523 | + fn test_simple_encode_slice() { | |
| 524 | + type Descriptor = (); | |
| 525 | + type Surface = libva::Surface<Descriptor>; | |
| 526 | + // Some drivers refuse smaller HEVC encode contexts, eg. AMD VCN requires at least | |
| 527 | + // 384x384. | |
| 528 | + const WIDTH: u32 = 512; | |
| 529 | + const HEIGHT: u32 = 512; | |
| 530 | + let fourcc = b"NV12".into(); | |
| 531 | + | |
| 532 | + let frame_layout = FrameLayout { | |
| 533 | + format: (fourcc, 0), | |
| 534 | + size: Resolution { width: WIDTH, height: HEIGHT }, | |
| 535 | + planes: vec![ | |
| 536 | + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH as usize }, | |
| 537 | + PlaneLayout { | |
| 538 | + buffer_index: 0, | |
| 539 | + offset: (WIDTH * HEIGHT) as usize, | |
| 540 | + stride: WIDTH as usize, | |
| 541 | + }, | |
| 542 | + ], | |
| 543 | + }; | |
| 544 | + | |
| 545 | + let display = Display::open().unwrap(); | |
| 546 | + let entrypoints = display.query_config_entrypoints(VAProfileHEVCMain).unwrap(); | |
| 547 | + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); | |
| 548 | + | |
| 549 | + let mut backend = VaapiBackend::<Descriptor, Surface>::new( | |
| 550 | + Rc::clone(&display), | |
| 551 | + VAProfileHEVCMain, | |
| 552 | + fourcc, | |
| 553 | + Resolution { width: WIDTH, height: HEIGHT }, | |
| 554 | + libva::VA_RC_CBR, | |
| 555 | + low_power, | |
| 556 | + ) | |
| 557 | + .unwrap(); | |
| 558 | + | |
| 559 | + let mut surfaces = display | |
| 560 | + .create_surfaces( | |
| 561 | + VA_RT_FORMAT_YUV420, | |
| 562 | + Some(frame_layout.format.0 .0), | |
| 563 | + WIDTH, | |
| 564 | + HEIGHT, | |
| 565 | + Some(UsageHint::USAGE_HINT_ENCODER), | |
| 566 | + vec![()], | |
| 567 | + ) | |
| 568 | + .unwrap(); | |
| 569 | + | |
| 570 | + let surface = surfaces.pop().unwrap(); | |
| 571 | + | |
| 572 | + upload_test_frame_nv12(&display, &surface, 0.0); | |
| 573 | + | |
| 574 | + let input_meta = | |
| 575 | + FrameMetadata { layout: frame_layout, force_keyframe: false, timestamp: 0 }; | |
| 576 | + | |
| 577 | + let pic = backend.import_picture(&input_meta, surface).unwrap(); | |
| 578 | + | |
| 579 | + let vps = VpsBuilder::new() | |
| 580 | + .video_parameter_set_id(0) | |
| 581 | + .general_profile(Profile::Main) | |
| 582 | + .general_level_idc(Level::L4) | |
| 583 | + .max_dec_pic_buffering_minus1(1) | |
| 584 | + .build(); | |
| 585 | + | |
| 586 | + let sps = SpsBuilder::new(Rc::clone(&vps)) | |
| 587 | + .seq_parameter_set_id(0) | |
| 588 | + .chroma_format_idc(1) | |
| 589 | + .resolution(WIDTH, HEIGHT) | |
| 590 | + .bit_depth_luma(8) | |
| 591 | + .bit_depth_chroma(8) | |
| 592 | + .max_pic_order_cnt_lsb(256) | |
| 593 | + .max_dec_pic_buffering_minus1(1) | |
| 594 | + .build(); | |
| 595 | + | |
| 596 | + let pps = PpsBuilder::new(Rc::clone(&sps)) | |
| 597 | + .pic_parameter_set_id(0) | |
| 598 | + .init_qp(26) | |
| 599 | + .deblocking_filter_control_present_flag(true) | |
| 600 | + .build(); | |
| 601 | + | |
| 602 | + let dpb_entry_meta = DpbEntryMeta { poc: 0, is_reference: IsReference::ShortTerm }; | |
| 603 | + | |
| 604 | + let request = BackendRequest { | |
| 605 | + sps: Rc::clone(&sps), | |
| 606 | + pps: Rc::clone(&pps), | |
| 607 | + slice_type: SliceType::I, | |
| 608 | + dpb_meta: dpb_entry_meta, | |
| 609 | + input: pic, | |
| 610 | + input_meta, | |
| 611 | + ref_list_0: vec![], | |
| 612 | + ref_list_1: vec![], | |
| 613 | + intra_period: 1, | |
| 614 | + ip_period: 0, | |
| 615 | + num_ctus: sps.pic_size_in_ctbs_y as usize, | |
| 616 | + is_idr: true, | |
| 617 | + tunings: Tunings { | |
| 618 | + rate_control: RateControl::ConstantBitrate(30_000), | |
| 619 | + ..Default::default() | |
| 620 | + }, | |
| 621 | + coded_output: vec![], | |
| 622 | + }; | |
| 623 | + | |
| 624 | + let (_, output) = backend.encode_slice(request).unwrap(); | |
| 625 | + let output = output.sync().unwrap(); | |
| 626 | + | |
| 627 | + assert!(!output.is_empty()); | |
| 628 | + | |
| 629 | + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); | |
| 630 | + if write_to_file { | |
| 631 | + use std::io::Write; | |
| 632 | + | |
| 633 | + let mut out = std::fs::File::create("test_simple_encode_slice.h265").unwrap(); | |
| 634 | + | |
| 635 | + Synthesizer::<'_, Vps, &mut std::fs::File>::synthesize(1, &vps, &mut out, true) | |
| 636 | + .unwrap(); | |
| 637 | + Synthesizer::<'_, Sps, &mut std::fs::File>::synthesize(1, &sps, &mut out, true) | |
| 638 | + .unwrap(); | |
| 639 | + Synthesizer::<'_, Pps, &mut std::fs::File>::synthesize(1, &pps, &mut out, true) | |
| 640 | + .unwrap(); | |
| 641 | + out.write_all(&output).unwrap(); | |
| 642 | + out.flush().unwrap(); | |
| 643 | + } | |
| 644 | + } | |
| 645 | + | |
| 646 | + #[test] | |
| 647 | + // Ignore this test by default as it requires libva-compatible hardware. | |
| 648 | + #[ignore] | |
| 649 | + fn test_vaapi_encoder() { | |
| 650 | + type VaapiH265Encoder<'l> = | |
| 651 | + StatelessEncoder<PooledVaSurface<()>, VaapiBackend<(), PooledVaSurface<()>>>; | |
| 652 | + | |
| 653 | + const WIDTH: usize = 512; | |
| 654 | + const HEIGHT: usize = 512; | |
| 655 | + | |
| 656 | + let _ = env_logger::try_init(); | |
| 657 | + | |
| 658 | + let display = libva::Display::open().unwrap(); | |
| 659 | + let entrypoints = display.query_config_entrypoints(VAProfileHEVCMain).unwrap(); | |
| 660 | + let low_power = entrypoints.contains(&VAEntrypointEncSliceLP); | |
| 661 | + | |
| 662 | + let config = EncoderConfig { | |
| 663 | + profile: Profile::Main, | |
| 664 | + resolution: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, | |
| 665 | + initial_tunings: Tunings { | |
| 666 | + rate_control: RateControl::ConstantBitrate(1_200_000), | |
| 667 | + framerate: 30, | |
| 668 | + ..Default::default() | |
| 669 | + }, | |
| 670 | + ..Default::default() | |
| 671 | + }; | |
| 672 | + | |
| 673 | + let frame_layout = FrameLayout { | |
| 674 | + format: (b"NV12".into(), 0), | |
| 675 | + size: Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, | |
| 676 | + planes: vec![ | |
| 677 | + PlaneLayout { buffer_index: 0, offset: 0, stride: WIDTH }, | |
| 678 | + PlaneLayout { buffer_index: 0, offset: WIDTH * HEIGHT, stride: WIDTH }, | |
| 679 | + ], | |
| 680 | + }; | |
| 681 | + | |
| 682 | + // [`StatelessEncoder::new_vaapi`] only accepts [`VideoFrame`] handles, whereas the test | |
| 683 | + // frame generator hands out pooled VA surfaces, hence the backend is built by hand. | |
| 684 | + let backend = VaapiBackend::new( | |
| 685 | + Rc::clone(&display), | |
| 686 | + VAProfileHEVCMain, | |
| 687 | + frame_layout.format.0, | |
| 688 | + frame_layout.size, | |
| 689 | + libva::VA_RC_CBR, | |
| 690 | + low_power, | |
| 691 | + ) | |
| 692 | + .unwrap(); | |
| 693 | + | |
| 694 | + let mut encoder = | |
| 695 | + VaapiH265Encoder::new_h265(backend, config, BlockingMode::Blocking).unwrap(); | |
| 696 | + | |
| 697 | + let mut pool = VaSurfacePool::new( | |
| 698 | + Rc::clone(&display), | |
| 699 | + VA_RT_FORMAT_YUV420, | |
| 700 | + Some(UsageHint::USAGE_HINT_ENCODER), | |
| 701 | + Resolution { width: WIDTH as u32, height: HEIGHT as u32 }, | |
| 702 | + ); | |
| 703 | + | |
| 704 | + pool.add_frames(vec![(); 16]).unwrap(); | |
| 705 | + | |
| 706 | + let mut frame_producer = TestFrameGenerator::new(100, display, pool, frame_layout); | |
| 707 | + | |
| 708 | + let mut bitstream = Vec::new(); | |
| 709 | + | |
| 710 | + simple_encode_loop(&mut encoder, &mut frame_producer, |coded| { | |
| 711 | + bitstream.extend(coded.bitstream) | |
| 712 | + }) | |
| 713 | + .unwrap(); | |
| 714 | + | |
| 715 | + assert!(!bitstream.is_empty()); | |
| 716 | + | |
| 717 | + let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true"); | |
| 718 | + if write_to_file { | |
| 719 | + use std::io::Write; | |
| 720 | + let mut out = std::fs::File::create("test_vaapi_encoder.h265").unwrap(); | |
| 721 | + out.write_all(&bitstream).unwrap(); | |
| 722 | + out.flush().unwrap(); | |
| 723 | + } | |
| 724 | + } | |
| 725 | +} |