From 213534f65a1eacbbddacd32bed1b1727ba942d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:40:40 +0300 Subject: [PATCH] U17: vk-video-ffi delete every example except caps.rs and the example-only ec-*-syntax dev-dependencies --- Cargo.lock | 3 - shims/vk-video-ffi/Cargo.toml | 5 - .../vk-video-ffi/examples/av1_decode_smoke.rs | 320 -------- shims/vk-video-ffi/examples/d3d11_pool.rs | 111 --- shims/vk-video-ffi/examples/dmabuf_smoke.rs | 767 ------------------ .../examples/h264_decode_smoke.rs | 182 ----- .../examples/h265_decode_smoke.rs | 284 ------- 7 files changed, 1672 deletions(-) delete mode 100644 shims/vk-video-ffi/examples/av1_decode_smoke.rs delete mode 100644 shims/vk-video-ffi/examples/d3d11_pool.rs delete mode 100644 shims/vk-video-ffi/examples/dmabuf_smoke.rs delete mode 100644 shims/vk-video-ffi/examples/h264_decode_smoke.rs delete mode 100644 shims/vk-video-ffi/examples/h265_decode_smoke.rs diff --git a/Cargo.lock b/Cargo.lock index 3979e7cf..35c4ca9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2063,9 +2063,6 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "vk-video-ffi" version = "0.1.0" dependencies = [ - "ec-av1-syntax", - "ec-h264-syntax", - "ec-h265-syntax", "vulkanalia", "windows", ] diff --git a/shims/vk-video-ffi/Cargo.toml b/shims/vk-video-ffi/Cargo.toml index b9f3e3d4..b83025f3 100644 --- a/shims/vk-video-ffi/Cargo.toml +++ b/shims/vk-video-ffi/Cargo.toml @@ -17,10 +17,5 @@ windows = { version = "0.62.2", features = [ "Win32_Graphics_Dxgi_Common", ] } -[dev-dependencies] -ec-av1-syntax.workspace = true -ec-h264-syntax.workspace = true -ec-h265-syntax.workspace = true - [target.'cfg(windows)'.dev-dependencies] windows = { version = "0.62.2", features = ["Win32_Graphics_Direct3D"] } diff --git a/shims/vk-video-ffi/examples/av1_decode_smoke.rs b/shims/vk-video-ffi/examples/av1_decode_smoke.rs deleted file mode 100644 index fb448bc7..00000000 --- a/shims/vk-video-ffi/examples/av1_decode_smoke.rs +++ /dev/null @@ -1,320 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use ec_av1_syntax::{ - Av1Parser, ChromaSamplePosition, ColorConfig, FrameHeader, FrameType, InterpolationFilter, - ObuKind, RestorationType, SequenceHeader, TxMode, WarpModel, -}; -use vk_video_ffi::{ - Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, - Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, - Av1LoopRestoration, Av1Quantization, Av1Restoration, Av1Segmentation, Av1SequenceHeader, - Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Gpu, -}; - -fn color(c: &ColorConfig) -> Av1ColorConfig { - Av1ColorConfig { - bit_depth: c.bit_depth, - mono_chrome: c.mono_chrome, - color_range: c.color_range, - separate_uv_delta_q: c.separate_uv_delta_q, - subsampling_x: c.subsampling_x, - subsampling_y: c.subsampling_y, - color_primaries: c.color_primaries, - transfer_characteristics: c.transfer_characteristics, - matrix_coefficients: c.matrix_coefficients, - chroma_sample_position: match c.chroma_sample_position { - ChromaSamplePosition::Unknown => 0, - ChromaSamplePosition::Vertical => 1, - ChromaSamplePosition::Colocated => 2, - ChromaSamplePosition::Reserved => 3, - }, - } -} - -fn sequence(s: &SequenceHeader) -> Av1SequenceHeader { - Av1SequenceHeader { - seq_profile: s.seq_profile, - still_picture: s.still_picture, - reduced_still_picture_header: s.reduced_still_picture_header, - timing_info: s.timing_info.map(|t| Av1TimingInfo { - equal_picture_interval: t.equal_picture_interval, - num_units_in_display_tick: t.num_units_in_display_tick, - time_scale: t.time_scale, - num_ticks_per_picture_minus_1: t.num_ticks_per_picture.saturating_sub(1), - }), - initial_display_delay_present: s.initial_display_delay_present_flag, - frame_width_bits_minus_1: (s.frame_width_bits - 1) as u8, - frame_height_bits_minus_1: (s.frame_height_bits - 1) as u8, - max_frame_width_minus_1: (s.max_frame_width - 1) as u16, - max_frame_height_minus_1: (s.max_frame_height - 1) as u16, - frame_id_numbers_present: s.frame_id_numbers_present_flag, - delta_frame_id_length_minus_2: s.delta_frame_id_length.saturating_sub(2) as u8, - additional_frame_id_length_minus_1: s.additional_frame_id_length.saturating_sub(1) as u8, - order_hint_bits_minus_1: s.order_hint_bits.saturating_sub(1) as u8, - seq_force_integer_mv: s.seq_force_integer_mv, - seq_force_screen_content_tools: s.seq_force_screen_content_tools, - use_128x128_superblock: s.use_128x128_superblock, - enable_filter_intra: s.enable_filter_intra, - enable_intra_edge_filter: s.enable_intra_edge_filter, - enable_interintra_compound: s.enable_interintra_compound, - enable_masked_compound: s.enable_masked_compound, - enable_warped_motion: s.enable_warped_motion, - enable_dual_filter: s.enable_dual_filter, - enable_order_hint: s.enable_order_hint, - enable_jnt_comp: s.enable_jnt_comp, - enable_ref_frame_mvs: s.enable_ref_frame_mvs, - enable_superres: s.enable_superres, - enable_cdef: s.enable_cdef, - enable_restoration: s.enable_restoration, - color_config: color(&s.color_config), - film_grain_params_present: s.film_grain_params_present, - } -} - -fn restoration(r: RestorationType) -> Av1Restoration { - match r { - RestorationType::None => Av1Restoration::None, - RestorationType::Wiener => Av1Restoration::Wiener, - RestorationType::Sgrproj => Av1Restoration::Sgrproj, - RestorationType::Switchable => Av1Restoration::Switchable, - } -} - -fn frame(h: &FrameHeader, s: &SequenceHeader) -> Av1FrameHeader { - let sb_shift = s.sb_shift(); - let mut global_motion = [Av1GlobalMotion::default(); 8]; - let mut order_hints = [0u8; 8]; - for i in 0..7 { - global_motion[i + 1] = Av1GlobalMotion { - model: match h.global_motion[i].model { - WarpModel::Identity => Av1WarpModel::Identity, - WarpModel::Translation => Av1WarpModel::Translation, - WarpModel::Rotzoom => Av1WarpModel::Rotzoom, - WarpModel::Affine => Av1WarpModel::Affine, - }, - params: h.global_motion[i].params, - }; - order_hints[i + 1] = h.order_hints[i] as u8; - } - Av1FrameHeader { - frame_type: match h.frame_type { - FrameType::Key => Av1FrameType::Key, - FrameType::Inter => Av1FrameType::Inter, - FrameType::IntraOnly => Av1FrameType::IntraOnly, - FrameType::Switch => Av1FrameType::Switch, - }, - show_frame: h.show_frame, - showable_frame: h.showable_frame, - error_resilient_mode: h.error_resilient_mode, - disable_cdf_update: h.disable_cdf_update, - allow_screen_content_tools: h.allow_screen_content_tools, - force_integer_mv: h.force_integer_mv, - current_frame_id: h.current_frame_id, - frame_size_override_flag: h.frame_size_override_flag, - order_hint: h.order_hint as u8, - primary_ref_frame: h.primary_ref_frame, - refresh_frame_flags: h.refresh_frame_flags, - frame_width: h.frame_width, - frame_height: h.frame_height, - upscaled_width: h.upscaled_width, - render_width: h.render_width, - render_height: h.render_height, - use_superres: h.use_superres, - superres_denom: h.superres_denom, - allow_intrabc: h.allow_intrabc, - allow_high_precision_mv: h.allow_high_precision_mv, - is_motion_mode_switchable: h.is_motion_mode_switchable, - use_ref_frame_mvs: h.use_ref_frame_mvs, - frame_refs_short_signaling: h.frame_refs_short_signaling, - disable_frame_end_update_cdf: h.disable_frame_end_update_cdf, - reference_select: h.reference_select, - skip_mode_present: h.skip_mode_present, - allow_warped_motion: h.allow_warped_motion, - reduced_tx_set: h.reduced_tx_set, - interpolation_filter: match h.interpolation_filter { - InterpolationFilter::Eighttap => Av1InterpolationFilter::EightTap, - InterpolationFilter::EighttapSmooth => Av1InterpolationFilter::EightTapSmooth, - InterpolationFilter::EighttapSharp => Av1InterpolationFilter::EightTapSharp, - InterpolationFilter::Bilinear => Av1InterpolationFilter::Bilinear, - InterpolationFilter::Switchable => Av1InterpolationFilter::Switchable, - }, - tx_mode: match h.tx_mode { - TxMode::Only4x4 => Av1TxMode::Only4x4, - TxMode::Largest => Av1TxMode::Largest, - TxMode::Select => Av1TxMode::Select, - }, - tile_info: Av1TileInfo { - uniform_spacing: h.tile_info.uniform_spacing, - cols: h.tile_info.cols as u8, - rows: h.tile_info.rows as u8, - mi_col_starts: h - .tile_info - .mi_col_starts - .iter() - .map(|&v| v as u16) - .collect(), - mi_row_starts: h - .tile_info - .mi_row_starts - .iter() - .map(|&v| v as u16) - .collect(), - width_in_sbs_minus_1: h.tile_info.width_in_sbs_minus_1(sb_shift), - height_in_sbs_minus_1: h.tile_info.height_in_sbs_minus_1(sb_shift), - context_update_tile_id: h.tile_info.context_update_tile_id as u16, - tile_size_bytes_minus_1: h.tile_info.tile_size_bytes.saturating_sub(1) as u8, - }, - quantization: Av1Quantization { - base_q_idx: h.quantization.base_q_idx, - delta_q_y_dc: h.quantization.delta_q_y_dc, - delta_q_u_dc: h.quantization.delta_q_u_dc, - delta_q_u_ac: h.quantization.delta_q_u_ac, - delta_q_v_dc: h.quantization.delta_q_v_dc, - delta_q_v_ac: h.quantization.delta_q_v_ac, - using_qmatrix: h.quantization.using_qmatrix, - qm_y: h.quantization.qm_y, - qm_u: h.quantization.qm_u, - qm_v: h.quantization.qm_v, - }, - segmentation: Av1Segmentation { - enabled: h.segmentation.enabled, - update_map: h.segmentation.update_map, - temporal_update: h.segmentation.temporal_update, - update_data: h.segmentation.update_data, - feature_enabled: h.segmentation.feature_enabled, - feature_data: h.segmentation.feature_data, - }, - delta: Av1DeltaParams { - q_present: h.delta.q_present, - q_res: h.delta.q_res, - lf_present: h.delta.lf_present, - lf_res: h.delta.lf_res, - lf_multi: h.delta.lf_multi, - }, - loop_filter: Av1LoopFilter { - level: h.loop_filter.level, - sharpness: h.loop_filter.sharpness, - delta_enabled: h.loop_filter.delta_enabled, - delta_update: h.loop_filter.delta_update, - ref_deltas: h.loop_filter.ref_deltas, - mode_deltas: h.loop_filter.mode_deltas, - }, - cdef: Av1Cdef { - damping_minus_3: h.cdef.damping.saturating_sub(3), - bits: h.cdef.bits, - y_pri: h.cdef.y_pri_strength, - y_sec: h.cdef.y_sec_strength, - uv_pri: h.cdef.uv_pri_strength, - uv_sec: h.cdef.uv_sec_strength, - }, - loop_restoration: Av1LoopRestoration { - frame_restoration_type: h.loop_restoration.frame_restoration_type.map(restoration), - loop_restoration_size: h.loop_restoration.loop_restoration_size.map(|v| v as u16), - }, - global_motion, - order_hints, - skip_mode_frame: h.skip_mode_frame, - expected_frame_id: [0; 8], - apply_grain: h.film_grain.apply_grain, - } -} - -fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs()) - .sum::() - / a.len() as f64 -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("key.ivf"); - let reference = dir.join("av1_ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args(["-frames:v", "1", "-c:v", "libsvtav1", "-f", "ivf"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let ivf = fs::read(&stream).expect("read ivf"); - let header_len = u16::from_le_bytes([ivf[6], ivf[7]]) as usize; - let frame_len = - u32::from_le_bytes(ivf[header_len..header_len + 4].try_into().unwrap()) as usize; - let data = &ivf[header_len + 12..header_len + 12 + frame_len]; - - let mut parser = Av1Parser::new(); - let obus = parser - .parse_temporal_unit(data) - .expect("parse temporal unit"); - let mut seq = None; - let mut frame_obu = None; - for obu in obus { - match obu.kind { - ObuKind::SequenceHeader(s) => seq = Some(*s), - ObuKind::Frame(h, tiles) => frame_obu = Some((*h, tiles)), - _ => {} - } - } - let seq = seq.expect("sequence header"); - let (header, tiles) = frame_obu.expect("frame OBU"); - assert_eq!(header.frame_type, FrameType::Key); - - let offsets: Vec = tiles.iter().map(|t| t.offset as u32).collect(); - let sizes: Vec = tiles.iter().map(|t| t.size as u32).collect(); - let plain_seq = sequence(&seq); - let plain_frame = frame(&header, &seq); - let (w, h) = (header.upscaled_width, header.frame_height); - - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = Av1DecodeConfig { - max_width: w, - max_height: h, - max_dpb_slots: 9, - bit_depth: 8, - }; - let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_sequence_header(&plain_seq) - .expect("sequence header"); - let pic = Av1DecodePicture { - header: &plain_frame, - setup_slot: 0, - ref_frame_slot: [-1; 7], - refs: &[], - tile_data: data, - tile_offsets: &offsets, - tile_sizes: &sizes, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let reference = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_uv: Vec = reference[luma..luma + chroma] - .iter() - .zip(&reference[luma + chroma..luma + 2 * chroma]) - .flat_map(|(&u, &v)| [u, v]) - .collect(); - println!( - "mean abs diff Y: {:.6}", - mean_abs_diff(&y, &reference[..luma]) - ); - println!("mean abs diff UV: {:.6}", mean_abs_diff(&uv, &ref_uv)); -} diff --git a/shims/vk-video-ffi/examples/d3d11_pool.rs b/shims/vk-video-ffi/examples/d3d11_pool.rs deleted file mode 100644 index 102b0523..00000000 --- a/shims/vk-video-ffi/examples/d3d11_pool.rs +++ /dev/null @@ -1,111 +0,0 @@ -#[cfg(windows)] -fn main() { - use std::os::windows::io::AsRawHandle; - - use vk_video_ffi::D3d11Pool; - use windows::Win32::Foundation::{HANDLE, HMODULE}; - use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_WARP; - use windows::Win32::Graphics::Direct3D11::{ - D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ, - D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, - D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11Device1, - ID3D11Texture2D, - }; - use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC}; - use windows::core::Interface; - - let (w, h) = (256u32, 144u32); - let mut device: Option = None; - unsafe { - D3D11CreateDevice( - None, - D3D_DRIVER_TYPE_WARP, - HMODULE::default(), - D3D11_CREATE_DEVICE_BGRA_SUPPORT, - None, - D3D11_SDK_VERSION, - Some(&mut device), - None, - None, - ) - .expect("WARP device"); - } - let device = device.expect("device"); - let context = unsafe { device.GetImmediateContext() }.expect("context"); - let desc = |usage, cpu: u32, bind: u32| D3D11_TEXTURE2D_DESC { - Width: w, - Height: h, - MipLevels: 1, - ArraySize: 1, - Format: DXGI_FORMAT_B8G8R8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Usage: usage, - BindFlags: bind, - CPUAccessFlags: cpu, - MiscFlags: 0, - }; - let mut pool = D3d11Pool::new(&device).expect("pool"); - let mut ids = Vec::new(); - for round in 0..6u32 { - let pixels: Vec = (0..w * h * 4).map(|i| (i * 7 + round * 13) as u8).collect(); - let init = D3D11_SUBRESOURCE_DATA { - pSysMem: pixels.as_ptr().cast(), - SysMemPitch: w * 4, - SysMemSlicePitch: 0, - }; - let mut src: Option = None; - unsafe { - device - .CreateTexture2D(&desc(D3D11_USAGE_DEFAULT, 0, 8), Some(&init), Some(&mut src)) - .expect("source texture"); - } - let src = src.expect("source"); - let frame = pool.submit(&src).expect("submit"); - ids.push(frame.id); - let dev1: ID3D11Device1 = device.cast().expect("ID3D11Device1"); - let opened: ID3D11Texture2D = - unsafe { dev1.OpenSharedResource1(HANDLE(frame.handle.as_raw_handle())) } - .expect("OpenSharedResource1"); - let mut staging: Option = None; - unsafe { - device - .CreateTexture2D( - &desc(D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ.0 as u32, 0), - None, - Some(&mut staging), - ) - .expect("staging"); - } - let staging = staging.expect("staging"); - let mut got = vec![0u8; pixels.len()]; - unsafe { - context.CopyResource(&staging, &opened); - let mut map = D3D11_MAPPED_SUBRESOURCE::default(); - context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut map)).expect("map"); - for y in 0..h as usize { - let row = std::slice::from_raw_parts( - map.pData.cast::().add(y * map.RowPitch as usize), - w as usize * 4, - ); - got[y * w as usize * 4..][..w as usize * 4].copy_from_slice(row); - } - context.Unmap(&staging, 0); - } - println!( - "round {round} id {} {}x{} bgr {} {}", - frame.id, - frame.width, - frame.height, - frame.bgr, - if got == pixels { "identical" } else { "DIFFERS" } - ); - } - println!("ids {ids:?}"); - match vk_video_ffi::Gpu::open() { - Ok(gpu) => println!("vulkan: importable bgr {}", vk_video_ffi::d3d11_importable(&gpu, true)), - Err(e) => println!("vulkan: {e}"), - } -} - -#[cfg(not(windows))] -fn main() {} diff --git a/shims/vk-video-ffi/examples/dmabuf_smoke.rs b/shims/vk-video-ffi/examples/dmabuf_smoke.rs deleted file mode 100644 index 1f303cc0..00000000 --- a/shims/vk-video-ffi/examples/dmabuf_smoke.rs +++ /dev/null @@ -1,767 +0,0 @@ -use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; - -use vk_video_ffi::{ - Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane, - Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, - H265EncodeSession, H265Picture, H265Ref, H264Profile, RateControl, -}; -use vulkanalia::prelude::v1_3::*; -use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands; - -const W: u32 = 1280; -const H: u32 = 720; -const FRAMES: usize = 10; -const FPS: (u32, u32) = (30, 1); -const RATE: RateControl = RateControl::ConstantQp { qp: 28 }; -const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM; -const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM; -const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16; - -struct Export { - image: vk::Image, - memory: vk::DeviceMemory, - fd: OwnedFd, - modifier: u64, - planes: Vec, -} - -impl Export { - fn destroy(&self, d: &Device) { - unsafe { - d.destroy_image(self.image, None); - d.free_memory(self.memory, None); - } - } -} - -struct Pattern { - bits: u8, - y: Vec, - uv: Vec, -} - -impl Pattern { - fn new(bits: u8) -> Self { - let max = (1u32 << bits) - 1; - let y = (0..W * H) - .map(|i| { - let (x, row) = (i % W, i / W); - ((x * max / (W - 1) + row * max / (H - 1)) / 2) as u16 - }) - .collect(); - let uv = (0..W * H / 2) - .map(|i| ((i * 7) % (max + 1)) as u16) - .collect(); - Pattern { bits, y, uv } - } - - fn y8(&self) -> Vec { - self.y.iter().map(|&v| v as u8).collect() - } - - fn uv8(&self) -> Vec { - self.uv.iter().map(|&v| v as u8).collect() - } - - fn device(&self) -> Vec { - let samples = self.y.iter().chain(&self.uv); - if self.bits == 8 { - samples.map(|&v| v as u8).collect() - } else { - samples.flat_map(|&v| (v << 6).to_le_bytes()).collect() - } - } -} - -trait Encode: Sized { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result; - fn rgb(&mut self, host: &[u8], frame: usize) -> Result, Error>; - fn planar(&mut self, pattern: &Pattern, frame: usize) -> Result, Error>; - fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result, Error>; -} - -impl Encode for H264EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), _bits: u8) -> Result { - let cfg = H264EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - profile: H264Profile::High, - level: 62, - colour: None, - quality: 0, - }; - H264EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = h264_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, pattern: &Pattern, i: usize) -> Result, Error> { - self.encode(&pattern.y8(), &pattern.uv8(), &h264_picture(i)) - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &h264_picture(i)) - } -} - -fn h264_picture(i: usize) -> H264Picture { - H264Picture { - idr: i == 0, - idr_pic_id: 0, - frame_num: i as u32, - poc: 2 * i as i32, - slot: (i % 2) as u32, - reference: (i > 0).then(|| H264Ref { - slot: ((i - 1) % 2) as u32, - frame_num: (i - 1) as u32, - poc: 2 * (i - 1) as i32, - }), - } -} - -impl Encode for H265EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result { - let cfg = H265EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - bit_depth: bits, - level: 186, - colour: None, - quality: 0, - }; - H265EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = h265_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, p: &Pattern, i: usize) -> Result, Error> { - let pic = h265_picture(i); - if p.bits == 8 { - self.encode(&p.y8(), &p.uv8(), &pic) - } else { - self.encode_16(&p.y, &p.uv, &pic) - } - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &h265_picture(i)) - } -} - -fn h265_picture(i: usize) -> H265Picture { - H265Picture { - idr: i == 0, - poc: 2 * i as i32, - slot: (i % 2) as u32, - reference: (i > 0).then(|| H265Ref { - slot: ((i - 1) % 2) as u32, - poc: 2 * (i - 1) as i32, - }), - keep: [None; vk_video_ffi::DPB_SLOTS], - } -} - -impl Encode for Av1EncodeSession { - fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result { - let cfg = Av1EncodeConfig { - width: size.0, - height: size.1, - fps: FPS, - rate: RATE, - bit_depth: bits, - level: 23, - colour: None, - quality: 0, - }; - Av1EncodeSession::new(gpu, &cfg) - } - - fn rgb(&mut self, host: &[u8], i: usize) -> Result, Error> { - let pic = av1_picture(i); - self.encode_rgb(host, W, H, W * 4, true, &pic) - } - - fn planar(&mut self, p: &Pattern, i: usize) -> Result, Error> { - let pic = av1_picture(i); - if p.bits == 8 { - self.encode(&p.y8(), &p.uv8(), &pic) - } else { - self.encode_16(&p.y, &p.uv, &pic) - } - } - - fn dma(&mut self, src: &DmaBuf, i: usize) -> Result, Error> { - self.encode_dmabuf(src, &av1_picture(i)) - } -} - -fn av1_picture(i: usize) -> Av1Picture { - Av1Picture { - key: i == 0, - order_hint: i as u8, - slot: (i % 2) as u32, - reference: (i > 0).then(|| Av1Ref { - slot: ((i - 1) % 2) as u32, - order_hint: (i - 1) as u8, - }), - } -} - -fn gradient() -> Vec { - let mut out = Vec::with_capacity((W * H * 4) as usize); - for y in 0..H { - for x in 0..W { - out.extend([ - (x * 255 / (W - 1)) as u8, - (y * 255 / (H - 1)) as u8, - (x ^ y) as u8, - 255, - ]); - } - } - out -} - -fn memory_index( - instance: &Instance, - physical: vk::PhysicalDevice, - bits: u32, - flags: vk::MemoryPropertyFlags, -) -> u32 { - let props = unsafe { instance.get_physical_device_memory_properties(physical) }; - (0..props.memory_type_count) - .find(|&i| { - bits & (1 << i) != 0 - && props.memory_types[i as usize] - .property_flags - .contains(flags) - }) - .expect("memory type") -} - -fn pick_modifier( - instance: &Instance, - physical: vk::PhysicalDevice, - format: vk::Format, - planes: u32, -) -> Option { - let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build(); - let mut props = vk::FormatProperties2::builder() - .push_next(&mut list) - .build(); - unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) }; - let count = list.drm_format_modifier_count as usize; - - let mut entries: Vec = (0..count) - .map(|_| vk::DrmFormatModifierPropertiesEXT::builder().build()) - .collect(); - let mut list = vk::DrmFormatModifierPropertiesListEXT::builder() - .drm_format_modifier_properties(&mut entries) - .build(); - let mut props = vk::FormatProperties2::builder() - .push_next(&mut list) - .build(); - unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) }; - - let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST; - entries - .iter() - .find(|e| { - e.drm_format_modifier != 0 - && e.drm_format_modifier_plane_count == planes - && e.drm_format_modifier_tiling_features.contains(want) - }) - .map(|e| e.drm_format_modifier) -} - -fn export( - instance: &Instance, - physical: vk::PhysicalDevice, - d: &Device, - queue: vk::Queue, - family: u32, - format: vk::Format, - modifier: u64, - host: &[u8], - regions: &[(vk::ImageAspectFlags, u64, u32, u32)], - memory_planes: usize, -) -> Export { - let modifiers = [modifier]; - let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder() - .drm_format_modifiers(&modifiers) - .build(); - let mut external = vk::ExternalMemoryImageCreateInfo::builder() - .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let info = vk::ImageCreateInfo::builder() - .image_type(vk::ImageType::_2D) - .format(format) - .extent(vk::Extent3D { - width: W, - height: H, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::_1) - .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) - .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST) - .sharing_mode(vk::SharingMode::EXCLUSIVE) - .initial_layout(vk::ImageLayout::UNDEFINED) - .push_next(&mut external) - .push_next(&mut list) - .build(); - let image = unsafe { d.create_image(&info, None) }.expect("export image"); - - let req = unsafe { d.get_image_memory_requirements(image) }; - let index = memory_index( - instance, - physical, - req.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - ); - let mut export_info = vk::ExportMemoryAllocateInfo::builder() - .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder() - .image(image) - .build(); - let alloc = vk::MemoryAllocateInfo::builder() - .allocation_size(req.size) - .memory_type_index(index) - .push_next(&mut dedicated) - .push_next(&mut export_info) - .build(); - let memory = unsafe { d.allocate_memory(&alloc, None) }.expect("export memory"); - unsafe { d.bind_image_memory(image, memory, 0) }.expect("bind export memory"); - - let fd_info = vk::MemoryGetFdInfoKHR::builder() - .memory(memory) - .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd"); - let fd = unsafe { OwnedFd::from_raw_fd(fd) }; - let memory_aspects = [ - vk::ImageAspectFlags::MEMORY_PLANE_0_EXT, - vk::ImageAspectFlags::MEMORY_PLANE_1_EXT, - ]; - let planes = memory_aspects[..memory_planes] - .iter() - .map(|&aspect_mask| { - let sub = vk::ImageSubresource { - aspect_mask, - mip_level: 0, - array_layer: 0, - }; - let layout = unsafe { d.get_image_subresource_layout(image, &sub) }; - DmaBufPlane { - fd: 0, - offset: layout.offset as u32, - pitch: layout.row_pitch as u32, - } - }) - .collect(); - - let bytes = host.len() as u64; - let buf_info = vk::BufferCreateInfo::builder() - .size(bytes) - .usage(vk::BufferUsageFlags::TRANSFER_SRC) - .sharing_mode(vk::SharingMode::EXCLUSIVE); - let staging = unsafe { d.create_buffer(&buf_info, None) }.expect("staging buffer"); - let breq = unsafe { d.get_buffer_memory_requirements(staging) }; - let bindex = memory_index( - instance, - physical, - breq.memory_type_bits, - vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, - ); - let balloc = vk::MemoryAllocateInfo::builder() - .allocation_size(breq.size) - .memory_type_index(bindex) - .build(); - let bmem = unsafe { d.allocate_memory(&balloc, None) }.expect("staging memory"); - unsafe { - d.bind_buffer_memory(staging, bmem, 0) - .expect("bind staging"); - let ptr = d - .map_memory(bmem, 0, bytes, vk::MemoryMapFlags::empty()) - .expect("map staging") as *mut u8; - std::ptr::copy_nonoverlapping(host.as_ptr(), ptr, host.len()); - d.unmap_memory(bmem); - } - - let pool_info = vk::CommandPoolCreateInfo::builder().queue_family_index(family); - let pool = unsafe { d.create_command_pool(&pool_info, None) }.expect("pool"); - let alloc = vk::CommandBufferAllocateInfo::builder() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0]; - let to_dst: Vec = regions - .iter() - .map(|&(aspect, ..)| { - vk::ImageMemoryBarrier::builder() - .old_layout(vk::ImageLayout::UNDEFINED) - .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL) - .src_access_mask(vk::AccessFlags::empty()) - .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .image(image) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: aspect, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }) - .build() - }) - .collect(); - let copies: Vec = regions - .iter() - .map(|&(aspect, offset, width, height)| { - vk::BufferImageCopy::builder() - .buffer_offset(offset) - .image_subresource(vk::ImageSubresourceLayers { - aspect_mask: aspect, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }) - .image_extent(vk::Extent3D { - width, - height, - depth: 1, - }) - .build() - }) - .collect(); - let begin = - vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - unsafe { - d.begin_command_buffer(cb, &begin).expect("begin"); - d.cmd_pipeline_barrier( - cb, - vk::PipelineStageFlags::TOP_OF_PIPE, - vk::PipelineStageFlags::TRANSFER, - vk::DependencyFlags::empty(), - &[] as &[vk::MemoryBarrier], - &[] as &[vk::BufferMemoryBarrier], - &to_dst, - ); - d.cmd_copy_buffer_to_image( - cb, - staging, - image, - vk::ImageLayout::TRANSFER_DST_OPTIMAL, - &copies, - ); - d.end_command_buffer(cb).expect("end"); - let cbs = [cb]; - let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build(); - d.queue_submit(queue, &[submit], vk::Fence::null()) - .expect("submit"); - d.queue_wait_idle(queue).expect("wait"); - d.destroy_command_pool(pool, None); - d.destroy_buffer(staging, None); - d.free_memory(bmem, None); - } - - Export { - image, - memory, - fd, - modifier, - planes, - } -} - -fn export_planar( - instance: &Instance, - physical: vk::PhysicalDevice, - d: &Device, - queue: vk::Queue, - family: u32, - format: vk::Format, - modifier: u64, - pattern: &Pattern, -) -> Export { - let bps = if pattern.bits == 8 { 1 } else { 2 }; - let luma = (W * H * bps) as u64; - let regions = [ - (vk::ImageAspectFlags::PLANE_0, 0, W, H), - (vk::ImageAspectFlags::PLANE_1, luma, W / 2, H / 2), - ]; - export( - instance, - physical, - d, - queue, - family, - format, - modifier, - &pattern.device(), - ®ions, - 2, - ) -} - -fn run(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) { - let modifiers = vk_video_ffi::rgb_import_modifiers(gpu, true); - println!( - "{name} bgrx import modifiers {modifiers:x?}, linear {} tiled {}", - modifiers.contains(&linear.modifier), - modifiers.contains(&tiled.modifier) - ); - let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))]; - for (export, size) in cases { - let mut a = S::open(gpu, size, 8).expect("encoder"); - let mut b = S::open(gpu, size, 8).expect("encoder"); - let owned = vk_video_ffi::dup_raw_fd(export.fd.as_raw_fd()).expect("dup"); - let fds = [owned.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &export.planes, - width: W, - height: H, - modifier: export.modifier, - format: DmaBufFormat::Bgrx, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.rgb(host, i).expect("encode_rgb")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!( - "{name} {:#x} {}x{} {verdict}", - export.modifier, size.0, size.1 - ); - } -} - -fn planar_format(pattern: &Pattern) -> DmaBufFormat { - if pattern.bits == 8 { - DmaBufFormat::Nv12 - } else { - DmaBufFormat::P010 - } -} - -fn split_planes(a: &Export, b: &Export) -> [DmaBufPlane; 2] { - [ - DmaBufPlane { fd: 0, ..a.planes[0] }, - DmaBufPlane { fd: 1, ..b.planes[1] }, - ] -} - -fn run_split(gpu: &Gpu, name: &str, pattern: &Pattern, pairs: &[(Export, Export)]) { - let format = planar_format(pattern); - for (a_export, b_export) in pairs { - let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let fds = [a_export.fd.as_fd(), b_export.fd.as_fd()]; - let planes = split_planes(a_export, b_export); - let src = DmaBuf { - fds: &fds, - planes: &planes, - width: W, - height: H, - modifier: a_export.modifier, - format, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.planar(pattern, i).expect("encode")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!("{name} split {:#x} {W}x{H} {verdict}", a_export.modifier); - } -} - -fn run_planar(gpu: &Gpu, name: &str, pattern: &Pattern, exports: &[&Export]) { - let format = planar_format(pattern); - for export in exports { - let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder"); - let fds = [export.fd.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &export.planes, - width: W, - height: H, - modifier: export.modifier, - format, - }; - let mut left = Vec::new(); - let mut right = Vec::new(); - for i in 0..FRAMES { - left.extend(a.planar(pattern, i).expect("encode")); - right.extend(b.dma(&src, i).expect("encode_dmabuf")); - } - let verdict = if left == right { - "identical" - } else { - "DIFFERENT" - }; - println!("{name} {:#x} {W}x{H} {verdict}", export.modifier); - } -} - -fn main() { - let gpu = Gpu::open().expect("open GPU"); - let (instance, physical, d) = gpu.vulkan(); - let family = unsafe { instance.get_physical_device_queue_family_properties(physical) } - .iter() - .position(|f| f.queue_flags.contains(vk::QueueFlags::GRAPHICS)) - .expect("graphics family") as u32; - let queue = unsafe { d.get_device_queue(family, 0) }; - let host = gradient(); - let rgb_regions = [(vk::ImageAspectFlags::COLOR, 0, W, H)]; - let linear = export( - instance, - physical, - d, - queue, - family, - FORMAT, - 0, - &host, - &rgb_regions, - 1, - ); - let modifier = - pick_modifier(instance, physical, FORMAT, 1).expect("tiled single-plane modifier"); - let tiled = export( - instance, - physical, - d, - queue, - family, - FORMAT, - modifier, - &host, - &rgb_regions, - 1, - ); - run::(&gpu, "h264", &host, &linear, &tiled); - run::(&gpu, "h265", &host, &linear, &tiled); - run::(&gpu, "av1", &host, &linear, &tiled); - - let nv12 = Pattern::new(8); - let p010 = Pattern::new(10); - let mut exports = vec![linear, tiled]; - let nv12_linear = export_planar(instance, physical, d, queue, family, NV12, 0, &nv12); - let nv12_tiled = pick_modifier(instance, physical, NV12, 2) - .map(|m| export_planar(instance, physical, d, queue, family, NV12, m, &nv12)); - let p010_linear = export_planar(instance, physical, d, queue, family, P010, 0, &p010); - let p010_tiled = pick_modifier(instance, physical, P010, 2) - .map(|m| export_planar(instance, physical, d, queue, family, P010, m, &p010)); - let nv12_set: Vec<&Export> = [Some(&nv12_linear), nv12_tiled.as_ref()] - .into_iter() - .flatten() - .collect(); - let p010_set: Vec<&Export> = [Some(&p010_linear), p010_tiled.as_ref()] - .into_iter() - .flatten() - .collect(); - run_planar::(&gpu, "h264 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "h265 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "h265 p010", &p010, &p010_set); - run_planar::(&gpu, "av1 nv12", &nv12, &nv12_set); - run_planar::(&gpu, "av1 p010", &p010, &p010_set); - - let pair = |format, pattern: &Pattern, modifier| { - ( - export_planar(instance, physical, d, queue, family, format, modifier, pattern), - export_planar(instance, physical, d, queue, family, format, modifier, pattern), - ) - }; - let nv12_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, NV12, 2)] - .into_iter() - .flatten() - .map(|m| pair(NV12, &nv12, m)) - .collect(); - let p010_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, P010, 2)] - .into_iter() - .flatten() - .map(|m| pair(P010, &p010, m)) - .collect(); - run_split::(&gpu, "h264 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "h265 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "h265 p010", &p010, &p010_pairs); - run_split::(&gpu, "av1 nv12", &nv12, &nv12_pairs); - run_split::(&gpu, "av1 p010", &p010, &p010_pairs); - - let mut split_cache = ::open(&gpu, (W, H), 8).expect("encoder"); - let (sa, sb) = &nv12_pairs[0]; - let fds = [sa.fd.as_fd(), sb.fd.as_fd()]; - let planes = split_planes(sa, sb); - let src = DmaBuf { - fds: &fds, - planes: &planes, - width: W, - height: H, - modifier: sa.modifier, - format: DmaBufFormat::Nv12, - }; - for pass in 1..=2 { - for i in 0..FRAMES { - split_cache.dma(&src, i).expect("encode_dmabuf"); - } - println!( - "cache h265 nv12 split pass {pass} {FRAMES} frames same fds imports {}", - split_cache.dmabuf_imports() - ); - } - - let mut cache = ::open(&gpu, (W, H), 8).expect("encoder"); - let fds = [nv12_linear.fd.as_fd()]; - let src = DmaBuf { - fds: &fds, - planes: &nv12_linear.planes, - width: W, - height: H, - modifier: nv12_linear.modifier, - format: DmaBufFormat::Nv12, - }; - for i in 0..FRAMES { - cache.dma(&src, i).expect("encode_dmabuf"); - } - println!( - "cache h265 nv12 {FRAMES} frames same fd imports {}", - cache.dmabuf_imports() - ); - - exports.extend(nv12_tiled); - exports.push(nv12_linear); - exports.extend(p010_tiled); - exports.push(p010_linear); - for e in &exports { - e.destroy(d); - } - for (a, b) in nv12_pairs.iter().chain(&p010_pairs) { - a.destroy(d); - b.destroy(d); - } -} diff --git a/shims/vk-video-ffi/examples/h264_decode_smoke.rs b/shims/vk-video-ffi/examples/h264_decode_smoke.rs deleted file mode 100644 index 939b1805..00000000 --- a/shims/vk-video-ffi/examples/h264_decode_smoke.rs +++ /dev/null @@ -1,182 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; -use ec_h264_syntax::{ - AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp, -}; -use vk_video_ffi::{ - Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264Sps, ScalingLists, -}; - -fn zigzag(raster: &[u8], scan: &[u8]) -> Vec { - scan.iter().map(|&r| raster[r as usize]).collect() -} - -fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists { - let mut out = ScalingLists { - l4x4: [[0; 16]; 6], - l8x8: [[0; 64]; 6], - }; - for i in 0..6 { - out.l4x4[i].copy_from_slice(&zigzag(&l.list_4x4[i], &ZIGZAG_4X4)); - out.l8x8[i].copy_from_slice(&zigzag(&l.list_8x8[i], &ZIGZAG_8X8)); - } - out -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("idr.h264"); - let reference = dir.join("ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args(["-frames:v", "1", "-c:v", "libx264", "-profile:v", "main"]) - .args(["-bsf:v", "h264_mp4toannexb", "-f", "h264"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let data = fs::read(&stream).expect("read stream"); - let mut sps_list: Vec = Vec::new(); - let mut pps_list: Vec = Vec::new(); - let mut slices: Vec<&[u8]> = Vec::new(); - let mut slice_header = None; - let mut rbsp = Vec::new(); - for nal in AnnexBIter::new(&data) { - let header = NalHeader::parse(nal[0]).expect("NAL header"); - unescape_rbsp(&nal[1..], &mut rbsp); - match header.unit_type { - NalUnitType::Sps => sps_list.push(Sps::parse(&rbsp).expect("SPS")), - NalUnitType::Pps => { - let pps = Pps::parse(&rbsp, |id| sps_list.iter().find(|s| s.id == id)) - .expect("PPS"); - pps_list.push(pps); - } - NalUnitType::SliceIdr => { - let sps = &sps_list[0]; - let pps = &pps_list[0]; - let sh = SliceHeader::parse(&rbsp, header, sps, pps).expect("slice header"); - slice_header = Some(sh); - slices.push(nal); - } - _ => {} - } - } - let sps = &sps_list[0]; - let pps = &pps_list[0]; - let sh = slice_header.expect("IDR slice"); - - let unit_y = if sps.frame_mbs_only { 2 } else { 4 }; - let (left, right, top, bottom) = sps.crop; - let h264_sps = H264Sps { - id: sps.id, - profile_idc: sps.profile_idc, - level_idc: sps.level_idc, - chroma_format_idc: sps.chroma_format_idc, - bit_depth_luma_minus8: sps.bit_depth_luma - 8, - bit_depth_chroma_minus8: sps.bit_depth_chroma - 8, - log2_max_frame_num_minus4: sps.log2_max_frame_num - 4, - pic_order_cnt_type: sps.pic_order_cnt_type, - log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb - 4, - offset_for_non_ref_pic: sps.offset_for_non_ref_pic, - offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field, - offset_for_ref_frame: sps.offsets_for_ref_frame.clone(), - max_num_ref_frames: sps.max_num_ref_frames as u8, - pic_width_in_mbs_minus1: sps.mb_width - 1, - pic_height_in_map_units_minus1: (if sps.frame_mbs_only { - sps.mb_height - } else { - sps.mb_height / 2 - }) - 1, - frame_mbs_only: sps.frame_mbs_only, - mb_adaptive_frame_field: sps.mb_adaptive_frame_field, - direct_8x8_inference: sps.direct_8x8_inference, - delta_pic_order_always_zero: sps.delta_pic_order_always_zero, - frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y], - qpprime_y_zero_transform_bypass: sps.transform_bypass, - seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists), - }; - let h264_pps = H264Pps { - id: pps.id as u8, - sps_id: pps.sps_id, - entropy_coding_mode: pps.entropy_coding_mode, - bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present, - num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8, - num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8, - weighted_pred: pps.weighted_pred, - weighted_bipred_idc: pps.weighted_bipred_idc, - pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, - pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, - chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, - second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, - deblocking_filter_control_present: pps.deblocking_filter_control_present, - constrained_intra_pred: pps.constrained_intra_pred, - redundant_pic_cnt_present: pps.redundant_pic_cnt_present, - transform_8x8_mode: pps.transform_8x8_mode, - pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists), - }; - - let (w, h) = (sps.width, sps.height); - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = H264DecodeConfig { - max_width: sps.coded_width, - max_height: sps.coded_height, - max_dpb_slots: 2, - profile_idc: sps.profile_idc, - chroma_format_idc: sps.chroma_format_idc, - }; - let mut session = H264DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_parameters(std::slice::from_ref(&h264_sps), std::slice::from_ref(&h264_pps)) - .expect("parameters"); - let poc = if sps.pic_order_cnt_type == 0 { - sh.pic_order_cnt_lsb as i32 - } else { - 0 - }; - let pic = H264DecodePicture { - sps_id: sps.id, - pps_id: pps.id as u8, - idr: true, - reference: true, - frame_num: sh.frame_num as u16, - idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16, - poc: [poc, poc + sh.delta_pic_order_cnt_bottom], - setup_slot: 0, - refs: &[], - slices: &slices, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let mut pgm = format!("P5\n{w} {h}\n255\n").into_bytes(); - pgm.extend_from_slice(&y); - fs::write(dir.join("out.pgm"), &pgm).expect("write pgm"); - - let ref_data = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_y = &ref_data[..luma]; - let ref_u = &ref_data[luma..luma + chroma]; - let ref_v = &ref_data[luma + chroma..luma + 2 * chroma]; - let mad = |a: &[u8], b: &[u8]| { - a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).abs()).sum::() / a.len() as f64 - }; - let ref_uv: Vec = ref_u.iter().zip(ref_v).flat_map(|(&u, &v)| [u, v]).collect(); - println!("mean abs diff Y: {:.6}", mad(&y, ref_y)); - println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv)); -} diff --git a/shims/vk-video-ffi/examples/h265_decode_smoke.rs b/shims/vk-video-ffi/examples/h265_decode_smoke.rs deleted file mode 100644 index 53c7ff78..00000000 --- a/shims/vk-video-ffi/examples/h265_decode_smoke.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use ec_h265_syntax::{ - NalUnitType, Pps, ProfileTierLevel, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, - split_annex_b, -}; -use vk_video_ffi::{ - Gpu, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, - H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265ScalingLists, - H265ShortTermRefPicSet, H265Sps, H265Vps, -}; - -fn ptl(p: &ProfileTierLevel) -> H265ProfileTierLevel { - H265ProfileTierLevel { - tier_flag: p.tier_flag, - progressive_source: p.progressive_source, - interlaced_source: p.interlaced_source, - non_packed_constraint: p.non_packed_constraint, - frame_only_constraint: p.frame_only_constraint, - profile_idc: p.profile_idc, - level_idc: p.level_idc, - } -} - -fn dpbm( - max_latency_increase_plus1: u32, - max_dec_pic_buffering_minus1: u32, - reorder: u32, -) -> H265DecPicBufMgr { - H265DecPicBufMgr { - max_latency_increase_plus1: [max_latency_increase_plus1; 7], - max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], - max_num_reorder_pics: [reorder as u8; 7], - } -} - -fn lists(l: &ScalingList) -> H265ScalingLists { - let c = &l.coefficients; - H265ScalingLists { - list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), - list_8x8: std::array::from_fn(|i| c[1][i]), - list_16x16: std::array::from_fn(|i| c[2][i]), - list_32x32: std::array::from_fn(|i| c[3][3 * i]), - dc_16x16: std::array::from_fn(|i| l.dc[2][i]), - dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), - } -} - -fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { - let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); - H265ShortTermRefPicSet { - delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), - used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), - delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), - used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), - } -} - -fn main() { - let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - let stream = dir.join("idr.hevc"); - let reference = dir.join("ref.yuv"); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=320x240:rate=30") - .args([ - "-frames:v", - "1", - "-c:v", - "libx265", - "-x265-params", - "log-level=error", - ]) - .args(["-f", "hevc"]) - .arg(&stream) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - let status = Command::new("ffmpeg") - .args(["-y", "-loglevel", "error", "-i"]) - .arg(&stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&reference) - .status() - .expect("run ffmpeg"); - assert!(status.success()); - - let data = fs::read(&stream).expect("read stream"); - let nals = split_annex_b(&data); - let mut vps_list: Vec = Vec::new(); - let mut sps_list: Vec = Vec::new(); - let mut pps_list: Vec = Vec::new(); - let mut slice_nals: Vec> = Vec::new(); - for nal in &nals { - match nal.header.nal_type { - NalUnitType::Vps => vps_list.push(Vps::parse(&nal.rbsp()).expect("VPS")), - NalUnitType::Sps => sps_list.push(Sps::parse(&nal.rbsp()).expect("SPS")), - NalUnitType::Pps => pps_list.push(Pps::parse(&nal.rbsp()).expect("PPS")), - t if t.is_vcl() => { - let mut raw = nal.header.to_bytes().to_vec(); - raw.extend_from_slice(nal.payload); - slice_nals.push(raw); - } - _ => {} - } - } - let first = nals - .iter() - .find(|n| n.header.nal_type.is_vcl()) - .expect("slice"); - let vps = &vps_list[0]; - let pps = &pps_list[0]; - let sps = sps_list - .iter() - .find(|s| s.id == pps.sps_id) - .expect("SPS for PPS"); - let (sh, pos) = - SliceHeader::parse(&first.rbsp(), sps, pps, first.header.nal_type).expect("slice header"); - - let h265_vps = H265Vps { - id: vps.id, - max_sub_layers_minus1: 0, - profile_tier_level: ptl(&vps.ptl), - dec_pic_buf_mgr: dpbm( - 0, - vps.max_dec_pic_buffering_minus1, - vps.max_num_reorder_pics, - ), - }; - let c = &sps.conf_win; - let h265_sps = H265Sps { - id: sps.id as u8, - vps_id: sps.vps_id, - max_sub_layers_minus1: 0, - profile_tier_level: ptl(&sps.ptl), - chroma_format_idc: sps.chroma_format_idc as u8, - pic_width_in_luma_samples: sps.pic_width_in_luma_samples, - pic_height_in_luma_samples: sps.pic_height_in_luma_samples, - conformance_window: [c.left, c.right, c.top, c.bottom], - bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, - bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, - log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, - log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, - log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, - log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, - log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, - max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, - max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, - pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { - bit_depth_luma_minus1: a as u8, - bit_depth_chroma_minus1: b as u8, - log2_min_luma_coding_block_size_minus3: c as u8, - log2_diff_max_min_luma_coding_block_size: d as u8, - loop_filter_disabled: e, - }), - dec_pic_buf_mgr: dpbm( - sps.max_latency_increase_plus1, - sps.max_dec_pic_buffering_minus1, - sps.max_num_reorder_pics, - ), - scaling_list_enabled: sps.scaling_list_enabled, - scaling_lists: sps.scaling_list.as_ref().map(lists), - amp_enabled: sps.amp_enabled, - sample_adaptive_offset_enabled: sps.sao_enabled, - long_term_ref_pics_present: sps.long_term_ref_pics_present, - long_term_ref_pics_sps: sps - .long_term_ref_pics_sps - .iter() - .map(|&(poc_lsb, used_by_curr_pic)| H265LongTermRefPicSps { - poc_lsb, - used_by_curr_pic, - }) - .collect(), - temporal_mvp_enabled: sps.temporal_mvp_enabled, - strong_intra_smoothing_enabled: sps.strong_intra_smoothing, - short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), - }; - let h265_pps = H265Pps { - id: pps.id as u8, - sps_id: pps.sps_id as u8, - dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, - output_flag_present: pps.output_flag_present, - num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, - sign_data_hiding_enabled: pps.sign_data_hiding_enabled, - cabac_init_present: pps.cabac_init_present, - num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, - num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, - init_qp_minus26: pps.init_qp_minus26 as i8, - constrained_intra_pred: pps.constrained_intra_pred, - transform_skip_enabled: pps.transform_skip_enabled, - cu_qp_delta_enabled: pps.cu_qp_delta_enabled, - diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, - cb_qp_offset: pps.cb_qp_offset as i8, - cr_qp_offset: pps.cr_qp_offset as i8, - slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, - weighted_pred: pps.weighted_pred, - weighted_bipred: pps.weighted_bipred, - transquant_bypass_enabled: pps.transquant_bypass_enabled, - tiles_enabled: pps.tiles_enabled, - entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, - num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, - num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, - uniform_spacing: pps.uniform_spacing, - column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), - row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), - loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, - loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, - deblocking_filter_control_present: pps.deblocking_filter_control_present, - deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, - deblocking_filter_disabled: pps.deblocking_filter_disabled, - beta_offset_div2: pps.beta_offset_div2 as i8, - tc_offset_div2: pps.tc_offset_div2 as i8, - scaling_lists: pps.scaling_list.as_ref().map(lists), - lists_modification_present: pps.lists_modification_present, - log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, - slice_segment_header_extension_present: pps.slice_segment_header_extension_present, - }; - - let (w, h) = ( - h265_sps.pic_width_in_luma_samples, - h265_sps.pic_height_in_luma_samples, - ); - let gpu = Gpu::open().expect("open GPU"); - println!("device: {}", gpu.device_name()); - let cfg = H265DecodeConfig { - max_width: w, - max_height: h, - max_dpb_slots: 2, - bit_depth: 8, - }; - let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session"); - session - .set_parameters( - std::slice::from_ref(&h265_vps), - std::slice::from_ref(&h265_sps), - std::slice::from_ref(&h265_pps), - ) - .expect("parameters"); - let slices: Vec<&[u8]> = slice_nals.iter().map(|v| v.as_slice()).collect(); - let pic = H265DecodePicture { - vps_id: sps.vps_id, - sps_id: sps.id as u8, - pps_id: pps.id as u8, - irap: first.header.nal_type.is_irap(), - idr: first.header.nal_type.is_idr(), - reference: true, - poc: 0, - setup_slot: 0, - short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, - num_delta_pocs_of_ref_rps_idx: 0, - st_rps_bits: pos.st_rps_bits, - st_curr_before: &[], - st_curr_after: &[], - lt_curr: &[], - refs: &[], - slices: &slices, - }; - session.decode(&pic).expect("decode"); - session.store_output(0, (0, 0, w, h)).expect("store"); - let (y, uv) = session.read_output(0, w, h).expect("read slot"); - - let ref_data = fs::read(&reference).expect("read reference"); - let luma = (w * h) as usize; - let chroma = luma / 4; - let ref_y = &ref_data[..luma]; - let ref_u = &ref_data[luma..luma + chroma]; - let ref_v = &ref_data[luma + chroma..luma + 2 * chroma]; - let mad = |a: &[u8], b: &[u8]| { - a.iter() - .zip(b) - .map(|(&x, &y)| (x as f64 - y as f64).abs()) - .sum::() - / a.len() as f64 - }; - let ref_uv: Vec = ref_u - .iter() - .zip(ref_v) - .flat_map(|(&u, &v)| [u, v]) - .collect(); - println!("mean abs diff Y: {:.6}", mad(&y, ref_y)); - println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv)); -}