leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 디코딩된 YUV 프레임을 GPU 텍스처로 올려 셰이더에서 RGB로 바꿔 그린다 (기획서 7.6 "표시"). |
| 2 | //! |
| 3 | //! CPU에서 색 변환하거나 RGBA로 복사하지 않는다. Y와 U/V(또는 NV12의 UV) 평면을 그대로 |
| 4 | //! 텍스처에 쓰고, egui 렌더 패스 안의 paint callback으로 휴대폰 화면 영역에 그린다. |
| 5 | |
| 6 | use std::sync::Arc; |
| 7 | |
| 8 | use egui_wgpu::wgpu; |
| 9 | use egui_wgpu::{CallbackResources, CallbackTrait, ScreenDescriptor}; |
| 10 | |
| 11 | /// 렌더러가 받는 프레임. 디코더 출력에서 만든다. |
| 12 | pub struct YuvFrame { |
| 13 | pub width: u32, |
| 14 | pub height: u32, |
| 15 | /// true면 NV12(Y + 교차 UV), false면 I420(Y, U, V). |
| 16 | pub nv12: bool, |
| 17 | /// (데이터, 한 줄 바이트 수, 너비, 높이). I420은 3개, NV12는 2개. |
| 18 | pub planes: Vec<(Vec<u8>, usize, u32, u32)>, |
| 19 | pub bt709: bool, |
| 20 | pub full_range: bool, |
| 21 | } |
| 22 | |
| 23 | #[repr(C)] |
| 24 | #[derive(Clone, Copy)] |
| 25 | struct Params { |
| 26 | nv12: u32, |
| 27 | full_range: u32, |
| 28 | bt709: u32, |
| 29 | /// 대상 표면이 sRGB 형식이면 셰이더 출력에서 감마를 되돌린다. |
| 30 | srgb_target: u32, |
| 31 | } |
| 32 | |
| 33 | impl Params { |
| 34 | fn bytes(&self) -> [u8; 16] { |
| 35 | let mut out = [0u8; 16]; |
| 36 | for (i, v) in [self.nv12, self.full_range, self.bt709, self.srgb_target] |
| 37 | .into_iter() |
| 38 | .enumerate() |
| 39 | { |
| 40 | out[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes()); |
| 41 | } |
| 42 | out |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | const SHADER: &str = r#" |
| 47 | struct Params { nv12: u32, full_range: u32, bt709: u32, srgb_target: u32 }; |
| 48 | @group(0) @binding(0) var samp: sampler; |
| 49 | @group(0) @binding(1) var tex_y: texture_2d<f32>; |
| 50 | @group(0) @binding(2) var tex_u: texture_2d<f32>; |
| 51 | @group(0) @binding(3) var tex_v: texture_2d<f32>; |
| 52 | @group(0) @binding(4) var<uniform> params: Params; |
| 53 | |
| 54 | struct VsOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> }; |
| 55 | |
| 56 | @vertex fn vs_main(@builtin(vertex_index) i: u32) -> VsOut { |
| 57 | var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); |
| 58 | let xy = p[i]; |
| 59 | var o: VsOut; |
| 60 | o.pos = vec4(xy, 0.0, 1.0); |
| 61 | o.uv = vec2((xy.x + 1.0) * 0.5, 1.0 - (xy.y + 1.0) * 0.5); |
| 62 | return o; |
| 63 | } |
| 64 | |
| 65 | fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> { |
| 66 | let lo = c / 12.92; |
| 67 | let hi = pow((c + 0.055) / 1.055, vec3(2.4)); |
| 68 | return select(hi, lo, c <= vec3(0.04045)); |
| 69 | } |
| 70 | |
| 71 | @fragment fn fs_main(in: VsOut) -> @location(0) vec4<f32> { |
| 72 | let y = textureSample(tex_y, samp, in.uv).r; |
| 73 | var u: f32; |
| 74 | var v: f32; |
| 75 | if (params.nv12 == 1u) { |
| 76 | let uv = textureSample(tex_u, samp, in.uv).rg; |
| 77 | u = uv.x; |
| 78 | v = uv.y; |
| 79 | } else { |
| 80 | u = textureSample(tex_u, samp, in.uv).r; |
| 81 | v = textureSample(tex_v, samp, in.uv).r; |
| 82 | } |
| 83 | var yy = y; |
| 84 | var cb = u - 0.5; |
| 85 | var cr = v - 0.5; |
| 86 | if (params.full_range == 0u) { |
| 87 | yy = (y - 16.0 / 255.0) * (255.0 / 219.0); |
| 88 | cb = (u - 128.0 / 255.0) * (255.0 / 224.0); |
| 89 | cr = (v - 128.0 / 255.0) * (255.0 / 224.0); |
| 90 | } |
| 91 | var rgb: vec3<f32>; |
| 92 | if (params.bt709 == 1u) { |
| 93 | rgb = vec3(yy + 1.5748 * cr, yy - 0.1873 * cb - 0.4681 * cr, yy + 1.8556 * cb); |
| 94 | } else { |
| 95 | rgb = vec3(yy + 1.402 * cr, yy - 0.3441 * cb - 0.7141 * cr, yy + 1.772 * cb); |
| 96 | } |
| 97 | rgb = clamp(rgb, vec3(0.0), vec3(1.0)); |
| 98 | if (params.srgb_target == 1u) { |
| 99 | rgb = srgb_to_linear(rgb); |
| 100 | } |
| 101 | return vec4(rgb, 1.0); |
| 102 | } |
| 103 | "#; |
| 104 | |
| 105 | /// 렌더 파이프라인과 현재 텍스처. egui-wgpu의 `callback_resources`에 한 번 넣어 둔다. |
| 106 | pub struct VideoPipeline { |
| 107 | pipeline: wgpu::RenderPipeline, |
| 108 | layout: wgpu::BindGroupLayout, |
| 109 | sampler: wgpu::Sampler, |
| 110 | params: wgpu::Buffer, |
| 111 | srgb_target: bool, |
| 112 | textures: Option<Textures>, |
| 113 | /// 마지막으로 GPU에 올린 프레임 번호. |
| 114 | uploaded: Option<u64>, |
| 115 | } |
| 116 | |
| 117 | struct Textures { |
| 118 | key: (u32, u32, bool), |
| 119 | planes: Vec<wgpu::Texture>, |
| 120 | bind_group: wgpu::BindGroup, |
| 121 | } |
| 122 | |
| 123 | impl VideoPipeline { |
| 124 | pub fn new(device: &wgpu::Device, target: wgpu::TextureFormat) -> Self { |
| 125 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 126 | label: Some("video-yuv"), |
| 127 | source: wgpu::ShaderSource::Wgsl(SHADER.into()), |
| 128 | }); |
| 129 | let tex_entry = |binding| wgpu::BindGroupLayoutEntry { |
| 130 | binding, |
| 131 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 132 | ty: wgpu::BindingType::Texture { |
| 133 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 134 | view_dimension: wgpu::TextureViewDimension::D2, |
| 135 | multisampled: false, |
| 136 | }, |
| 137 | count: None, |
| 138 | }; |
| 139 | let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 140 | label: Some("video-yuv"), |
| 141 | entries: &[ |
| 142 | wgpu::BindGroupLayoutEntry { |
| 143 | binding: 0, |
| 144 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 145 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 146 | count: None, |
| 147 | }, |
| 148 | tex_entry(1), |
| 149 | tex_entry(2), |
| 150 | tex_entry(3), |
| 151 | wgpu::BindGroupLayoutEntry { |
| 152 | binding: 4, |
| 153 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 154 | ty: wgpu::BindingType::Buffer { |
| 155 | ty: wgpu::BufferBindingType::Uniform, |
| 156 | has_dynamic_offset: false, |
| 157 | min_binding_size: None, |
| 158 | }, |
| 159 | count: None, |
| 160 | }, |
| 161 | ], |
| 162 | }); |
| 163 | let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 164 | label: Some("video-yuv"), |
| 165 | bind_group_layouts: &[Some(&layout)], |
| 166 | immediate_size: 0, |
| 167 | }); |
| 168 | let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 169 | label: Some("video-yuv"), |
| 170 | layout: Some(&pipeline_layout), |
| 171 | vertex: wgpu::VertexState { |
| 172 | module: &shader, |
| 173 | entry_point: Some("vs_main"), |
| 174 | compilation_options: Default::default(), |
| 175 | buffers: &[], |
| 176 | }, |
| 177 | fragment: Some(wgpu::FragmentState { |
| 178 | module: &shader, |
| 179 | entry_point: Some("fs_main"), |
| 180 | compilation_options: Default::default(), |
| 181 | targets: &[Some(wgpu::ColorTargetState { |
| 182 | format: target, |
| 183 | blend: None, |
| 184 | write_mask: wgpu::ColorWrites::ALL, |
| 185 | })], |
| 186 | }), |
| 187 | primitive: wgpu::PrimitiveState::default(), |
| 188 | depth_stencil: None, |
| 189 | multisample: wgpu::MultisampleState::default(), |
| 190 | multiview_mask: None, |
| 191 | cache: None, |
| 192 | }); |
| 193 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 194 | label: Some("video-yuv"), |
| 195 | mag_filter: wgpu::FilterMode::Linear, |
| 196 | min_filter: wgpu::FilterMode::Linear, |
| 197 | ..Default::default() |
| 198 | }); |
| 199 | let params = device.create_buffer(&wgpu::BufferDescriptor { |
| 200 | label: Some("video-yuv-params"), |
| 201 | size: 16, |
| 202 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 203 | mapped_at_creation: false, |
| 204 | }); |
| 205 | Self { |
| 206 | pipeline, |
| 207 | layout, |
| 208 | sampler, |
| 209 | params, |
| 210 | srgb_target: target.is_srgb(), |
| 211 | textures: None, |
| 212 | uploaded: None, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn upload(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: &YuvFrame) { |
| 217 | let key = (frame.width, frame.height, frame.nv12); |
| 218 | if self.textures.as_ref().map(|t| t.key) != Some(key) { |
| 219 | self.textures = Some(self.create_textures(device, frame)); |
| 220 | } |
| 221 | let Some(tex) = &self.textures else { return }; |
| 222 | for (texture, (data, stride, w, h)) in tex.planes.iter().zip(&frame.planes) { |
| 223 | queue.write_texture( |
| 224 | texture.as_image_copy(), |
| 225 | data, |
| 226 | wgpu::TexelCopyBufferLayout { |
| 227 | offset: 0, |
| 228 | bytes_per_row: Some(*stride as u32), |
| 229 | rows_per_image: Some(*h), |
| 230 | }, |
| 231 | wgpu::Extent3d { |
| 232 | width: *w, |
| 233 | height: *h, |
| 234 | depth_or_array_layers: 1, |
| 235 | }, |
| 236 | ); |
| 237 | } |
| 238 | let params = Params { |
| 239 | nv12: frame.nv12.into(), |
| 240 | full_range: frame.full_range.into(), |
| 241 | bt709: frame.bt709.into(), |
| 242 | srgb_target: self.srgb_target.into(), |
| 243 | }; |
| 244 | queue.write_buffer(&self.params, 0, ¶ms.bytes()); |
| 245 | } |
| 246 | |
| 247 | fn create_textures(&self, device: &wgpu::Device, frame: &YuvFrame) -> Textures { |
| 248 | let make = |w: u32, h: u32, format| { |
| 249 | device.create_texture(&wgpu::TextureDescriptor { |
| 250 | label: Some("video-plane"), |
| 251 | size: wgpu::Extent3d { |
| 252 | width: w.max(1), |
| 253 | height: h.max(1), |
| 254 | depth_or_array_layers: 1, |
| 255 | }, |
| 256 | mip_level_count: 1, |
| 257 | sample_count: 1, |
| 258 | dimension: wgpu::TextureDimension::D2, |
| 259 | format, |
| 260 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, |
| 261 | view_formats: &[], |
| 262 | }) |
| 263 | }; |
| 264 | let (cw, ch) = (frame.width.div_ceil(2), frame.height.div_ceil(2)); |
| 265 | let mut planes = vec![make( |
| 266 | frame.width, |
| 267 | frame.height, |
| 268 | wgpu::TextureFormat::R8Unorm, |
| 269 | )]; |
| 270 | if frame.nv12 { |
| 271 | planes.push(make(cw, ch, wgpu::TextureFormat::Rg8Unorm)); |
| 272 | // V 자리는 쓰지 않지만 바인딩을 채우기 위해 1x1 텍스처를 둔다. |
| 273 | planes.push(make(1, 1, wgpu::TextureFormat::R8Unorm)); |
| 274 | } else { |
| 275 | planes.push(make(cw, ch, wgpu::TextureFormat::R8Unorm)); |
| 276 | planes.push(make(cw, ch, wgpu::TextureFormat::R8Unorm)); |
| 277 | } |
| 278 | let views: Vec<_> = planes |
| 279 | .iter() |
| 280 | .map(|t| t.create_view(&Default::default())) |
| 281 | .collect(); |
| 282 | let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 283 | label: Some("video-yuv"), |
| 284 | layout: &self.layout, |
| 285 | entries: &[ |
| 286 | wgpu::BindGroupEntry { |
| 287 | binding: 0, |
| 288 | resource: wgpu::BindingResource::Sampler(&self.sampler), |
| 289 | }, |
| 290 | wgpu::BindGroupEntry { |
| 291 | binding: 1, |
| 292 | resource: wgpu::BindingResource::TextureView(&views[0]), |
| 293 | }, |
| 294 | wgpu::BindGroupEntry { |
| 295 | binding: 2, |
| 296 | resource: wgpu::BindingResource::TextureView(&views[1]), |
| 297 | }, |
| 298 | wgpu::BindGroupEntry { |
| 299 | binding: 3, |
| 300 | resource: wgpu::BindingResource::TextureView(&views[2]), |
| 301 | }, |
| 302 | wgpu::BindGroupEntry { |
| 303 | binding: 4, |
| 304 | resource: self.params.as_entire_binding(), |
| 305 | }, |
| 306 | ], |
| 307 | }); |
| 308 | Textures { |
| 309 | key: (frame.width, frame.height, frame.nv12), |
| 310 | planes, |
| 311 | bind_group, |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /// 한 번의 그리기 요청. 아직 올리지 않은 번호의 프레임이면 텍스처에 쓴 뒤 그린다. |
| 317 | /// |
| 318 | /// egui는 한 프레임에 여러 패스를 돌리고 그중 하나만 그릴 수 있으므로, "새 프레임은 한 번만 |
| 319 | /// 넘긴다" 대신 항상 최신 프레임과 번호를 넘기고 GPU 쪽에서 중복 업로드를 거른다. |
| 320 | pub struct VideoCallback { |
| 321 | pub frame: Arc<YuvFrame>, |
| 322 | pub seq: u64, |
| 323 | } |
| 324 | |
| 325 | impl CallbackTrait for VideoCallback { |
| 326 | fn prepare( |
| 327 | &self, |
| 328 | device: &wgpu::Device, |
| 329 | queue: &wgpu::Queue, |
| 330 | _screen: &ScreenDescriptor, |
| 331 | _encoder: &mut wgpu::CommandEncoder, |
| 332 | resources: &mut CallbackResources, |
| 333 | ) -> Vec<wgpu::CommandBuffer> { |
| 334 | if let Some(pipeline) = resources.get_mut::<VideoPipeline>() |
| 335 | && pipeline.uploaded != Some(self.seq) |
| 336 | { |
| 337 | pipeline.upload(device, queue, &self.frame); |
| 338 | pipeline.uploaded = Some(self.seq); |
| 339 | } |
| 340 | Vec::new() |
| 341 | } |
| 342 | |
| 343 | fn paint( |
| 344 | &self, |
| 345 | _info: egui::PaintCallbackInfo, |
| 346 | render_pass: &mut wgpu::RenderPass<'static>, |
| 347 | resources: &CallbackResources, |
| 348 | ) { |
| 349 | let Some(pipeline) = resources.get::<VideoPipeline>() else { |
| 350 | return; |
| 351 | }; |
| 352 | let Some(tex) = &pipeline.textures else { |
| 353 | return; |
| 354 | }; |
| 355 | render_pass.set_pipeline(&pipeline.pipeline); |
| 356 | render_pass.set_bind_group(0, &tex.bind_group, &[]); |
| 357 | render_pass.draw(0..3, 0..1); |
| 358 | } |
| 359 | } |