forge
Explore
Log in

Don't you dare go Hollow

encode_rgb scales: RGB source may be larger than the encoder (box/area downscale in the RGB->NV12 compute pass; VA path via ec_dsp::rgb_box_downscale); same-size output unchanged

Browse files at this commit

bb053746edc1988f9a0842fa56e12195c1259d7bAhmet Kaan GümüşParent: 8defefb
crates/ec-dsp/src/rgb.rsmodified+37 -0
@@ -24,6 +24,43 @@ pub fn bgra_to_i420_709(
24 i420_709(bgra, width, height, [2, 1, 0], y, u, v);24 i420_709(bgra, width, height, [2, 1, 0], y, u, v);
25 }25 }
26 26
27+/// Box-filter downscale of packed 4-byte pixels (`src` rows `stride` bytes apart, `sw` x `sh` source) to `dw` x `dh` packed rows; each channel is the rounded mean of its source footprint.
28+pub fn rgb_box_downscale(
29+ src: &[u8],
30+ sw: usize,
31+ sh: usize,
32+ stride: usize,
33+ dst: &mut [u8],
34+ dw: usize,
35+ dh: usize,
36+) {
37+ assert!(sw >= dw && sh >= dh && dw > 0 && dh > 0, "source smaller than output");
38+ assert!(stride >= sw * 4 && src.len() >= stride * sh);
39+ assert_eq!(dst.len(), dw * dh * 4);
40+ for oy in 0..dh {
41+ let (y0, y1) = footprint(oy, sh, dh);
42+ for ox in 0..dw {
43+ let (x0, x1) = footprint(ox, sw, dw);
44+ let mut sum = [0u32; 4];
45+ for row in src[y0 * stride..y1 * stride].chunks_exact(stride) {
46+ for px in row[x0 * 4..x1 * 4].chunks_exact(4) {
47+ for (s, &c) in sum.iter_mut().zip(px) {
48+ *s += u32::from(c);
49+ }
50+ }
51+ }
52+ let n = ((x1 - x0) * (y1 - y0)) as u32;
53+ for (d, s) in dst[(oy * dw + ox) * 4..][..4].iter_mut().zip(sum) {
54+ *d = ((s + n / 2) / n) as u8;
55+ }
56+ }
57+ }
58+}
59+
60+fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) {
61+ (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out))
62+}
63+
27 fn i420_709(64 fn i420_709(
28 rgba: &[u8],65 rgba: &[u8],
29 width: usize,66 width: usize,
crates/ec-hw/examples/hw_rgb.rsmodified+44 -28
@@ -4,24 +4,27 @@ use ec_hw::{
4 };4 };
5 5
6 const FRAMES: u32 = 30;6 const FRAMES: u32 = 30;
7-const WIDTH: u32 = 1280;
8-const HEIGHT: u32 = 720;
9 7
10 fn main() {8 fn main() {
11 for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {9 for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {
12- if let Err(e) = run(codec) {10+ if let Err(e) = run(codec, (1280, 720), (1280, 720)) {
13- println!("{codec:?}: error: {e}");11+ println!("{codec:?} 1280x720: error: {e}");
12+ }
13+ }
14+ for target in [(1280, 720), (640, 360)] {
15+ if let Err(e) = run(EncCodec::H264, (1920, 1080), target) {
16+ println!("H264 1920x1080 -> {}x{}: error: {e}", target.0, target.1);
14 }17 }
15 }18 }
16 }19 }
17 20
18-fn run(codec: EncCodec) -> ec_hw::Result<()> {21+fn run(codec: EncCodec, source: (u32, u32), target: (u32, u32)) -> ec_hw::Result<()> {
19 let config = EncoderConfig {22 let config = EncoderConfig {
20 bitrate: 4_000_000,23 bitrate: 4_000_000,
21 rate_control: RateControlMode::ConstantBitrate,24 rate_control: RateControlMode::ConstantBitrate,
22- ..EncoderConfig::new(codec, WIDTH, HEIGHT)25+ ..EncoderConfig::new(codec, target.0, target.1)
23 };26 };
24- let mut encoder = match HwEncoder::open(config, std::env::args().nth(1).map(|_| ec_hw::Backend::Va)) {27+ let mut encoder = match HwEncoder::open(config, std::env::args().nth(1).map(|_| Backend::Va)) {
25 Ok(encoder) => encoder,28 Ok(encoder) => encoder,
26 Err(e) => {29 Err(e) => {
27 println!("{codec:?}: no encoder: {e}");30 println!("{codec:?}: no encoder: {e}");
@@ -29,14 +32,14 @@ fn run(codec: EncCodec) -> ec_hw::Result<()> {
29 }32 }
30 };33 };
31 let backend = encoder.backend();34 let backend = encoder.backend();
32- let sources: Vec<Vec<u8>> = (0..FRAMES).map(bgra_gradient).collect();35+ let mut coded = Vec::with_capacity(FRAMES as usize);
33- let mut coded = Vec::with_capacity(sources.len());36+ for index in 0..FRAMES {
34- for (index, source) in sources.iter().enumerate() {37+ let pixels = bgra_gradient(index, source);
35 let frame = RgbFrame {38 let frame = RgbFrame {
36- data: source,39+ data: &pixels,
37- width: WIDTH,40+ width: source.0,
38- height: HEIGHT,41+ height: source.1,
39- stride: WIDTH * 4,42+ stride: source.0 * 4,
40 order: RgbOrder::Bgra,43 order: RgbOrder::Bgra,
41 };44 };
42 let meta = FrameMetadata {45 let meta = FrameMetadata {
@@ -46,11 +49,11 @@ fn run(codec: EncCodec) -> ec_hw::Result<()> {
46 coded.push(encoder.encode_rgb(&frame, meta)?);49 coded.push(encoder.encode_rgb(&frame, meta)?);
47 }50 }
48 let bytes: usize = coded.iter().map(|c| c.data.len()).sum();51 let bytes: usize = coded.iter().map(|c| c.data.len()).sum();
49- println!("{codec:?} {backend:?} {FRAMES} frames {bytes} bytes");52+ println!(
53+ "{codec:?} {backend:?} {}x{} -> {}x{} {FRAMES} frames {bytes} bytes",
54+ source.0, source.1, target.0, target.1
55+ );
50 56
51- if backend != Backend::Vk {
52- return Ok(());
53- }
54 let mut decoder = match HwDecoder::open(decode_codec(codec)) {57 let mut decoder = match HwDecoder::open(decode_codec(codec)) {
55 Ok(decoder) => decoder,58 Ok(decoder) => decoder,
56 Err(e) => {59 Err(e) => {
@@ -72,7 +75,9 @@ fn run(codec: EncCodec) -> ec_hw::Result<()> {
72 75
73 let total: f64 = decoded76 let total: f64 = decoded
74 .iter()77 .iter()
75- .map(|(ts, frame)| mean_abs_luma(&frame.y, &luma_reference(&sources[*ts as usize])))78+ .map(|(ts, frame)| {
79+ mean_abs_luma(&frame.y, &luma_reference(*ts as u32, source, target))
80+ })
76 .sum();81 .sum();
77 let mean = if decoded.is_empty() {82 let mean = if decoded.is_empty() {
78 0.083 0.0
@@ -94,11 +99,11 @@ fn decode_codec(codec: EncCodec) -> Codec {
94 }99 }
95 }100 }
96 101
97-fn bgra_gradient(index: u32) -> Vec<u8> {102+fn bgra_gradient(index: u32, (w, h): (u32, u32)) -> Vec<u8> {
98 let shift = index as usize * 4;103 let shift = index as usize * 4;
99- let mut out = Vec::with_capacity(WIDTH as usize * HEIGHT as usize * 4);104+ let mut out = Vec::with_capacity(w as usize * h as usize * 4);
100- for y in 0..HEIGHT as usize {105+ for y in 0..h as usize {
101- for x in 0..WIDTH as usize {106+ for x in 0..w as usize {
102 let r = (x + shift) & 0xff;107 let r = (x + shift) & 0xff;
103 let g = (y + 2 * shift) & 0xff;108 let g = (y + 2 * shift) & 0xff;
104 let b = ((x + y) / 2 + 3 * shift) & 0xff;109 let b = ((x + y) / 2 + 3 * shift) & 0xff;
@@ -108,17 +113,28 @@ fn bgra_gradient(index: u32) -> Vec<u8> {
108 out113 out
109 }114 }
110 115
111-fn luma_reference(bgra: &[u8]) -> Vec<u8> {116+fn luma_reference(index: u32, source: (u32, u32), target: (u32, u32)) -> Vec<u8> {
112- let (w, h) = (WIDTH as usize, HEIGHT as usize);117+ let (sw, sh) = (source.0 as usize, source.1 as usize);
118+ let (w, h) = (target.0 as usize, target.1 as usize);
119+ let mut scaled = vec![0; w * h * 4];
120+ ec_dsp::rgb::rgb_box_downscale(
121+ &bgra_gradient(index, source),
122+ sw,
123+ sh,
124+ sw * 4,
125+ &mut scaled,
126+ w,
127+ h,
128+ );
113 let chroma = (w / 2) * (h / 2);129 let chroma = (w / 2) * (h / 2);
114 let mut frame = I420 {130 let mut frame = I420 {
115 y: vec![0; w * h],131 y: vec![0; w * h],
116 u: vec![0; chroma],132 u: vec![0; chroma],
117 v: vec![0; chroma],133 v: vec![0; chroma],
118- width: WIDTH,134+ width: target.0,
119- height: HEIGHT,135+ height: target.1,
120 };136 };
121- ec_dsp::rgb::bgra_to_i420_709(bgra, w, h, &mut frame.y, &mut frame.u, &mut frame.v);137+ ec_dsp::rgb::bgra_to_i420_709(&scaled, w, h, &mut frame.y, &mut frame.u, &mut frame.v);
122 frame.y138 frame.y
123 }139 }
124 140
crates/ec-hw/src/hw.rsmodified+33 -19
@@ -158,9 +158,9 @@ pub enum RgbOrder {
158 pub struct RgbFrame<'a> {158 pub struct RgbFrame<'a> {
159 /// Pixels, `stride * height` bytes at least.159 /// Pixels, `stride * height` bytes at least.
160 pub data: &'a [u8],160 pub data: &'a [u8],
161- /// Width in luma samples, even.161+ /// Source width in pixels, even; at least the encoder width.
162 pub width: u32,162 pub width: u32,
163- /// Height in luma samples, even.163+ /// Source height in pixels, even; at least the encoder height.
164 pub height: u32,164 pub height: u32,
165 /// Row stride in bytes, a multiple of 4 and at least `width * 4`.165 /// Row stride in bytes, a multiple of 4 and at least `width * 4`.
166 pub stride: u32,166 pub stride: u32,
@@ -169,34 +169,44 @@ pub struct RgbFrame<'a> {
169 }169 }
170 170
171 #[cfg(target_os = "linux")]171 #[cfg(target_os = "linux")]
172-fn rgb_to_i420(frame: &RgbFrame) -> Result<I420> {172+fn rgb_to_i420(frame: &RgbFrame, (w, h): (usize, usize)) -> Result<I420> {
173- let (w, h, stride) = (173+ let (sw, sh, stride) = (
174 frame.width as usize,174 frame.width as usize,
175 frame.height as usize,175 frame.height as usize,
176 frame.stride as usize,176 frame.stride as usize,
177 );177 );
178- if w % 2 != 0178+ if sw % 2 != 0
179- || h % 2 != 0179+ || sh % 2 != 0
180 || stride % 4 != 0180 || stride % 4 != 0
181- || stride < w * 4181+ || stride < sw * 4
182- || frame.data.len() < stride * h182+ || frame.data.len() < stride * sh
183 {183 {
184 return Err(Error::config("RGB frame size or stride"));184 return Err(Error::config("RGB frame size or stride"));
185 }185 }
186+ if sw < w || sh < h {
187+ return Err(Error::config("RGB source smaller than encoder"));
188+ }
186 let packed: Vec<u8> = frame189 let packed: Vec<u8> = frame
187 .data190 .data
188 .chunks(stride)191 .chunks(stride)
189- .take(h)192+ .take(sh)
190- .flat_map(|row| &row[..w * 4])193+ .flat_map(|row| &row[..sw * 4])
191 .copied()194 .copied()
192 .collect();195 .collect();
196+ let packed = if (sw, sh) == (w, h) {
197+ packed
198+ } else {
199+ let mut scaled = vec![0; w * h * 4];
200+ ec_dsp::rgb::rgb_box_downscale(&packed, sw, sh, sw * 4, &mut scaled, w, h);
201+ scaled
202+ };
193 let chroma = (w / 2) * (h / 2);203 let chroma = (w / 2) * (h / 2);
194 let mut out = I420 {204 let mut out = I420 {
195 y: vec![0; w * h],205 y: vec![0; w * h],
196 u: vec![0; chroma],206 u: vec![0; chroma],
197 v: vec![0; chroma],207 v: vec![0; chroma],
198- width: frame.width,208+ width: w as u32,
199- height: frame.height,209+ height: h as u32,
200 };210 };
201 match frame.order {211 match frame.order {
202 RgbOrder::Rgba => {212 RgbOrder::Rgba => {
@@ -236,11 +246,11 @@ impl VkEncoder {
236 force_keyframe: bool,246 force_keyframe: bool,
237 ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {247 ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {
238 let bgr = frame.order == RgbOrder::Bgra;248 let bgr = frame.order == RgbOrder::Bgra;
239- let (data, stride) = (frame.data, frame.stride);249+ let (data, sw, sh, stride) = (frame.data, frame.width, frame.height, frame.stride);
240 match self {250 match self {
241- VkEncoder::H264(e) => e.encode_rgb(data, stride, bgr, force_keyframe),251+ VkEncoder::H264(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe),
242- VkEncoder::H265(e) => e.encode_rgb(data, stride, bgr, force_keyframe),252+ VkEncoder::H265(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe),
243- VkEncoder::Av1(e) => e.encode_rgb(data, stride, bgr, force_keyframe),253+ VkEncoder::Av1(e) => e.encode_rgb(data, sw, sh, stride, bgr, force_keyframe),
244 }254 }
245 }255 }
246 }256 }
@@ -254,6 +264,7 @@ enum EncInner {
254 /// A hardware encoder on whichever backend opened.264 /// A hardware encoder on whichever backend opened.
255 pub struct HwEncoder {265 pub struct HwEncoder {
256 inner: EncInner,266 inner: EncInner,
267+ size: (usize, usize),
257 }268 }
258 269
259 impl HwEncoder {270 impl HwEncoder {
@@ -266,7 +277,10 @@ impl HwEncoder {
266 let mut reasons = Vec::new();277 let mut reasons = Vec::new();
267 for backend in order {278 for backend in order {
268 match open_backend(backend, config) {279 match open_backend(backend, config) {
269- Ok(inner) => return Ok(HwEncoder { inner }),280+ Ok(inner) => {
281+ let size = (config.width as usize, config.height as usize);
282+ return Ok(HwEncoder { inner, size });
283+ }
270 Err(e) => reasons.push(format!("{backend:?}: {e}")),284 Err(e) => reasons.push(format!("{backend:?}: {e}")),
271 }285 }
272 }286 }
@@ -301,7 +315,7 @@ impl HwEncoder {
301 }315 }
302 }316 }
303 317
304- /// Encode one packed RGB frame; Vulkan converts it to NV12 on the GPU, VA-API on the CPU.318+ /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU.
305 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {319 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
306 match &mut self.inner {320 match &mut self.inner {
307 EncInner::Vk(enc) => {321 EncInner::Vk(enc) => {
@@ -313,7 +327,7 @@ impl HwEncoder {
313 })327 })
314 }328 }
315 #[cfg(target_os = "linux")]329 #[cfg(target_os = "linux")]
316- EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame)?, meta),330+ EncInner::Va(enc) => enc.encode(&rgb_to_i420(frame, self.size)?, meta),
317 }331 }
318 }332 }
319 }333 }
crates/ec-vk/src/av1.rsmodified+4 -2
@@ -82,16 +82,18 @@ impl Av1Encoder {
82 Ok(self.finish(&pic, frame))82 Ok(self.finish(&pic, frame))
83 }83 }
84 84
85- /// Encodes one packed RGB frame (BGRx if `bgr`, else RGBx; row stride in bytes) converted to NV12 on the GPU.85+ /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
86 pub fn encode_rgb(86 pub fn encode_rgb(
87 &mut self,87 &mut self,
88 rgb: &[u8],88 rgb: &[u8],
89+ src_width: u32,
90+ src_height: u32,
89 stride_bytes: u32,91 stride_bytes: u32,
90 bgr: bool,92 bgr: bool,
91 force_keyframe: bool,93 force_keyframe: bool,
92 ) -> Result<CodedFrame, Error> {94 ) -> Result<CodedFrame, Error> {
93 let pic = self.next_picture(force_keyframe);95 let pic = self.next_picture(force_keyframe);
94- let frame = self.session.encode_rgb(rgb, stride_bytes, bgr, &pic)?;96+ let frame = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
95 Ok(self.finish(&pic, frame))97 Ok(self.finish(&pic, frame))
96 }98 }
97 99
crates/ec-vk/src/h265.rsmodified+4 -2
@@ -80,16 +80,18 @@ impl H265Encoder {
80 Ok(self.finish(&pic, slice))80 Ok(self.finish(&pic, slice))
81 }81 }
82 82
83- /// Encodes one packed RGB frame (BGRx if `bgr`, else RGBx; row stride in bytes) converted to NV12 on the GPU.83+ /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
84 pub fn encode_rgb(84 pub fn encode_rgb(
85 &mut self,85 &mut self,
86 rgb: &[u8],86 rgb: &[u8],
87+ src_width: u32,
88+ src_height: u32,
87 stride_bytes: u32,89 stride_bytes: u32,
88 bgr: bool,90 bgr: bool,
89 force_keyframe: bool,91 force_keyframe: bool,
90 ) -> Result<CodedFrame, Error> {92 ) -> Result<CodedFrame, Error> {
91 let pic = self.next_picture(force_keyframe);93 let pic = self.next_picture(force_keyframe);
92- let slice = self.session.encode_rgb(rgb, stride_bytes, bgr, &pic)?;94+ let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
93 Ok(self.finish(&pic, slice))95 Ok(self.finish(&pic, slice))
94 }96 }
95 97
crates/ec-vk/src/lib.rsmodified+4 -2
@@ -103,16 +103,18 @@ impl H264Encoder {
103 Ok(self.finish(&pic, slice))103 Ok(self.finish(&pic, slice))
104 }104 }
105 105
106- /// Encodes one packed RGB frame (BGRx if `bgr`, else RGBx; row stride in bytes) converted to NV12 on the GPU.106+ /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
107 pub fn encode_rgb(107 pub fn encode_rgb(
108 &mut self,108 &mut self,
109 rgb: &[u8],109 rgb: &[u8],
110+ src_width: u32,
111+ src_height: u32,
110 stride_bytes: u32,112 stride_bytes: u32,
111 bgr: bool,113 bgr: bool,
112 force_keyframe: bool,114 force_keyframe: bool,
113 ) -> Result<CodedFrame, Error> {115 ) -> Result<CodedFrame, Error> {
114 let pic = self.next_picture(force_keyframe);116 let pic = self.next_picture(force_keyframe);
115- let slice = self.session.encode_rgb(rgb, stride_bytes, bgr, &pic)?;117+ let slice = self.session.encode_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?;
116 Ok(self.finish(&pic, slice))118 Ok(self.finish(&pic, slice))
117 }119 }
118 120
shims/vk-video-ffi/shaders/rgb_to_nv12.compmodified+19 -6
@@ -15,6 +15,8 @@ layout(push_constant) uniform Push {
15 uint src_h;15 uint src_h;
16 uint stride;16 uint stride;
17 uint bgr;17 uint bgr;
18+ uint out_w;
19+ uint out_h;
18 uint dst_w;20 uint dst_w;
19 uint dst_h;21 uint dst_h;
20 } pc;22 } pc;
@@ -24,12 +26,23 @@ const ivec3 KCB = ivec3(-6596, -22189, 28784);
24 const ivec3 KCR = ivec3(28784, -26145, -2639);26 const ivec3 KCR = ivec3(28784, -26145, -2639);
25 27
26 ivec3 rgb(int x, int y) {28 ivec3 rgb(int x, int y) {
27- x = clamp(x, 0, int(pc.src_w) - 1);29+ x = clamp(x, 0, int(pc.out_w) - 1);
28- y = clamp(y, 0, int(pc.src_h) - 1);30+ y = clamp(y, 0, int(pc.out_h) - 1);
29- uint p = src[uint(y) * pc.stride + uint(x)];31+ uint x0 = uint(x) * pc.src_w / pc.out_w;
30- uint r = pc.bgr != 0u ? (p >> 16) & 255u : p & 255u;32+ uint x1 = ((uint(x) + 1u) * pc.src_w + pc.out_w - 1u) / pc.out_w;
31- uint b = pc.bgr != 0u ? p & 255u : (p >> 16) & 255u;33+ uint y0 = uint(y) * pc.src_h / pc.out_h;
32- return ivec3(int(r), int((p >> 8) & 255u), int(b));34+ uint y1 = ((uint(y) + 1u) * pc.src_h + pc.out_h - 1u) / pc.out_h;
35+ uvec3 sum = uvec3(0u);
36+ for (uint sy = y0; sy < y1; ++sy) {
37+ for (uint sx = x0; sx < x1; ++sx) {
38+ uint p = src[sy * pc.stride + sx];
39+ uint r = pc.bgr != 0u ? (p >> 16) & 255u : p & 255u;
40+ uint b = pc.bgr != 0u ? p & 255u : (p >> 16) & 255u;
41+ sum += uvec3(r, (p >> 8) & 255u, b);
42+ }
43+ }
44+ uint n = (x1 - x0) * (y1 - y0);
45+ return ivec3((sum + uvec3(n / 2u)) / n);
33 }46 }
34 47
35 uint luma(int x, int y) {48 uint luma(int x, int y) {
shims/vk-video-ffi/shaders/rgb_to_nv12.spvmodified+0 -0

Binary file changed

shims/vk-video-ffi/src/av1_encode.rsmodified+17 -4
@@ -274,18 +274,23 @@ impl Av1EncodeSession {
274 self.encode_uploaded(pic)274 self.encode_uploaded(pic)
275 }275 }
276 276
277- /// Encodes one packed RGB picture (row stride in bytes, BGRx or RGBx byte order) with the GPU converter.277+ /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
278 pub fn encode_rgb(278 pub fn encode_rgb(
279 &mut self,279 &mut self,
280 rgb: &[u8],280 rgb: &[u8],
281+ src_width: u32,
282+ src_height: u32,
281 stride_bytes: u32,283 stride_bytes: u32,
282 bgr: bool,284 bgr: bool,
283 pic: &Av1Picture,285 pic: &Av1Picture,
284 ) -> Result<Vec<u8>, Error> {286 ) -> Result<Vec<u8>, Error> {
285 self.check(pic)?;287 self.check(pic)?;
286- check_rgb(self.src_w, self.src_h, rgb, stride_bytes as usize)?;288+ let src = (src_width as usize, src_height as usize);
289+ check_rgb((self.src_w, self.src_h), src, rgb, stride_bytes as usize)?;
287 self.upload(Input::Rgb {290 self.upload(Input::Rgb {
288 data: rgb,291 data: rgb,
292+ width: src.0,
293+ height: src.1,
289 stride: stride_bytes as usize,294 stride: stride_bytes as usize,
290 bgr,295 bgr,
291 })?;296 })?;
@@ -507,11 +512,19 @@ impl Av1EncodeSession {
507 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };512 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };
508 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);513 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);
509 }514 }
510- Input::Rgb { data, stride, .. } => {515+ Input::Rgb {
516+ data,
517+ width,
518+ height,
519+ stride,
520+ ..
521+ } => {
522+ let gpu = self.gpu.clone();
511 let rgb = self523 let rgb = self
512 .rgb524 .rgb
513 .as_mut()525 .as_mut()
514 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;526 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
527+ rgb.reserve(&gpu, width, height)?;
515 rgb.load(data, stride);528 rgb.load(data, stride);
516 }529 }
517 }530 }
@@ -749,7 +762,7 @@ impl Av1EncodeSession {
749 )?;762 )?;
750 self.rgb = Some(RgbConverter::new(763 self.rgb = Some(RgbConverter::new(
751 &gpu,764 &gpu,
752- (self.src_w, self.src_h),765+ (self.src_w as u32, self.src_h as u32),
753 (self.width, self.height),766 (self.width, self.height),
754 self.staging.buffer,767 self.staging.buffer,
755 )?);768 )?);
shims/vk-video-ffi/src/h264_encode.rsmodified+17 -4
@@ -306,18 +306,23 @@ impl H264EncodeSession {
306 self.encode_uploaded(pic)306 self.encode_uploaded(pic)
307 }307 }
308 308
309- /// Encodes one packed RGB picture (row stride in bytes, BGRx or RGBx byte order) with the GPU converter.309+ /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
310 pub fn encode_rgb(310 pub fn encode_rgb(
311 &mut self,311 &mut self,
312 rgb: &[u8],312 rgb: &[u8],
313+ src_width: u32,
314+ src_height: u32,
313 stride_bytes: u32,315 stride_bytes: u32,
314 bgr: bool,316 bgr: bool,
315 pic: &H264Picture,317 pic: &H264Picture,
316 ) -> Result<Vec<u8>, Error> {318 ) -> Result<Vec<u8>, Error> {
317 self.check(pic)?;319 self.check(pic)?;
318- check_rgb(self.src_w, self.src_h, rgb, stride_bytes as usize)?;320+ let src = (src_width as usize, src_height as usize);
321+ check_rgb((self.src_w, self.src_h), src, rgb, stride_bytes as usize)?;
319 self.upload(Input::Rgb {322 self.upload(Input::Rgb {
320 data: rgb,323 data: rgb,
324+ width: src.0,
325+ height: src.1,
321 stride: stride_bytes as usize,326 stride: stride_bytes as usize,
322 bgr,327 bgr,
323 })?;328 })?;
@@ -510,11 +515,19 @@ impl H264EncodeSession {
510 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };515 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };
511 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);516 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);
512 }517 }
513- Input::Rgb { data, stride, .. } => {518+ Input::Rgb {
519+ data,
520+ width,
521+ height,
522+ stride,
523+ ..
524+ } => {
525+ let gpu = self.gpu.clone();
514 let rgb = self526 let rgb = self
515 .rgb527 .rgb
516 .as_mut()528 .as_mut()
517 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;529 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
530+ rgb.reserve(&gpu, width, height)?;
518 rgb.load(data, stride);531 rgb.load(data, stride);
519 }532 }
520 }533 }
@@ -776,7 +789,7 @@ impl H264EncodeSession {
776 )?;789 )?;
777 self.rgb = Some(RgbConverter::new(790 self.rgb = Some(RgbConverter::new(
778 &gpu,791 &gpu,
779- (self.src_w, self.src_h),792+ (self.src_w as u32, self.src_h as u32),
780 (self.width, self.height),793 (self.width, self.height),
781 self.staging.buffer,794 self.staging.buffer,
782 )?);795 )?);
shims/vk-video-ffi/src/h265_encode.rsmodified+17 -4
@@ -285,18 +285,23 @@ impl H265EncodeSession {
285 self.encode_uploaded(pic)285 self.encode_uploaded(pic)
286 }286 }
287 287
288- /// Encodes one packed RGB picture (row stride in bytes, BGRx or RGBx byte order) with the GPU converter.288+ /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU.
289 pub fn encode_rgb(289 pub fn encode_rgb(
290 &mut self,290 &mut self,
291 rgb: &[u8],291 rgb: &[u8],
292+ src_width: u32,
293+ src_height: u32,
292 stride_bytes: u32,294 stride_bytes: u32,
293 bgr: bool,295 bgr: bool,
294 pic: &H265Picture,296 pic: &H265Picture,
295 ) -> Result<Vec<u8>, Error> {297 ) -> Result<Vec<u8>, Error> {
296 self.check(pic)?;298 self.check(pic)?;
297- check_rgb(self.src_w, self.src_h, rgb, stride_bytes as usize)?;299+ let src = (src_width as usize, src_height as usize);
300+ check_rgb((self.src_w, self.src_h), src, rgb, stride_bytes as usize)?;
298 self.upload(Input::Rgb {301 self.upload(Input::Rgb {
299 data: rgb,302 data: rgb,
303+ width: src.0,
304+ height: src.1,
300 stride: stride_bytes as usize,305 stride: stride_bytes as usize,
301 bgr,306 bgr,
302 })?;307 })?;
@@ -499,11 +504,19 @@ impl H265EncodeSession {
499 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };504 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };
500 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);505 fill_nv12(staging, y, uv, self.src_w, self.src_h, aw, ah);
501 }506 }
502- Input::Rgb { data, stride, .. } => {507+ Input::Rgb {
508+ data,
509+ width,
510+ height,
511+ stride,
512+ ..
513+ } => {
514+ let gpu = self.gpu.clone();
503 let rgb = self515 let rgb = self
504 .rgb516 .rgb
505 .as_mut()517 .as_mut()
506 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;518 .ok_or_else(|| Error::Invalid("RGB converter not created".into()))?;
519+ rgb.reserve(&gpu, width, height)?;
507 rgb.load(data, stride);520 rgb.load(data, stride);
508 }521 }
509 }522 }
@@ -778,7 +791,7 @@ impl H265EncodeSession {
778 )?;791 )?;
779 self.rgb = Some(RgbConverter::new(792 self.rgb = Some(RgbConverter::new(
780 &gpu,793 &gpu,
781- (self.src_w, self.src_h),794+ (self.src_w as u32, self.src_h as u32),
782 (self.width, self.height),795 (self.width, self.height),
783 self.staging.buffer,796 self.staging.buffer,
784 )?);797 )?);
shims/vk-video-ffi/src/rgb_convert.rsmodified+94 -52
@@ -13,20 +13,26 @@ pub(crate) enum Input<'a> {
13 },13 },
14 Rgb {14 Rgb {
15 data: &'a [u8],15 data: &'a [u8],
16+ width: usize,
17+ height: usize,
16 stride: usize,18 stride: usize,
17 bgr: bool,19 bgr: bool,
18 },20 },
19 }21 }
20 22
21 pub(crate) fn check_rgb(23 pub(crate) fn check_rgb(
22- src_w: usize,24+ out: (usize, usize),
23- src_h: usize,25+ src: (usize, usize),
24 data: &[u8],26 data: &[u8],
25 stride: usize,27 stride: usize,
26 ) -> Result<(), Error> {28 ) -> Result<(), Error> {
29+ let (src_w, src_h) = src;
27 if !src_w.is_multiple_of(2) || !src_h.is_multiple_of(2) {30 if !src_w.is_multiple_of(2) || !src_h.is_multiple_of(2) {
28 return Err(Error::Invalid("RGB size must be even".into()));31 return Err(Error::Invalid("RGB size must be even".into()));
29 }32 }
33+ if src_w < out.0 || src_h < out.1 {
34+ return Err(Error::Invalid("RGB source smaller than encoder".into()));
35+ }
30 if !stride.is_multiple_of(4) || stride < src_w * 4 || data.len() < stride * src_h {36 if !stride.is_multiple_of(4) || stride < src_w * 4 || data.len() < stride * src_h {
31 return Err(Error::Invalid("RGB buffer size or stride".into()));37 return Err(Error::Invalid("RGB buffer size or stride".into()));
32 }38 }
@@ -34,12 +40,15 @@ pub(crate) fn check_rgb(
34 }40 }
35 41
36 pub(crate) struct RgbConverter {42 pub(crate) struct RgbConverter {
43+ out_w: u32,
44+ out_h: u32,
37 src_w: usize,45 src_w: usize,
38 src_h: usize,46 src_h: usize,
39 dst_w: u32,47 dst_w: u32,
40 dst_h: u32,48 dst_h: u32,
41 staging: vk::Buffer,49 staging: vk::Buffer,
42 input: vk::Buffer,50 input: vk::Buffer,
51+ cap: u64,
43 memory: vk::DeviceMemory,52 memory: vk::DeviceMemory,
44 ptr: *mut u8,53 ptr: *mut u8,
45 set_layout: vk::DescriptorSetLayout,54 set_layout: vk::DescriptorSetLayout,
@@ -49,39 +58,59 @@ pub(crate) struct RgbConverter {
49 pipeline: vk::Pipeline,58 pipeline: vk::Pipeline,
50 }59 }
51 60
61+fn alloc_input(gpu: &Gpu, len: u64) -> Result<(vk::Buffer, vk::DeviceMemory, *mut u8), Error> {
62+ let d = gpu.device();
63+ let info = vk::BufferCreateInfo::builder()
64+ .size(len)
65+ .usage(vk::BufferUsageFlags::STORAGE_BUFFER)
66+ .sharing_mode(vk::SharingMode::EXCLUSIVE);
67+ let input = unsafe { vk(d.create_buffer(&info, None), "vkCreateBuffer")? };
68+ let req = unsafe { d.get_buffer_memory_requirements(input) };
69+ let index = memory_type(
70+ gpu,
71+ req.memory_type_bits,
72+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
73+ )?;
74+ let alloc = vk::MemoryAllocateInfo::builder()
75+ .allocation_size(req.size)
76+ .memory_type_index(index)
77+ .build();
78+ let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
79+ let ptr = unsafe {
80+ vk(d.bind_buffer_memory(input, memory, 0), "vkBindBufferMemory")?;
81+ vk(
82+ d.map_memory(memory, 0, len, vk::MemoryMapFlags::empty()),
83+ "vkMapMemory",
84+ )?
85+ };
86+ Ok((input, memory, ptr as *mut u8))
87+}
88+
89+fn write_input(d: &Device, set: vk::DescriptorSet, input: vk::Buffer, len: u64) {
90+ let input_info = [vk::DescriptorBufferInfo {
91+ buffer: input,
92+ offset: 0,
93+ range: len,
94+ }];
95+ let writes = [vk::WriteDescriptorSet::builder()
96+ .dst_set(set)
97+ .dst_binding(0)
98+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
99+ .buffer_info(&input_info)
100+ .build()];
101+ unsafe { d.update_descriptor_sets(&writes, &[] as &[vk::CopyDescriptorSet]) };
102+}
103+
52 impl RgbConverter {104 impl RgbConverter {
53 pub(crate) fn new(105 pub(crate) fn new(
54 gpu: &Gpu,106 gpu: &Gpu,
55- src: (usize, usize),107+ out: (u32, u32),
56 dst: (u32, u32),108 dst: (u32, u32),
57 staging: vk::Buffer,109 staging: vk::Buffer,
58 ) -> Result<Self, Error> {110 ) -> Result<Self, Error> {
59 let d = gpu.device();111 let d = gpu.device();
60- let (src_w, src_h) = src;112+ let cap = out.0 as u64 * out.1 as u64 * 4;
61- let input_len = (src_w * src_h * 4) as u64;113+ let (input, memory, ptr) = alloc_input(gpu, cap)?;
62- let info = vk::BufferCreateInfo::builder()
63- .size(input_len)
64- .usage(vk::BufferUsageFlags::STORAGE_BUFFER)
65- .sharing_mode(vk::SharingMode::EXCLUSIVE);
66- let input = unsafe { vk(d.create_buffer(&info, None), "vkCreateBuffer")? };
67- let req = unsafe { d.get_buffer_memory_requirements(input) };
68- let index = memory_type(
69- gpu,
70- req.memory_type_bits,
71- vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
72- )?;
73- let alloc = vk::MemoryAllocateInfo::builder()
74- .allocation_size(req.size)
75- .memory_type_index(index)
76- .build();
77- let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
78- let ptr = unsafe {
79- vk(d.bind_buffer_memory(input, memory, 0), "vkBindBufferMemory")?;
80- vk(
81- d.map_memory(memory, 0, input_len, vk::MemoryMapFlags::empty()),
82- "vkMapMemory",
83- )?
84- };
85 114
86 let bindings = [storage(0), storage(1)];115 let bindings = [storage(0), storage(1)];
87 let set_info = vk::DescriptorSetLayoutCreateInfo::builder().bindings(&bindings);116 let set_info = vk::DescriptorSetLayoutCreateInfo::builder().bindings(&bindings);
@@ -94,7 +123,7 @@ impl RgbConverter {
94 let push = vk::PushConstantRange::builder()123 let push = vk::PushConstantRange::builder()
95 .stage_flags(vk::ShaderStageFlags::COMPUTE)124 .stage_flags(vk::ShaderStageFlags::COMPUTE)
96 .offset(0)125 .offset(0)
97- .size(24)126+ .size(32)
98 .build();127 .build();
99 let set_layouts = [set_layout];128 let set_layouts = [set_layout];
100 let pushes = [push];129 let pushes = [push];
@@ -158,41 +187,32 @@ impl RgbConverter {
158 "vkAllocateDescriptorSets",187 "vkAllocateDescriptorSets",
159 )?[0]188 )?[0]
160 };189 };
161- let input_info = [vk::DescriptorBufferInfo {190+ write_input(d, set, input, cap);
162- buffer: input,
163- offset: 0,
164- range: input_len,
165- }];
166 let staging_info = [vk::DescriptorBufferInfo {191 let staging_info = [vk::DescriptorBufferInfo {
167 buffer: staging,192 buffer: staging,
168 offset: 0,193 offset: 0,
169 range: vk::WHOLE_SIZE,194 range: vk::WHOLE_SIZE,
170 }];195 }];
171- let writes = [196+ let staging_write = [vk::WriteDescriptorSet::builder()
172- vk::WriteDescriptorSet::builder()197+ .dst_set(set)
173- .dst_set(set)198+ .dst_binding(1)
174- .dst_binding(0)199+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
175- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)200+ .buffer_info(&staging_info)
176- .buffer_info(&input_info)201+ .build()];
177- .build(),202+ unsafe { d.update_descriptor_sets(&staging_write, &[] as &[vk::CopyDescriptorSet]) };
178- vk::WriteDescriptorSet::builder()
179- .dst_set(set)
180- .dst_binding(1)
181- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
182- .buffer_info(&staging_info)
183- .build(),
184- ];
185- unsafe { d.update_descriptor_sets(&writes, &[] as &[vk::CopyDescriptorSet]) };
186 203
187 Ok(RgbConverter {204 Ok(RgbConverter {
188- src_w,205+ out_w: out.0,
189- src_h,206+ out_h: out.1,
207+ src_w: out.0 as usize,
208+ src_h: out.1 as usize,
190 dst_w: dst.0,209 dst_w: dst.0,
191 dst_h: dst.1,210 dst_h: dst.1,
192 staging,211 staging,
193 input,212 input,
213+ cap,
194 memory,214 memory,
195- ptr: ptr as *mut u8,215+ ptr,
196 set_layout,216 set_layout,
197 pool,217 pool,
198 set,218 set,
@@ -201,6 +221,26 @@ impl RgbConverter {
201 })221 })
202 }222 }
203 223
224+ pub(crate) fn reserve(&mut self, gpu: &Gpu, src_w: usize, src_h: usize) -> Result<(), Error> {
225+ let len = (src_w * src_h * 4) as u64;
226+ if len > self.cap {
227+ let d = gpu.device();
228+ unsafe {
229+ d.destroy_buffer(self.input, None);
230+ d.free_memory(self.memory, None);
231+ }
232+ let (input, memory, ptr) = alloc_input(gpu, len)?;
233+ write_input(d, self.set, input, len);
234+ self.input = input;
235+ self.memory = memory;
236+ self.ptr = ptr;
237+ self.cap = len;
238+ }
239+ self.src_w = src_w;
240+ self.src_h = src_h;
241+ Ok(())
242+ }
243+
204 pub(crate) fn load(&mut self, data: &[u8], stride: usize) {244 pub(crate) fn load(&mut self, data: &[u8], stride: usize) {
205 let row = self.src_w * 4;245 let row = self.src_w * 4;
206 let dst = unsafe { std::slice::from_raw_parts_mut(self.ptr, row * self.src_h) };246 let dst = unsafe { std::slice::from_raw_parts_mut(self.ptr, row * self.src_h) };
@@ -215,6 +255,8 @@ impl RgbConverter {
215 self.src_h as u32,255 self.src_h as u32,
216 self.src_w as u32,256 self.src_w as u32,
217 bgr as u32,257 bgr as u32,
258+ self.out_w,
259+ self.out_h,
218 self.dst_w,260 self.dst_w,
219 self.dst_h,261 self.dst_h,
220 ];262 ];