forge
Explore
Log in

Don't you dare go Hollow

U17: vk-video-ffi delete every example except caps.rs and the example-only ec-*-syntax dev-dependencies

Browse files at this commit

213534f65a1eacbbddacd32bed1b1727ba942d8dAhmet Kaan GümüşParent: 5c7d6bf
Cargo.lockmodified+0 -3
@@ -2063,9 +2063,6 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
20632063 name = "vk-video-ffi"
20642064 version = "0.1.0"
20652065 dependencies = [
2066- "ec-av1-syntax",
2067- "ec-h264-syntax",
2068- "ec-h265-syntax",
20692066 "vulkanalia",
20702067 "windows",
20712068 ]
shims/vk-video-ffi/Cargo.tomlmodified+0 -5
@@ -17,10 +17,5 @@ windows = { version = "0.62.2", features = [
1717 "Win32_Graphics_Dxgi_Common",
1818 ] }
1919
20-[dev-dependencies]
21-ec-av1-syntax.workspace = true
22-ec-h264-syntax.workspace = true
23-ec-h265-syntax.workspace = true
24-
2520 [target.'cfg(windows)'.dev-dependencies]
2621 windows = { version = "0.62.2", features = ["Win32_Graphics_Direct3D"] }
shims/vk-video-ffi/examples/av1_decode_smoke.rsdeleted+0 -320
@@ -1,320 +0,0 @@
1-use std::fs;
2-use std::path::PathBuf;
3-use std::process::Command;
4-
5-use ec_av1_syntax::{
6- Av1Parser, ChromaSamplePosition, ColorConfig, FrameHeader, FrameType, InterpolationFilter,
7- ObuKind, RestorationType, SequenceHeader, TxMode, WarpModel,
8-};
9-use vk_video_ffi::{
10- Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
11- Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
12- Av1LoopRestoration, Av1Quantization, Av1Restoration, Av1Segmentation, Av1SequenceHeader,
13- Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Gpu,
14-};
15-
16-fn color(c: &ColorConfig) -> Av1ColorConfig {
17- Av1ColorConfig {
18- bit_depth: c.bit_depth,
19- mono_chrome: c.mono_chrome,
20- color_range: c.color_range,
21- separate_uv_delta_q: c.separate_uv_delta_q,
22- subsampling_x: c.subsampling_x,
23- subsampling_y: c.subsampling_y,
24- color_primaries: c.color_primaries,
25- transfer_characteristics: c.transfer_characteristics,
26- matrix_coefficients: c.matrix_coefficients,
27- chroma_sample_position: match c.chroma_sample_position {
28- ChromaSamplePosition::Unknown => 0,
29- ChromaSamplePosition::Vertical => 1,
30- ChromaSamplePosition::Colocated => 2,
31- ChromaSamplePosition::Reserved => 3,
32- },
33- }
34-}
35-
36-fn sequence(s: &SequenceHeader) -> Av1SequenceHeader {
37- Av1SequenceHeader {
38- seq_profile: s.seq_profile,
39- still_picture: s.still_picture,
40- reduced_still_picture_header: s.reduced_still_picture_header,
41- timing_info: s.timing_info.map(|t| Av1TimingInfo {
42- equal_picture_interval: t.equal_picture_interval,
43- num_units_in_display_tick: t.num_units_in_display_tick,
44- time_scale: t.time_scale,
45- num_ticks_per_picture_minus_1: t.num_ticks_per_picture.saturating_sub(1),
46- }),
47- initial_display_delay_present: s.initial_display_delay_present_flag,
48- frame_width_bits_minus_1: (s.frame_width_bits - 1) as u8,
49- frame_height_bits_minus_1: (s.frame_height_bits - 1) as u8,
50- max_frame_width_minus_1: (s.max_frame_width - 1) as u16,
51- max_frame_height_minus_1: (s.max_frame_height - 1) as u16,
52- frame_id_numbers_present: s.frame_id_numbers_present_flag,
53- delta_frame_id_length_minus_2: s.delta_frame_id_length.saturating_sub(2) as u8,
54- additional_frame_id_length_minus_1: s.additional_frame_id_length.saturating_sub(1) as u8,
55- order_hint_bits_minus_1: s.order_hint_bits.saturating_sub(1) as u8,
56- seq_force_integer_mv: s.seq_force_integer_mv,
57- seq_force_screen_content_tools: s.seq_force_screen_content_tools,
58- use_128x128_superblock: s.use_128x128_superblock,
59- enable_filter_intra: s.enable_filter_intra,
60- enable_intra_edge_filter: s.enable_intra_edge_filter,
61- enable_interintra_compound: s.enable_interintra_compound,
62- enable_masked_compound: s.enable_masked_compound,
63- enable_warped_motion: s.enable_warped_motion,
64- enable_dual_filter: s.enable_dual_filter,
65- enable_order_hint: s.enable_order_hint,
66- enable_jnt_comp: s.enable_jnt_comp,
67- enable_ref_frame_mvs: s.enable_ref_frame_mvs,
68- enable_superres: s.enable_superres,
69- enable_cdef: s.enable_cdef,
70- enable_restoration: s.enable_restoration,
71- color_config: color(&s.color_config),
72- film_grain_params_present: s.film_grain_params_present,
73- }
74-}
75-
76-fn restoration(r: RestorationType) -> Av1Restoration {
77- match r {
78- RestorationType::None => Av1Restoration::None,
79- RestorationType::Wiener => Av1Restoration::Wiener,
80- RestorationType::Sgrproj => Av1Restoration::Sgrproj,
81- RestorationType::Switchable => Av1Restoration::Switchable,
82- }
83-}
84-
85-fn frame(h: &FrameHeader, s: &SequenceHeader) -> Av1FrameHeader {
86- let sb_shift = s.sb_shift();
87- let mut global_motion = [Av1GlobalMotion::default(); 8];
88- let mut order_hints = [0u8; 8];
89- for i in 0..7 {
90- global_motion[i + 1] = Av1GlobalMotion {
91- model: match h.global_motion[i].model {
92- WarpModel::Identity => Av1WarpModel::Identity,
93- WarpModel::Translation => Av1WarpModel::Translation,
94- WarpModel::Rotzoom => Av1WarpModel::Rotzoom,
95- WarpModel::Affine => Av1WarpModel::Affine,
96- },
97- params: h.global_motion[i].params,
98- };
99- order_hints[i + 1] = h.order_hints[i] as u8;
100- }
101- Av1FrameHeader {
102- frame_type: match h.frame_type {
103- FrameType::Key => Av1FrameType::Key,
104- FrameType::Inter => Av1FrameType::Inter,
105- FrameType::IntraOnly => Av1FrameType::IntraOnly,
106- FrameType::Switch => Av1FrameType::Switch,
107- },
108- show_frame: h.show_frame,
109- showable_frame: h.showable_frame,
110- error_resilient_mode: h.error_resilient_mode,
111- disable_cdf_update: h.disable_cdf_update,
112- allow_screen_content_tools: h.allow_screen_content_tools,
113- force_integer_mv: h.force_integer_mv,
114- current_frame_id: h.current_frame_id,
115- frame_size_override_flag: h.frame_size_override_flag,
116- order_hint: h.order_hint as u8,
117- primary_ref_frame: h.primary_ref_frame,
118- refresh_frame_flags: h.refresh_frame_flags,
119- frame_width: h.frame_width,
120- frame_height: h.frame_height,
121- upscaled_width: h.upscaled_width,
122- render_width: h.render_width,
123- render_height: h.render_height,
124- use_superres: h.use_superres,
125- superres_denom: h.superres_denom,
126- allow_intrabc: h.allow_intrabc,
127- allow_high_precision_mv: h.allow_high_precision_mv,
128- is_motion_mode_switchable: h.is_motion_mode_switchable,
129- use_ref_frame_mvs: h.use_ref_frame_mvs,
130- frame_refs_short_signaling: h.frame_refs_short_signaling,
131- disable_frame_end_update_cdf: h.disable_frame_end_update_cdf,
132- reference_select: h.reference_select,
133- skip_mode_present: h.skip_mode_present,
134- allow_warped_motion: h.allow_warped_motion,
135- reduced_tx_set: h.reduced_tx_set,
136- interpolation_filter: match h.interpolation_filter {
137- InterpolationFilter::Eighttap => Av1InterpolationFilter::EightTap,
138- InterpolationFilter::EighttapSmooth => Av1InterpolationFilter::EightTapSmooth,
139- InterpolationFilter::EighttapSharp => Av1InterpolationFilter::EightTapSharp,
140- InterpolationFilter::Bilinear => Av1InterpolationFilter::Bilinear,
141- InterpolationFilter::Switchable => Av1InterpolationFilter::Switchable,
142- },
143- tx_mode: match h.tx_mode {
144- TxMode::Only4x4 => Av1TxMode::Only4x4,
145- TxMode::Largest => Av1TxMode::Largest,
146- TxMode::Select => Av1TxMode::Select,
147- },
148- tile_info: Av1TileInfo {
149- uniform_spacing: h.tile_info.uniform_spacing,
150- cols: h.tile_info.cols as u8,
151- rows: h.tile_info.rows as u8,
152- mi_col_starts: h
153- .tile_info
154- .mi_col_starts
155- .iter()
156- .map(|&v| v as u16)
157- .collect(),
158- mi_row_starts: h
159- .tile_info
160- .mi_row_starts
161- .iter()
162- .map(|&v| v as u16)
163- .collect(),
164- width_in_sbs_minus_1: h.tile_info.width_in_sbs_minus_1(sb_shift),
165- height_in_sbs_minus_1: h.tile_info.height_in_sbs_minus_1(sb_shift),
166- context_update_tile_id: h.tile_info.context_update_tile_id as u16,
167- tile_size_bytes_minus_1: h.tile_info.tile_size_bytes.saturating_sub(1) as u8,
168- },
169- quantization: Av1Quantization {
170- base_q_idx: h.quantization.base_q_idx,
171- delta_q_y_dc: h.quantization.delta_q_y_dc,
172- delta_q_u_dc: h.quantization.delta_q_u_dc,
173- delta_q_u_ac: h.quantization.delta_q_u_ac,
174- delta_q_v_dc: h.quantization.delta_q_v_dc,
175- delta_q_v_ac: h.quantization.delta_q_v_ac,
176- using_qmatrix: h.quantization.using_qmatrix,
177- qm_y: h.quantization.qm_y,
178- qm_u: h.quantization.qm_u,
179- qm_v: h.quantization.qm_v,
180- },
181- segmentation: Av1Segmentation {
182- enabled: h.segmentation.enabled,
183- update_map: h.segmentation.update_map,
184- temporal_update: h.segmentation.temporal_update,
185- update_data: h.segmentation.update_data,
186- feature_enabled: h.segmentation.feature_enabled,
187- feature_data: h.segmentation.feature_data,
188- },
189- delta: Av1DeltaParams {
190- q_present: h.delta.q_present,
191- q_res: h.delta.q_res,
192- lf_present: h.delta.lf_present,
193- lf_res: h.delta.lf_res,
194- lf_multi: h.delta.lf_multi,
195- },
196- loop_filter: Av1LoopFilter {
197- level: h.loop_filter.level,
198- sharpness: h.loop_filter.sharpness,
199- delta_enabled: h.loop_filter.delta_enabled,
200- delta_update: h.loop_filter.delta_update,
201- ref_deltas: h.loop_filter.ref_deltas,
202- mode_deltas: h.loop_filter.mode_deltas,
203- },
204- cdef: Av1Cdef {
205- damping_minus_3: h.cdef.damping.saturating_sub(3),
206- bits: h.cdef.bits,
207- y_pri: h.cdef.y_pri_strength,
208- y_sec: h.cdef.y_sec_strength,
209- uv_pri: h.cdef.uv_pri_strength,
210- uv_sec: h.cdef.uv_sec_strength,
211- },
212- loop_restoration: Av1LoopRestoration {
213- frame_restoration_type: h.loop_restoration.frame_restoration_type.map(restoration),
214- loop_restoration_size: h.loop_restoration.loop_restoration_size.map(|v| v as u16),
215- },
216- global_motion,
217- order_hints,
218- skip_mode_frame: h.skip_mode_frame,
219- expected_frame_id: [0; 8],
220- apply_grain: h.film_grain.apply_grain,
221- }
222-}
223-
224-fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
225- a.iter()
226- .zip(b)
227- .map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs())
228- .sum::<f64>()
229- / a.len() as f64
230-}
231-
232-fn main() {
233- let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
234- let stream = dir.join("key.ivf");
235- let reference = dir.join("av1_ref.yuv");
236- let status = Command::new("ffmpeg")
237- .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"])
238- .arg("testsrc2=size=320x240:rate=30")
239- .args(["-frames:v", "1", "-c:v", "libsvtav1", "-f", "ivf"])
240- .arg(&stream)
241- .status()
242- .expect("run ffmpeg");
243- assert!(status.success());
244- let status = Command::new("ffmpeg")
245- .args(["-y", "-loglevel", "error", "-i"])
246- .arg(&stream)
247- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
248- .arg(&reference)
249- .status()
250- .expect("run ffmpeg");
251- assert!(status.success());
252-
253- let ivf = fs::read(&stream).expect("read ivf");
254- let header_len = u16::from_le_bytes([ivf[6], ivf[7]]) as usize;
255- let frame_len =
256- u32::from_le_bytes(ivf[header_len..header_len + 4].try_into().unwrap()) as usize;
257- let data = &ivf[header_len + 12..header_len + 12 + frame_len];
258-
259- let mut parser = Av1Parser::new();
260- let obus = parser
261- .parse_temporal_unit(data)
262- .expect("parse temporal unit");
263- let mut seq = None;
264- let mut frame_obu = None;
265- for obu in obus {
266- match obu.kind {
267- ObuKind::SequenceHeader(s) => seq = Some(*s),
268- ObuKind::Frame(h, tiles) => frame_obu = Some((*h, tiles)),
269- _ => {}
270- }
271- }
272- let seq = seq.expect("sequence header");
273- let (header, tiles) = frame_obu.expect("frame OBU");
274- assert_eq!(header.frame_type, FrameType::Key);
275-
276- let offsets: Vec<u32> = tiles.iter().map(|t| t.offset as u32).collect();
277- let sizes: Vec<u32> = tiles.iter().map(|t| t.size as u32).collect();
278- let plain_seq = sequence(&seq);
279- let plain_frame = frame(&header, &seq);
280- let (w, h) = (header.upscaled_width, header.frame_height);
281-
282- let gpu = Gpu::open().expect("open GPU");
283- println!("device: {}", gpu.device_name());
284- let cfg = Av1DecodeConfig {
285- max_width: w,
286- max_height: h,
287- max_dpb_slots: 9,
288- bit_depth: 8,
289- };
290- let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session");
291- session
292- .set_sequence_header(&plain_seq)
293- .expect("sequence header");
294- let pic = Av1DecodePicture {
295- header: &plain_frame,
296- setup_slot: 0,
297- ref_frame_slot: [-1; 7],
298- refs: &[],
299- tile_data: data,
300- tile_offsets: &offsets,
301- tile_sizes: &sizes,
302- };
303- session.decode(&pic).expect("decode");
304- session.store_output(0, (0, 0, w, h)).expect("store");
305- let (y, uv) = session.read_output(0, w, h).expect("read slot");
306-
307- let reference = fs::read(&reference).expect("read reference");
308- let luma = (w * h) as usize;
309- let chroma = luma / 4;
310- let ref_uv: Vec<u8> = reference[luma..luma + chroma]
311- .iter()
312- .zip(&reference[luma + chroma..luma + 2 * chroma])
313- .flat_map(|(&u, &v)| [u, v])
314- .collect();
315- println!(
316- "mean abs diff Y: {:.6}",
317- mean_abs_diff(&y, &reference[..luma])
318- );
319- println!("mean abs diff UV: {:.6}", mean_abs_diff(&uv, &ref_uv));
320-}
shims/vk-video-ffi/examples/d3d11_pool.rsdeleted+0 -111
@@ -1,111 +0,0 @@
1-#[cfg(windows)]
2-fn main() {
3- use std::os::windows::io::AsRawHandle;
4-
5- use vk_video_ffi::D3d11Pool;
6- use windows::Win32::Foundation::{HANDLE, HMODULE};
7- use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_WARP;
8- use windows::Win32::Graphics::Direct3D11::{
9- D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
10- D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC,
11- D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11Device1,
12- ID3D11Texture2D,
13- };
14- use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};
15- use windows::core::Interface;
16-
17- let (w, h) = (256u32, 144u32);
18- let mut device: Option<ID3D11Device> = None;
19- unsafe {
20- D3D11CreateDevice(
21- None,
22- D3D_DRIVER_TYPE_WARP,
23- HMODULE::default(),
24- D3D11_CREATE_DEVICE_BGRA_SUPPORT,
25- None,
26- D3D11_SDK_VERSION,
27- Some(&mut device),
28- None,
29- None,
30- )
31- .expect("WARP device");
32- }
33- let device = device.expect("device");
34- let context = unsafe { device.GetImmediateContext() }.expect("context");
35- let desc = |usage, cpu: u32, bind: u32| D3D11_TEXTURE2D_DESC {
36- Width: w,
37- Height: h,
38- MipLevels: 1,
39- ArraySize: 1,
40- Format: DXGI_FORMAT_B8G8R8A8_UNORM,
41- SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
42- Usage: usage,
43- BindFlags: bind,
44- CPUAccessFlags: cpu,
45- MiscFlags: 0,
46- };
47- let mut pool = D3d11Pool::new(&device).expect("pool");
48- let mut ids = Vec::new();
49- for round in 0..6u32 {
50- let pixels: Vec<u8> = (0..w * h * 4).map(|i| (i * 7 + round * 13) as u8).collect();
51- let init = D3D11_SUBRESOURCE_DATA {
52- pSysMem: pixels.as_ptr().cast(),
53- SysMemPitch: w * 4,
54- SysMemSlicePitch: 0,
55- };
56- let mut src: Option<ID3D11Texture2D> = None;
57- unsafe {
58- device
59- .CreateTexture2D(&desc(D3D11_USAGE_DEFAULT, 0, 8), Some(&init), Some(&mut src))
60- .expect("source texture");
61- }
62- let src = src.expect("source");
63- let frame = pool.submit(&src).expect("submit");
64- ids.push(frame.id);
65- let dev1: ID3D11Device1 = device.cast().expect("ID3D11Device1");
66- let opened: ID3D11Texture2D =
67- unsafe { dev1.OpenSharedResource1(HANDLE(frame.handle.as_raw_handle())) }
68- .expect("OpenSharedResource1");
69- let mut staging: Option<ID3D11Texture2D> = None;
70- unsafe {
71- device
72- .CreateTexture2D(
73- &desc(D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ.0 as u32, 0),
74- None,
75- Some(&mut staging),
76- )
77- .expect("staging");
78- }
79- let staging = staging.expect("staging");
80- let mut got = vec![0u8; pixels.len()];
81- unsafe {
82- context.CopyResource(&staging, &opened);
83- let mut map = D3D11_MAPPED_SUBRESOURCE::default();
84- context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut map)).expect("map");
85- for y in 0..h as usize {
86- let row = std::slice::from_raw_parts(
87- map.pData.cast::<u8>().add(y * map.RowPitch as usize),
88- w as usize * 4,
89- );
90- got[y * w as usize * 4..][..w as usize * 4].copy_from_slice(row);
91- }
92- context.Unmap(&staging, 0);
93- }
94- println!(
95- "round {round} id {} {}x{} bgr {} {}",
96- frame.id,
97- frame.width,
98- frame.height,
99- frame.bgr,
100- if got == pixels { "identical" } else { "DIFFERS" }
101- );
102- }
103- println!("ids {ids:?}");
104- match vk_video_ffi::Gpu::open() {
105- Ok(gpu) => println!("vulkan: importable bgr {}", vk_video_ffi::d3d11_importable(&gpu, true)),
106- Err(e) => println!("vulkan: {e}"),
107- }
108-}
109-
110-#[cfg(not(windows))]
111-fn main() {}
shims/vk-video-ffi/examples/dmabuf_smoke.rsdeleted+0 -767
@@ -1,767 +0,0 @@
1-use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
2-
3-use vk_video_ffi::{
4- Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane,
5- Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig,
6- H265EncodeSession, H265Picture, H265Ref, H264Profile, RateControl,
7-};
8-use vulkanalia::prelude::v1_3::*;
9-use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
10-
11-const W: u32 = 1280;
12-const H: u32 = 720;
13-const FRAMES: usize = 10;
14-const FPS: (u32, u32) = (30, 1);
15-const RATE: RateControl = RateControl::ConstantQp { qp: 28 };
16-const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM;
17-const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM;
18-const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
19-
20-struct Export {
21- image: vk::Image,
22- memory: vk::DeviceMemory,
23- fd: OwnedFd,
24- modifier: u64,
25- planes: Vec<DmaBufPlane>,
26-}
27-
28-impl Export {
29- fn destroy(&self, d: &Device) {
30- unsafe {
31- d.destroy_image(self.image, None);
32- d.free_memory(self.memory, None);
33- }
34- }
35-}
36-
37-struct Pattern {
38- bits: u8,
39- y: Vec<u16>,
40- uv: Vec<u16>,
41-}
42-
43-impl Pattern {
44- fn new(bits: u8) -> Self {
45- let max = (1u32 << bits) - 1;
46- let y = (0..W * H)
47- .map(|i| {
48- let (x, row) = (i % W, i / W);
49- ((x * max / (W - 1) + row * max / (H - 1)) / 2) as u16
50- })
51- .collect();
52- let uv = (0..W * H / 2)
53- .map(|i| ((i * 7) % (max + 1)) as u16)
54- .collect();
55- Pattern { bits, y, uv }
56- }
57-
58- fn y8(&self) -> Vec<u8> {
59- self.y.iter().map(|&v| v as u8).collect()
60- }
61-
62- fn uv8(&self) -> Vec<u8> {
63- self.uv.iter().map(|&v| v as u8).collect()
64- }
65-
66- fn device(&self) -> Vec<u8> {
67- let samples = self.y.iter().chain(&self.uv);
68- if self.bits == 8 {
69- samples.map(|&v| v as u8).collect()
70- } else {
71- samples.flat_map(|&v| (v << 6).to_le_bytes()).collect()
72- }
73- }
74-}
75-
76-trait Encode: Sized {
77- fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error>;
78- fn rgb(&mut self, host: &[u8], frame: usize) -> Result<Vec<u8>, Error>;
79- fn planar(&mut self, pattern: &Pattern, frame: usize) -> Result<Vec<u8>, Error>;
80- fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result<Vec<u8>, Error>;
81-}
82-
83-impl Encode for H264EncodeSession {
84- fn open(gpu: &Gpu, size: (u32, u32), _bits: u8) -> Result<Self, Error> {
85- let cfg = H264EncodeConfig {
86- width: size.0,
87- height: size.1,
88- fps: FPS,
89- rate: RATE,
90- profile: H264Profile::High,
91- level: 62,
92- colour: None,
93- quality: 0,
94- };
95- H264EncodeSession::new(gpu, &cfg)
96- }
97-
98- fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {
99- let pic = h264_picture(i);
100- self.encode_rgb(host, W, H, W * 4, true, &pic)
101- }
102-
103- fn planar(&mut self, pattern: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
104- self.encode(&pattern.y8(), &pattern.uv8(), &h264_picture(i))
105- }
106-
107- fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
108- self.encode_dmabuf(src, &h264_picture(i))
109- }
110-}
111-
112-fn h264_picture(i: usize) -> H264Picture {
113- H264Picture {
114- idr: i == 0,
115- idr_pic_id: 0,
116- frame_num: i as u32,
117- poc: 2 * i as i32,
118- slot: (i % 2) as u32,
119- reference: (i > 0).then(|| H264Ref {
120- slot: ((i - 1) % 2) as u32,
121- frame_num: (i - 1) as u32,
122- poc: 2 * (i - 1) as i32,
123- }),
124- }
125-}
126-
127-impl Encode for H265EncodeSession {
128- fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error> {
129- let cfg = H265EncodeConfig {
130- width: size.0,
131- height: size.1,
132- fps: FPS,
133- rate: RATE,
134- bit_depth: bits,
135- level: 186,
136- colour: None,
137- quality: 0,
138- };
139- H265EncodeSession::new(gpu, &cfg)
140- }
141-
142- fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {
143- let pic = h265_picture(i);
144- self.encode_rgb(host, W, H, W * 4, true, &pic)
145- }
146-
147- fn planar(&mut self, p: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
148- let pic = h265_picture(i);
149- if p.bits == 8 {
150- self.encode(&p.y8(), &p.uv8(), &pic)
151- } else {
152- self.encode_16(&p.y, &p.uv, &pic)
153- }
154- }
155-
156- fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
157- self.encode_dmabuf(src, &h265_picture(i))
158- }
159-}
160-
161-fn h265_picture(i: usize) -> H265Picture {
162- H265Picture {
163- idr: i == 0,
164- poc: 2 * i as i32,
165- slot: (i % 2) as u32,
166- reference: (i > 0).then(|| H265Ref {
167- slot: ((i - 1) % 2) as u32,
168- poc: 2 * (i - 1) as i32,
169- }),
170- keep: [None; vk_video_ffi::DPB_SLOTS],
171- }
172-}
173-
174-impl Encode for Av1EncodeSession {
175- fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error> {
176- let cfg = Av1EncodeConfig {
177- width: size.0,
178- height: size.1,
179- fps: FPS,
180- rate: RATE,
181- bit_depth: bits,
182- level: 23,
183- colour: None,
184- quality: 0,
185- };
186- Av1EncodeSession::new(gpu, &cfg)
187- }
188-
189- fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {
190- let pic = av1_picture(i);
191- self.encode_rgb(host, W, H, W * 4, true, &pic)
192- }
193-
194- fn planar(&mut self, p: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
195- let pic = av1_picture(i);
196- if p.bits == 8 {
197- self.encode(&p.y8(), &p.uv8(), &pic)
198- } else {
199- self.encode_16(&p.y, &p.uv, &pic)
200- }
201- }
202-
203- fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
204- self.encode_dmabuf(src, &av1_picture(i))
205- }
206-}
207-
208-fn av1_picture(i: usize) -> Av1Picture {
209- Av1Picture {
210- key: i == 0,
211- order_hint: i as u8,
212- slot: (i % 2) as u32,
213- reference: (i > 0).then(|| Av1Ref {
214- slot: ((i - 1) % 2) as u32,
215- order_hint: (i - 1) as u8,
216- }),
217- }
218-}
219-
220-fn gradient() -> Vec<u8> {
221- let mut out = Vec::with_capacity((W * H * 4) as usize);
222- for y in 0..H {
223- for x in 0..W {
224- out.extend([
225- (x * 255 / (W - 1)) as u8,
226- (y * 255 / (H - 1)) as u8,
227- (x ^ y) as u8,
228- 255,
229- ]);
230- }
231- }
232- out
233-}
234-
235-fn memory_index(
236- instance: &Instance,
237- physical: vk::PhysicalDevice,
238- bits: u32,
239- flags: vk::MemoryPropertyFlags,
240-) -> u32 {
241- let props = unsafe { instance.get_physical_device_memory_properties(physical) };
242- (0..props.memory_type_count)
243- .find(|&i| {
244- bits & (1 << i) != 0
245- && props.memory_types[i as usize]
246- .property_flags
247- .contains(flags)
248- })
249- .expect("memory type")
250-}
251-
252-fn pick_modifier(
253- instance: &Instance,
254- physical: vk::PhysicalDevice,
255- format: vk::Format,
256- planes: u32,
257-) -> Option<u64> {
258- let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build();
259- let mut props = vk::FormatProperties2::builder()
260- .push_next(&mut list)
261- .build();
262- unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) };
263- let count = list.drm_format_modifier_count as usize;
264-
265- let mut entries: Vec<vk::DrmFormatModifierPropertiesEXT> = (0..count)
266- .map(|_| vk::DrmFormatModifierPropertiesEXT::builder().build())
267- .collect();
268- let mut list = vk::DrmFormatModifierPropertiesListEXT::builder()
269- .drm_format_modifier_properties(&mut entries)
270- .build();
271- let mut props = vk::FormatProperties2::builder()
272- .push_next(&mut list)
273- .build();
274- unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) };
275-
276- let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST;
277- entries
278- .iter()
279- .find(|e| {
280- e.drm_format_modifier != 0
281- && e.drm_format_modifier_plane_count == planes
282- && e.drm_format_modifier_tiling_features.contains(want)
283- })
284- .map(|e| e.drm_format_modifier)
285-}
286-
287-fn export(
288- instance: &Instance,
289- physical: vk::PhysicalDevice,
290- d: &Device,
291- queue: vk::Queue,
292- family: u32,
293- format: vk::Format,
294- modifier: u64,
295- host: &[u8],
296- regions: &[(vk::ImageAspectFlags, u64, u32, u32)],
297- memory_planes: usize,
298-) -> Export {
299- let modifiers = [modifier];
300- let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()
301- .drm_format_modifiers(&modifiers)
302- .build();
303- let mut external = vk::ExternalMemoryImageCreateInfo::builder()
304- .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
305- .build();
306- let info = vk::ImageCreateInfo::builder()
307- .image_type(vk::ImageType::_2D)
308- .format(format)
309- .extent(vk::Extent3D {
310- width: W,
311- height: H,
312- depth: 1,
313- })
314- .mip_levels(1)
315- .array_layers(1)
316- .samples(vk::SampleCountFlags::_1)
317- .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
318- .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST)
319- .sharing_mode(vk::SharingMode::EXCLUSIVE)
320- .initial_layout(vk::ImageLayout::UNDEFINED)
321- .push_next(&mut external)
322- .push_next(&mut list)
323- .build();
324- let image = unsafe { d.create_image(&info, None) }.expect("export image");
325-
326- let req = unsafe { d.get_image_memory_requirements(image) };
327- let index = memory_index(
328- instance,
329- physical,
330- req.memory_type_bits,
331- vk::MemoryPropertyFlags::DEVICE_LOCAL,
332- );
333- let mut export_info = vk::ExportMemoryAllocateInfo::builder()
334- .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
335- .build();
336- let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
337- .image(image)
338- .build();
339- let alloc = vk::MemoryAllocateInfo::builder()
340- .allocation_size(req.size)
341- .memory_type_index(index)
342- .push_next(&mut dedicated)
343- .push_next(&mut export_info)
344- .build();
345- let memory = unsafe { d.allocate_memory(&alloc, None) }.expect("export memory");
346- unsafe { d.bind_image_memory(image, memory, 0) }.expect("bind export memory");
347-
348- let fd_info = vk::MemoryGetFdInfoKHR::builder()
349- .memory(memory)
350- .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
351- .build();
352- let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd");
353- let fd = unsafe { OwnedFd::from_raw_fd(fd) };
354- let memory_aspects = [
355- vk::ImageAspectFlags::MEMORY_PLANE_0_EXT,
356- vk::ImageAspectFlags::MEMORY_PLANE_1_EXT,
357- ];
358- let planes = memory_aspects[..memory_planes]
359- .iter()
360- .map(|&aspect_mask| {
361- let sub = vk::ImageSubresource {
362- aspect_mask,
363- mip_level: 0,
364- array_layer: 0,
365- };
366- let layout = unsafe { d.get_image_subresource_layout(image, &sub) };
367- DmaBufPlane {
368- fd: 0,
369- offset: layout.offset as u32,
370- pitch: layout.row_pitch as u32,
371- }
372- })
373- .collect();
374-
375- let bytes = host.len() as u64;
376- let buf_info = vk::BufferCreateInfo::builder()
377- .size(bytes)
378- .usage(vk::BufferUsageFlags::TRANSFER_SRC)
379- .sharing_mode(vk::SharingMode::EXCLUSIVE);
380- let staging = unsafe { d.create_buffer(&buf_info, None) }.expect("staging buffer");
381- let breq = unsafe { d.get_buffer_memory_requirements(staging) };
382- let bindex = memory_index(
383- instance,
384- physical,
385- breq.memory_type_bits,
386- vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
387- );
388- let balloc = vk::MemoryAllocateInfo::builder()
389- .allocation_size(breq.size)
390- .memory_type_index(bindex)
391- .build();
392- let bmem = unsafe { d.allocate_memory(&balloc, None) }.expect("staging memory");
393- unsafe {
394- d.bind_buffer_memory(staging, bmem, 0)
395- .expect("bind staging");
396- let ptr = d
397- .map_memory(bmem, 0, bytes, vk::MemoryMapFlags::empty())
398- .expect("map staging") as *mut u8;
399- std::ptr::copy_nonoverlapping(host.as_ptr(), ptr, host.len());
400- d.unmap_memory(bmem);
401- }
402-
403- let pool_info = vk::CommandPoolCreateInfo::builder().queue_family_index(family);
404- let pool = unsafe { d.create_command_pool(&pool_info, None) }.expect("pool");
405- let alloc = vk::CommandBufferAllocateInfo::builder()
406- .command_pool(pool)
407- .level(vk::CommandBufferLevel::PRIMARY)
408- .command_buffer_count(1);
409- let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0];
410- let to_dst: Vec<vk::ImageMemoryBarrier> = regions
411- .iter()
412- .map(|&(aspect, ..)| {
413- vk::ImageMemoryBarrier::builder()
414- .old_layout(vk::ImageLayout::UNDEFINED)
415- .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
416- .src_access_mask(vk::AccessFlags::empty())
417- .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
418- .image(image)
419- .subresource_range(vk::ImageSubresourceRange {
420- aspect_mask: aspect,
421- base_mip_level: 0,
422- level_count: 1,
423- base_array_layer: 0,
424- layer_count: 1,
425- })
426- .build()
427- })
428- .collect();
429- let copies: Vec<vk::BufferImageCopy> = regions
430- .iter()
431- .map(|&(aspect, offset, width, height)| {
432- vk::BufferImageCopy::builder()
433- .buffer_offset(offset)
434- .image_subresource(vk::ImageSubresourceLayers {
435- aspect_mask: aspect,
436- mip_level: 0,
437- base_array_layer: 0,
438- layer_count: 1,
439- })
440- .image_extent(vk::Extent3D {
441- width,
442- height,
443- depth: 1,
444- })
445- .build()
446- })
447- .collect();
448- let begin =
449- vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
450- unsafe {
451- d.begin_command_buffer(cb, &begin).expect("begin");
452- d.cmd_pipeline_barrier(
453- cb,
454- vk::PipelineStageFlags::TOP_OF_PIPE,
455- vk::PipelineStageFlags::TRANSFER,
456- vk::DependencyFlags::empty(),
457- &[] as &[vk::MemoryBarrier],
458- &[] as &[vk::BufferMemoryBarrier],
459- &to_dst,
460- );
461- d.cmd_copy_buffer_to_image(
462- cb,
463- staging,
464- image,
465- vk::ImageLayout::TRANSFER_DST_OPTIMAL,
466- &copies,
467- );
468- d.end_command_buffer(cb).expect("end");
469- let cbs = [cb];
470- let submit = vk::SubmitInfo::builder().command_buffers(&cbs).build();
471- d.queue_submit(queue, &[submit], vk::Fence::null())
472- .expect("submit");
473- d.queue_wait_idle(queue).expect("wait");
474- d.destroy_command_pool(pool, None);
475- d.destroy_buffer(staging, None);
476- d.free_memory(bmem, None);
477- }
478-
479- Export {
480- image,
481- memory,
482- fd,
483- modifier,
484- planes,
485- }
486-}
487-
488-fn export_planar(
489- instance: &Instance,
490- physical: vk::PhysicalDevice,
491- d: &Device,
492- queue: vk::Queue,
493- family: u32,
494- format: vk::Format,
495- modifier: u64,
496- pattern: &Pattern,
497-) -> Export {
498- let bps = if pattern.bits == 8 { 1 } else { 2 };
499- let luma = (W * H * bps) as u64;
500- let regions = [
501- (vk::ImageAspectFlags::PLANE_0, 0, W, H),
502- (vk::ImageAspectFlags::PLANE_1, luma, W / 2, H / 2),
503- ];
504- export(
505- instance,
506- physical,
507- d,
508- queue,
509- family,
510- format,
511- modifier,
512- &pattern.device(),
513- &regions,
514- 2,
515- )
516-}
517-
518-fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) {
519- let modifiers = vk_video_ffi::rgb_import_modifiers(gpu, true);
520- println!(
521- "{name} bgrx import modifiers {modifiers:x?}, linear {} tiled {}",
522- modifiers.contains(&linear.modifier),
523- modifiers.contains(&tiled.modifier)
524- );
525- let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))];
526- for (export, size) in cases {
527- let mut a = S::open(gpu, size, 8).expect("encoder");
528- let mut b = S::open(gpu, size, 8).expect("encoder");
529- let owned = vk_video_ffi::dup_raw_fd(export.fd.as_raw_fd()).expect("dup");
530- let fds = [owned.as_fd()];
531- let src = DmaBuf {
532- fds: &fds,
533- planes: &export.planes,
534- width: W,
535- height: H,
536- modifier: export.modifier,
537- format: DmaBufFormat::Bgrx,
538- };
539- let mut left = Vec::new();
540- let mut right = Vec::new();
541- for i in 0..FRAMES {
542- left.extend(a.rgb(host, i).expect("encode_rgb"));
543- right.extend(b.dma(&src, i).expect("encode_dmabuf"));
544- }
545- let verdict = if left == right {
546- "identical"
547- } else {
548- "DIFFERENT"
549- };
550- println!(
551- "{name} {:#x} {}x{} {verdict}",
552- export.modifier, size.0, size.1
553- );
554- }
555-}
556-
557-fn planar_format(pattern: &Pattern) -> DmaBufFormat {
558- if pattern.bits == 8 {
559- DmaBufFormat::Nv12
560- } else {
561- DmaBufFormat::P010
562- }
563-}
564-
565-fn split_planes(a: &Export, b: &Export) -> [DmaBufPlane; 2] {
566- [
567- DmaBufPlane { fd: 0, ..a.planes[0] },
568- DmaBufPlane { fd: 1, ..b.planes[1] },
569- ]
570-}
571-
572-fn run_split<S: Encode>(gpu: &Gpu, name: &str, pattern: &Pattern, pairs: &[(Export, Export)]) {
573- let format = planar_format(pattern);
574- for (a_export, b_export) in pairs {
575- let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder");
576- let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder");
577- let fds = [a_export.fd.as_fd(), b_export.fd.as_fd()];
578- let planes = split_planes(a_export, b_export);
579- let src = DmaBuf {
580- fds: &fds,
581- planes: &planes,
582- width: W,
583- height: H,
584- modifier: a_export.modifier,
585- format,
586- };
587- let mut left = Vec::new();
588- let mut right = Vec::new();
589- for i in 0..FRAMES {
590- left.extend(a.planar(pattern, i).expect("encode"));
591- right.extend(b.dma(&src, i).expect("encode_dmabuf"));
592- }
593- let verdict = if left == right {
594- "identical"
595- } else {
596- "DIFFERENT"
597- };
598- println!("{name} split {:#x} {W}x{H} {verdict}", a_export.modifier);
599- }
600-}
601-
602-fn run_planar<S: Encode>(gpu: &Gpu, name: &str, pattern: &Pattern, exports: &[&Export]) {
603- let format = planar_format(pattern);
604- for export in exports {
605- let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder");
606- let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder");
607- let fds = [export.fd.as_fd()];
608- let src = DmaBuf {
609- fds: &fds,
610- planes: &export.planes,
611- width: W,
612- height: H,
613- modifier: export.modifier,
614- format,
615- };
616- let mut left = Vec::new();
617- let mut right = Vec::new();
618- for i in 0..FRAMES {
619- left.extend(a.planar(pattern, i).expect("encode"));
620- right.extend(b.dma(&src, i).expect("encode_dmabuf"));
621- }
622- let verdict = if left == right {
623- "identical"
624- } else {
625- "DIFFERENT"
626- };
627- println!("{name} {:#x} {W}x{H} {verdict}", export.modifier);
628- }
629-}
630-
631-fn main() {
632- let gpu = Gpu::open().expect("open GPU");
633- let (instance, physical, d) = gpu.vulkan();
634- let family = unsafe { instance.get_physical_device_queue_family_properties(physical) }
635- .iter()
636- .position(|f| f.queue_flags.contains(vk::QueueFlags::GRAPHICS))
637- .expect("graphics family") as u32;
638- let queue = unsafe { d.get_device_queue(family, 0) };
639- let host = gradient();
640- let rgb_regions = [(vk::ImageAspectFlags::COLOR, 0, W, H)];
641- let linear = export(
642- instance,
643- physical,
644- d,
645- queue,
646- family,
647- FORMAT,
648- 0,
649- &host,
650- &rgb_regions,
651- 1,
652- );
653- let modifier =
654- pick_modifier(instance, physical, FORMAT, 1).expect("tiled single-plane modifier");
655- let tiled = export(
656- instance,
657- physical,
658- d,
659- queue,
660- family,
661- FORMAT,
662- modifier,
663- &host,
664- &rgb_regions,
665- 1,
666- );
667- run::<H264EncodeSession>(&gpu, "h264", &host, &linear, &tiled);
668- run::<H265EncodeSession>(&gpu, "h265", &host, &linear, &tiled);
669- run::<Av1EncodeSession>(&gpu, "av1", &host, &linear, &tiled);
670-
671- let nv12 = Pattern::new(8);
672- let p010 = Pattern::new(10);
673- let mut exports = vec![linear, tiled];
674- let nv12_linear = export_planar(instance, physical, d, queue, family, NV12, 0, &nv12);
675- let nv12_tiled = pick_modifier(instance, physical, NV12, 2)
676- .map(|m| export_planar(instance, physical, d, queue, family, NV12, m, &nv12));
677- let p010_linear = export_planar(instance, physical, d, queue, family, P010, 0, &p010);
678- let p010_tiled = pick_modifier(instance, physical, P010, 2)
679- .map(|m| export_planar(instance, physical, d, queue, family, P010, m, &p010));
680- let nv12_set: Vec<&Export> = [Some(&nv12_linear), nv12_tiled.as_ref()]
681- .into_iter()
682- .flatten()
683- .collect();
684- let p010_set: Vec<&Export> = [Some(&p010_linear), p010_tiled.as_ref()]
685- .into_iter()
686- .flatten()
687- .collect();
688- run_planar::<H264EncodeSession>(&gpu, "h264 nv12", &nv12, &nv12_set);
689- run_planar::<H265EncodeSession>(&gpu, "h265 nv12", &nv12, &nv12_set);
690- run_planar::<H265EncodeSession>(&gpu, "h265 p010", &p010, &p010_set);
691- run_planar::<Av1EncodeSession>(&gpu, "av1 nv12", &nv12, &nv12_set);
692- run_planar::<Av1EncodeSession>(&gpu, "av1 p010", &p010, &p010_set);
693-
694- let pair = |format, pattern: &Pattern, modifier| {
695- (
696- export_planar(instance, physical, d, queue, family, format, modifier, pattern),
697- export_planar(instance, physical, d, queue, family, format, modifier, pattern),
698- )
699- };
700- let nv12_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, NV12, 2)]
701- .into_iter()
702- .flatten()
703- .map(|m| pair(NV12, &nv12, m))
704- .collect();
705- let p010_pairs: Vec<(Export, Export)> = [Some(0), pick_modifier(instance, physical, P010, 2)]
706- .into_iter()
707- .flatten()
708- .map(|m| pair(P010, &p010, m))
709- .collect();
710- run_split::<H264EncodeSession>(&gpu, "h264 nv12", &nv12, &nv12_pairs);
711- run_split::<H265EncodeSession>(&gpu, "h265 nv12", &nv12, &nv12_pairs);
712- run_split::<H265EncodeSession>(&gpu, "h265 p010", &p010, &p010_pairs);
713- run_split::<Av1EncodeSession>(&gpu, "av1 nv12", &nv12, &nv12_pairs);
714- run_split::<Av1EncodeSession>(&gpu, "av1 p010", &p010, &p010_pairs);
715-
716- let mut split_cache = <H265EncodeSession as Encode>::open(&gpu, (W, H), 8).expect("encoder");
717- let (sa, sb) = &nv12_pairs[0];
718- let fds = [sa.fd.as_fd(), sb.fd.as_fd()];
719- let planes = split_planes(sa, sb);
720- let src = DmaBuf {
721- fds: &fds,
722- planes: &planes,
723- width: W,
724- height: H,
725- modifier: sa.modifier,
726- format: DmaBufFormat::Nv12,
727- };
728- for pass in 1..=2 {
729- for i in 0..FRAMES {
730- split_cache.dma(&src, i).expect("encode_dmabuf");
731- }
732- println!(
733- "cache h265 nv12 split pass {pass} {FRAMES} frames same fds imports {}",
734- split_cache.dmabuf_imports()
735- );
736- }
737-
738- let mut cache = <H265EncodeSession as Encode>::open(&gpu, (W, H), 8).expect("encoder");
739- let fds = [nv12_linear.fd.as_fd()];
740- let src = DmaBuf {
741- fds: &fds,
742- planes: &nv12_linear.planes,
743- width: W,
744- height: H,
745- modifier: nv12_linear.modifier,
746- format: DmaBufFormat::Nv12,
747- };
748- for i in 0..FRAMES {
749- cache.dma(&src, i).expect("encode_dmabuf");
750- }
751- println!(
752- "cache h265 nv12 {FRAMES} frames same fd imports {}",
753- cache.dmabuf_imports()
754- );
755-
756- exports.extend(nv12_tiled);
757- exports.push(nv12_linear);
758- exports.extend(p010_tiled);
759- exports.push(p010_linear);
760- for e in &exports {
761- e.destroy(d);
762- }
763- for (a, b) in nv12_pairs.iter().chain(&p010_pairs) {
764- a.destroy(d);
765- b.destroy(d);
766- }
767-}
shims/vk-video-ffi/examples/h264_decode_smoke.rsdeleted+0 -182
@@ -1,182 +0,0 @@
1-use std::fs;
2-use std::path::PathBuf;
3-use std::process::Command;
4-
5-use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};
6-use ec_h264_syntax::{
7- AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp,
8-};
9-use vk_video_ffi::{
10- Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264Sps, ScalingLists,
11-};
12-
13-fn zigzag(raster: &[u8], scan: &[u8]) -> Vec<u8> {
14- scan.iter().map(|&r| raster[r as usize]).collect()
15-}
16-
17-fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists {
18- let mut out = ScalingLists {
19- l4x4: [[0; 16]; 6],
20- l8x8: [[0; 64]; 6],
21- };
22- for i in 0..6 {
23- out.l4x4[i].copy_from_slice(&zigzag(&l.list_4x4[i], &ZIGZAG_4X4));
24- out.l8x8[i].copy_from_slice(&zigzag(&l.list_8x8[i], &ZIGZAG_8X8));
25- }
26- out
27-}
28-
29-fn main() {
30- let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
31- let stream = dir.join("idr.h264");
32- let reference = dir.join("ref.yuv");
33- let status = Command::new("ffmpeg")
34- .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"])
35- .arg("testsrc2=size=320x240:rate=30")
36- .args(["-frames:v", "1", "-c:v", "libx264", "-profile:v", "main"])
37- .args(["-bsf:v", "h264_mp4toannexb", "-f", "h264"])
38- .arg(&stream)
39- .status()
40- .expect("run ffmpeg");
41- assert!(status.success());
42- let status = Command::new("ffmpeg")
43- .args(["-y", "-loglevel", "error", "-i"])
44- .arg(&stream)
45- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
46- .arg(&reference)
47- .status()
48- .expect("run ffmpeg");
49- assert!(status.success());
50-
51- let data = fs::read(&stream).expect("read stream");
52- let mut sps_list: Vec<Sps> = Vec::new();
53- let mut pps_list: Vec<Pps> = Vec::new();
54- let mut slices: Vec<&[u8]> = Vec::new();
55- let mut slice_header = None;
56- let mut rbsp = Vec::new();
57- for nal in AnnexBIter::new(&data) {
58- let header = NalHeader::parse(nal[0]).expect("NAL header");
59- unescape_rbsp(&nal[1..], &mut rbsp);
60- match header.unit_type {
61- NalUnitType::Sps => sps_list.push(Sps::parse(&rbsp).expect("SPS")),
62- NalUnitType::Pps => {
63- let pps = Pps::parse(&rbsp, |id| sps_list.iter().find(|s| s.id == id))
64- .expect("PPS");
65- pps_list.push(pps);
66- }
67- NalUnitType::SliceIdr => {
68- let sps = &sps_list[0];
69- let pps = &pps_list[0];
70- let sh = SliceHeader::parse(&rbsp, header, sps, pps).expect("slice header");
71- slice_header = Some(sh);
72- slices.push(nal);
73- }
74- _ => {}
75- }
76- }
77- let sps = &sps_list[0];
78- let pps = &pps_list[0];
79- let sh = slice_header.expect("IDR slice");
80-
81- let unit_y = if sps.frame_mbs_only { 2 } else { 4 };
82- let (left, right, top, bottom) = sps.crop;
83- let h264_sps = H264Sps {
84- id: sps.id,
85- profile_idc: sps.profile_idc,
86- level_idc: sps.level_idc,
87- chroma_format_idc: sps.chroma_format_idc,
88- bit_depth_luma_minus8: sps.bit_depth_luma - 8,
89- bit_depth_chroma_minus8: sps.bit_depth_chroma - 8,
90- log2_max_frame_num_minus4: sps.log2_max_frame_num - 4,
91- pic_order_cnt_type: sps.pic_order_cnt_type,
92- log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb - 4,
93- offset_for_non_ref_pic: sps.offset_for_non_ref_pic,
94- offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field,
95- offset_for_ref_frame: sps.offsets_for_ref_frame.clone(),
96- max_num_ref_frames: sps.max_num_ref_frames as u8,
97- pic_width_in_mbs_minus1: sps.mb_width - 1,
98- pic_height_in_map_units_minus1: (if sps.frame_mbs_only {
99- sps.mb_height
100- } else {
101- sps.mb_height / 2
102- }) - 1,
103- frame_mbs_only: sps.frame_mbs_only,
104- mb_adaptive_frame_field: sps.mb_adaptive_frame_field,
105- direct_8x8_inference: sps.direct_8x8_inference,
106- delta_pic_order_always_zero: sps.delta_pic_order_always_zero,
107- frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y],
108- qpprime_y_zero_transform_bypass: sps.transform_bypass,
109- seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists),
110- };
111- let h264_pps = H264Pps {
112- id: pps.id as u8,
113- sps_id: pps.sps_id,
114- entropy_coding_mode: pps.entropy_coding_mode,
115- bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present,
116- num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8,
117- num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8,
118- weighted_pred: pps.weighted_pred,
119- weighted_bipred_idc: pps.weighted_bipred_idc,
120- pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8,
121- pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8,
122- chroma_qp_index_offset: pps.chroma_qp_index_offset as i8,
123- second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8,
124- deblocking_filter_control_present: pps.deblocking_filter_control_present,
125- constrained_intra_pred: pps.constrained_intra_pred,
126- redundant_pic_cnt_present: pps.redundant_pic_cnt_present,
127- transform_8x8_mode: pps.transform_8x8_mode,
128- pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists),
129- };
130-
131- let (w, h) = (sps.width, sps.height);
132- let gpu = Gpu::open().expect("open GPU");
133- println!("device: {}", gpu.device_name());
134- let cfg = H264DecodeConfig {
135- max_width: sps.coded_width,
136- max_height: sps.coded_height,
137- max_dpb_slots: 2,
138- profile_idc: sps.profile_idc,
139- chroma_format_idc: sps.chroma_format_idc,
140- };
141- let mut session = H264DecodeSession::new(&gpu, &cfg).expect("decode session");
142- session
143- .set_parameters(std::slice::from_ref(&h264_sps), std::slice::from_ref(&h264_pps))
144- .expect("parameters");
145- let poc = if sps.pic_order_cnt_type == 0 {
146- sh.pic_order_cnt_lsb as i32
147- } else {
148- 0
149- };
150- let pic = H264DecodePicture {
151- sps_id: sps.id,
152- pps_id: pps.id as u8,
153- idr: true,
154- reference: true,
155- frame_num: sh.frame_num as u16,
156- idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16,
157- poc: [poc, poc + sh.delta_pic_order_cnt_bottom],
158- setup_slot: 0,
159- refs: &[],
160- slices: &slices,
161- };
162- session.decode(&pic).expect("decode");
163- session.store_output(0, (0, 0, w, h)).expect("store");
164- let (y, uv) = session.read_output(0, w, h).expect("read slot");
165-
166- let mut pgm = format!("P5\n{w} {h}\n255\n").into_bytes();
167- pgm.extend_from_slice(&y);
168- fs::write(dir.join("out.pgm"), &pgm).expect("write pgm");
169-
170- let ref_data = fs::read(&reference).expect("read reference");
171- let luma = (w * h) as usize;
172- let chroma = luma / 4;
173- let ref_y = &ref_data[..luma];
174- let ref_u = &ref_data[luma..luma + chroma];
175- let ref_v = &ref_data[luma + chroma..luma + 2 * chroma];
176- let mad = |a: &[u8], b: &[u8]| {
177- a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).abs()).sum::<f64>() / a.len() as f64
178- };
179- let ref_uv: Vec<u8> = ref_u.iter().zip(ref_v).flat_map(|(&u, &v)| [u, v]).collect();
180- println!("mean abs diff Y: {:.6}", mad(&y, ref_y));
181- println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv));
182-}
shims/vk-video-ffi/examples/h265_decode_smoke.rsdeleted+0 -284
@@ -1,284 +0,0 @@
1-use std::fs;
2-use std::path::PathBuf;
3-use std::process::Command;
4-
5-use ec_h265_syntax::{
6- NalUnitType, Pps, ProfileTierLevel, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps,
7- split_annex_b,
8-};
9-use vk_video_ffi::{
10- Gpu, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
11- H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265ScalingLists,
12- H265ShortTermRefPicSet, H265Sps, H265Vps,
13-};
14-
15-fn ptl(p: &ProfileTierLevel) -> H265ProfileTierLevel {
16- H265ProfileTierLevel {
17- tier_flag: p.tier_flag,
18- progressive_source: p.progressive_source,
19- interlaced_source: p.interlaced_source,
20- non_packed_constraint: p.non_packed_constraint,
21- frame_only_constraint: p.frame_only_constraint,
22- profile_idc: p.profile_idc,
23- level_idc: p.level_idc,
24- }
25-}
26-
27-fn dpbm(
28- max_latency_increase_plus1: u32,
29- max_dec_pic_buffering_minus1: u32,
30- reorder: u32,
31-) -> H265DecPicBufMgr {
32- H265DecPicBufMgr {
33- max_latency_increase_plus1: [max_latency_increase_plus1; 7],
34- max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7],
35- max_num_reorder_pics: [reorder as u8; 7],
36- }
37-}
38-
39-fn lists(l: &ScalingList) -> H265ScalingLists {
40- let c = &l.coefficients;
41- H265ScalingLists {
42- list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()),
43- list_8x8: std::array::from_fn(|i| c[1][i]),
44- list_16x16: std::array::from_fn(|i| c[2][i]),
45- list_32x32: std::array::from_fn(|i| c[3][3 * i]),
46- dc_16x16: std::array::from_fn(|i| l.dc[2][i]),
47- dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]),
48- }
49-}
50-
51-fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet {
52- let (n0, n1) = (r.num_negative as usize, r.num_positive as usize);
53- H265ShortTermRefPicSet {
54- delta_poc_s0: r.delta_poc_s0[..n0].to_vec(),
55- used_by_curr_pic_s0: r.used_s0[..n0].to_vec(),
56- delta_poc_s1: r.delta_poc_s1[..n1].to_vec(),
57- used_by_curr_pic_s1: r.used_s1[..n1].to_vec(),
58- }
59-}
60-
61-fn main() {
62- let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
63- let stream = dir.join("idr.hevc");
64- let reference = dir.join("ref.yuv");
65- let status = Command::new("ffmpeg")
66- .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"])
67- .arg("testsrc2=size=320x240:rate=30")
68- .args([
69- "-frames:v",
70- "1",
71- "-c:v",
72- "libx265",
73- "-x265-params",
74- "log-level=error",
75- ])
76- .args(["-f", "hevc"])
77- .arg(&stream)
78- .status()
79- .expect("run ffmpeg");
80- assert!(status.success());
81- let status = Command::new("ffmpeg")
82- .args(["-y", "-loglevel", "error", "-i"])
83- .arg(&stream)
84- .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
85- .arg(&reference)
86- .status()
87- .expect("run ffmpeg");
88- assert!(status.success());
89-
90- let data = fs::read(&stream).expect("read stream");
91- let nals = split_annex_b(&data);
92- let mut vps_list: Vec<Vps> = Vec::new();
93- let mut sps_list: Vec<Sps> = Vec::new();
94- let mut pps_list: Vec<Pps> = Vec::new();
95- let mut slice_nals: Vec<Vec<u8>> = Vec::new();
96- for nal in &nals {
97- match nal.header.nal_type {
98- NalUnitType::Vps => vps_list.push(Vps::parse(&nal.rbsp()).expect("VPS")),
99- NalUnitType::Sps => sps_list.push(Sps::parse(&nal.rbsp()).expect("SPS")),
100- NalUnitType::Pps => pps_list.push(Pps::parse(&nal.rbsp()).expect("PPS")),
101- t if t.is_vcl() => {
102- let mut raw = nal.header.to_bytes().to_vec();
103- raw.extend_from_slice(nal.payload);
104- slice_nals.push(raw);
105- }
106- _ => {}
107- }
108- }
109- let first = nals
110- .iter()
111- .find(|n| n.header.nal_type.is_vcl())
112- .expect("slice");
113- let vps = &vps_list[0];
114- let pps = &pps_list[0];
115- let sps = sps_list
116- .iter()
117- .find(|s| s.id == pps.sps_id)
118- .expect("SPS for PPS");
119- let (sh, pos) =
120- SliceHeader::parse(&first.rbsp(), sps, pps, first.header.nal_type).expect("slice header");
121-
122- let h265_vps = H265Vps {
123- id: vps.id,
124- max_sub_layers_minus1: 0,
125- profile_tier_level: ptl(&vps.ptl),
126- dec_pic_buf_mgr: dpbm(
127- 0,
128- vps.max_dec_pic_buffering_minus1,
129- vps.max_num_reorder_pics,
130- ),
131- };
132- let c = &sps.conf_win;
133- let h265_sps = H265Sps {
134- id: sps.id as u8,
135- vps_id: sps.vps_id,
136- max_sub_layers_minus1: 0,
137- profile_tier_level: ptl(&sps.ptl),
138- chroma_format_idc: sps.chroma_format_idc as u8,
139- pic_width_in_luma_samples: sps.pic_width_in_luma_samples,
140- pic_height_in_luma_samples: sps.pic_height_in_luma_samples,
141- conformance_window: [c.left, c.right, c.top, c.bottom],
142- bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8,
143- bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8,
144- log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8,
145- log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8,
146- log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8,
147- log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8,
148- log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8,
149- max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8,
150- max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8,
151- pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm {
152- bit_depth_luma_minus1: a as u8,
153- bit_depth_chroma_minus1: b as u8,
154- log2_min_luma_coding_block_size_minus3: c as u8,
155- log2_diff_max_min_luma_coding_block_size: d as u8,
156- loop_filter_disabled: e,
157- }),
158- dec_pic_buf_mgr: dpbm(
159- sps.max_latency_increase_plus1,
160- sps.max_dec_pic_buffering_minus1,
161- sps.max_num_reorder_pics,
162- ),
163- scaling_list_enabled: sps.scaling_list_enabled,
164- scaling_lists: sps.scaling_list.as_ref().map(lists),
165- amp_enabled: sps.amp_enabled,
166- sample_adaptive_offset_enabled: sps.sao_enabled,
167- long_term_ref_pics_present: sps.long_term_ref_pics_present,
168- long_term_ref_pics_sps: sps
169- .long_term_ref_pics_sps
170- .iter()
171- .map(|&(poc_lsb, used_by_curr_pic)| H265LongTermRefPicSps {
172- poc_lsb,
173- used_by_curr_pic,
174- })
175- .collect(),
176- temporal_mvp_enabled: sps.temporal_mvp_enabled,
177- strong_intra_smoothing_enabled: sps.strong_intra_smoothing,
178- short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(),
179- };
180- let h265_pps = H265Pps {
181- id: pps.id as u8,
182- sps_id: pps.sps_id as u8,
183- dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled,
184- output_flag_present: pps.output_flag_present,
185- num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,
186- sign_data_hiding_enabled: pps.sign_data_hiding_enabled,
187- cabac_init_present: pps.cabac_init_present,
188- num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8,
189- num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8,
190- init_qp_minus26: pps.init_qp_minus26 as i8,
191- constrained_intra_pred: pps.constrained_intra_pred,
192- transform_skip_enabled: pps.transform_skip_enabled,
193- cu_qp_delta_enabled: pps.cu_qp_delta_enabled,
194- diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8,
195- cb_qp_offset: pps.cb_qp_offset as i8,
196- cr_qp_offset: pps.cr_qp_offset as i8,
197- slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present,
198- weighted_pred: pps.weighted_pred,
199- weighted_bipred: pps.weighted_bipred,
200- transquant_bypass_enabled: pps.transquant_bypass_enabled,
201- tiles_enabled: pps.tiles_enabled,
202- entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled,
203- num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8,
204- num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8,
205- uniform_spacing: pps.uniform_spacing,
206- column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(),
207- row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(),
208- loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled,
209- loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
210- deblocking_filter_control_present: pps.deblocking_filter_control_present,
211- deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled,
212- deblocking_filter_disabled: pps.deblocking_filter_disabled,
213- beta_offset_div2: pps.beta_offset_div2 as i8,
214- tc_offset_div2: pps.tc_offset_div2 as i8,
215- scaling_lists: pps.scaling_list.as_ref().map(lists),
216- lists_modification_present: pps.lists_modification_present,
217- log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8,
218- slice_segment_header_extension_present: pps.slice_segment_header_extension_present,
219- };
220-
221- let (w, h) = (
222- h265_sps.pic_width_in_luma_samples,
223- h265_sps.pic_height_in_luma_samples,
224- );
225- let gpu = Gpu::open().expect("open GPU");
226- println!("device: {}", gpu.device_name());
227- let cfg = H265DecodeConfig {
228- max_width: w,
229- max_height: h,
230- max_dpb_slots: 2,
231- bit_depth: 8,
232- };
233- let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session");
234- session
235- .set_parameters(
236- std::slice::from_ref(&h265_vps),
237- std::slice::from_ref(&h265_sps),
238- std::slice::from_ref(&h265_pps),
239- )
240- .expect("parameters");
241- let slices: Vec<&[u8]> = slice_nals.iter().map(|v| v.as_slice()).collect();
242- let pic = H265DecodePicture {
243- vps_id: sps.vps_id,
244- sps_id: sps.id as u8,
245- pps_id: pps.id as u8,
246- irap: first.header.nal_type.is_irap(),
247- idr: first.header.nal_type.is_idr(),
248- reference: true,
249- poc: 0,
250- setup_slot: 0,
251- short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag,
252- num_delta_pocs_of_ref_rps_idx: 0,
253- st_rps_bits: pos.st_rps_bits,
254- st_curr_before: &[],
255- st_curr_after: &[],
256- lt_curr: &[],
257- refs: &[],
258- slices: &slices,
259- };
260- session.decode(&pic).expect("decode");
261- session.store_output(0, (0, 0, w, h)).expect("store");
262- let (y, uv) = session.read_output(0, w, h).expect("read slot");
263-
264- let ref_data = fs::read(&reference).expect("read reference");
265- let luma = (w * h) as usize;
266- let chroma = luma / 4;
267- let ref_y = &ref_data[..luma];
268- let ref_u = &ref_data[luma..luma + chroma];
269- let ref_v = &ref_data[luma + chroma..luma + 2 * chroma];
270- let mad = |a: &[u8], b: &[u8]| {
271- a.iter()
272- .zip(b)
273- .map(|(&x, &y)| (x as f64 - y as f64).abs())
274- .sum::<f64>()
275- / a.len() as f64
276- };
277- let ref_uv: Vec<u8> = ref_u
278- .iter()
279- .zip(ref_v)
280- .flat_map(|(&u, &v)| [u, v])
281- .collect();
282- println!("mean abs diff Y: {:.6}", mad(&y, ref_y));
283- println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv));
284-}