leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! FFmpeg 기반 저지연 비디오 디코더. |
| 2 | //! |
| 3 | //! - 비디오 패킷 헤더만 보고 동작한다. CONFIG 패킷을 기억해 두었다가 키프레임마다 앞에 붙인다. |
| 4 | //! - `config_gen`이 바뀐 CONFIG가 오면 코덱 컨텍스트를 새로 만든다(해상도 변경 대응). |
| 5 | //! - 재정렬 지연이 없도록 `AV_CODEC_FLAG_LOW_DELAY`를 켜고 프레임 스레딩은 쓰지 않는다. |
| 6 | //! - 하드웨어(CUDA → VA-API) 디코딩이 실패하면 소프트웨어로 한 번 전환한다. |
| 7 | |
| 8 | use std::cell::Cell; |
| 9 | use std::error::Error; |
| 10 | use std::ffi::CString; |
| 11 | use std::fmt; |
| 12 | use std::mem::ManuallyDrop; |
| 13 | use std::ops::{Deref, DerefMut}; |
| 14 | use std::ptr; |
| 15 | use std::sync::{Mutex, MutexGuard}; |
| 16 | |
| 17 | use ff::codec::{self, threading}; |
| 18 | use ff::color; |
| 19 | use ff::format::Pixel; |
| 20 | use ff::software::scaling; |
| 21 | use ff::util::frame::video::Video as Frame; |
| 22 | use ffmpeg_next as ff; |
| 23 | use ffmpeg_sys_next as sys; |
| 24 | use log::{debug, info, warn}; |
| 25 | |
| 26 | use crate::protocol::{VideoCodec, VideoPacketHeader}; |
| 27 | |
| 28 | /// 렌더러가 처리해야 하는 평면 배치. |
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 30 | pub enum PlaneLayout { |
| 31 | /// Y, U, V 3평면. 텍셀당 1바이트, 색차 평면은 가로·세로 1/2(올림). |
| 32 | I420, |
| 33 | /// Y + 인터리브 UV 2평면. UV 평면은 텍셀당 2바이트(U, V 순), 가로·세로 1/2(올림). |
| 34 | Nv12, |
| 35 | } |
| 36 | |
| 37 | impl PlaneLayout { |
| 38 | pub fn plane_count(self) -> usize { |
| 39 | match self { |
| 40 | Self::I420 => 3, |
| 41 | Self::Nv12 => 2, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// `plane`번 평면의 텍셀당 바이트 수. |
| 46 | pub fn bytes_per_texel(self, plane: usize) -> usize { |
| 47 | match (self, plane) { |
| 48 | (Self::Nv12, 1) => 2, |
| 49 | _ => 1, |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// 디코딩된 한 평면. 행 사이 패딩 없이 담는다(`stride == width * 텍셀당 바이트`). |
| 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 56 | pub struct Plane { |
| 57 | pub data: Vec<u8>, |
| 58 | /// 행 간격(바이트). |
| 59 | pub stride: usize, |
| 60 | /// 텍셀 단위 너비. |
| 61 | pub width: u32, |
| 62 | /// 행 수. |
| 63 | pub height: u32, |
| 64 | } |
| 65 | |
| 66 | /// YUV→RGB 변환 행렬. |
| 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 68 | pub enum ColorMatrix { |
| 69 | Bt601, |
| 70 | Bt709, |
| 71 | } |
| 72 | |
| 73 | /// 프레임 색 정보. 스트림에 명시되지 않으면 BT.709 제한 범위. |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 75 | pub struct ColorInfo { |
| 76 | pub matrix: ColorMatrix, |
| 77 | /// true면 0~255 전체 범위, false면 16~235(색차 16~240) 제한 범위. |
| 78 | pub full_range: bool, |
| 79 | } |
| 80 | |
| 81 | impl Default for ColorInfo { |
| 82 | fn default() -> Self { |
| 83 | Self { |
| 84 | matrix: ColorMatrix::Bt709, |
| 85 | full_range: false, |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /// 렌더러에 넘길 시스템 메모리 프레임. |
| 91 | #[derive(Debug, Clone)] |
| 92 | pub struct DecodedFrame { |
| 93 | pub width: u32, |
| 94 | pub height: u32, |
| 95 | pub layout: PlaneLayout, |
| 96 | /// `layout.plane_count()`개. |
| 97 | pub planes: Vec<Plane>, |
| 98 | pub color: ColorInfo, |
| 99 | pub pts_us: u64, |
| 100 | pub config_gen: u8, |
| 101 | } |
| 102 | |
| 103 | /// 실제 디코딩을 수행하는 백엔드. |
| 104 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 105 | pub enum Backend { |
| 106 | /// NVDEC (CUDA hwaccel). |
| 107 | Cuda, |
| 108 | Vaapi, |
| 109 | Software, |
| 110 | } |
| 111 | |
| 112 | impl Backend { |
| 113 | fn hw(self) -> Option<(sys::AVHWDeviceType, GetFormatFn)> { |
| 114 | match self { |
| 115 | Self::Cuda => Some((sys::AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA, get_format_cuda)), |
| 116 | Self::Vaapi => Some(( |
| 117 | sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI, |
| 118 | get_format_vaapi, |
| 119 | )), |
| 120 | Self::Software => None, |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl fmt::Display for Backend { |
| 126 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 127 | f.write_str(match self { |
| 128 | Self::Cuda => "CUDA(NVDEC)", |
| 129 | Self::Vaapi => "VA-API", |
| 130 | Self::Software => "소프트웨어", |
| 131 | }) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 136 | pub enum DecodeError { |
| 137 | /// 디코더를 만들 수 없음. 복구 불가. |
| 138 | Init(String), |
| 139 | /// 이 패킷을 디코딩하지 못함. 키프레임을 요청하고 계속 넣으면 된다. |
| 140 | Corrupt(String), |
| 141 | /// 백엔드 전환 등으로 참조 프레임을 잃음. 키프레임 전까지 일반 프레임은 버린다. |
| 142 | NeedKeyframe, |
| 143 | } |
| 144 | |
| 145 | impl DecodeError { |
| 146 | /// 호출자가 기기에 키프레임을 요청해야 하는 오류인지. |
| 147 | pub fn needs_keyframe(&self) -> bool { |
| 148 | matches!(self, Self::Corrupt(_) | Self::NeedKeyframe) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl fmt::Display for DecodeError { |
| 153 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 154 | match self { |
| 155 | Self::Init(m) => write!(f, "디코더 초기화 실패: {m}"), |
| 156 | Self::Corrupt(m) => write!(f, "패킷 디코딩 실패: {m}"), |
| 157 | Self::NeedKeyframe => f.write_str("키프레임 필요"), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | impl Error for DecodeError {} |
| 163 | |
| 164 | /// 하드웨어 디코더(CUDA 등) 생성·디코딩·해제를 프로세스 전체에서 한 번에 하나로 묶는 잠금. |
| 165 | /// |
| 166 | /// 여러 스레드가 동시에 NVDEC 디코더를 만들거나 해제하면 드라이버 안에서 멈추는 일이 있었다 |
| 167 | /// (병렬 테스트에서 재현). 앱은 디코더를 하나만 쓰므로 비용은 없고, 빠르게 다시 연결할 때 |
| 168 | /// 이전 디코더 해제와 새 디코더 생성이 겹치는 경우도 막는다. 같은 스레드 안에서는 다시 |
| 169 | /// 잡을 수 있다(디코딩 중 컨텍스트 재생성). |
| 170 | static HW_LOCK: Mutex<()> = Mutex::new(()); |
| 171 | |
| 172 | thread_local! { |
| 173 | static HW_DEPTH: Cell<u32> = const { Cell::new(0) }; |
| 174 | } |
| 175 | |
| 176 | struct HwGuard { |
| 177 | _lock: Option<MutexGuard<'static, ()>>, |
| 178 | } |
| 179 | |
| 180 | impl HwGuard { |
| 181 | fn acquire() -> Self { |
| 182 | let depth = HW_DEPTH.get(); |
| 183 | let guard = (depth == 0).then(|| HW_LOCK.lock().unwrap_or_else(|e| e.into_inner())); |
| 184 | HW_DEPTH.set(depth + 1); |
| 185 | Self { _lock: guard } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl Drop for HwGuard { |
| 190 | fn drop(&mut self) { |
| 191 | HW_DEPTH.set(HW_DEPTH.get() - 1); |
| 192 | // 잠금은 필드(MutexGuard)가 이 다음에 해제될 때 풀린다. |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// 잠금을 잡은 채 해제되는 코덱 컨텍스트. |
| 197 | struct Ctx(ManuallyDrop<ff::decoder::Video>); |
| 198 | |
| 199 | impl Ctx { |
| 200 | fn new(dec: ff::decoder::Video) -> Self { |
| 201 | Self(ManuallyDrop::new(dec)) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | impl Deref for Ctx { |
| 206 | type Target = ff::decoder::Video; |
| 207 | fn deref(&self) -> &Self::Target { |
| 208 | &self.0 |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | impl DerefMut for Ctx { |
| 213 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 214 | &mut self.0 |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl Drop for Ctx { |
| 219 | fn drop(&mut self) { |
| 220 | let _hw = HwGuard::acquire(); |
| 221 | // SAFETY: 이 Drop에서 한 번만 해제하고 이후 접근하지 않는다. |
| 222 | unsafe { ManuallyDrop::drop(&mut self.0) }; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /// 저지연 디코더. 한 비디오 채널에 하나. |
| 227 | pub struct Decoder { |
| 228 | codec: VideoCodec, |
| 229 | /// None이면 소프트웨어 디코딩. |
| 230 | device: Option<HwDevice>, |
| 231 | dec: Ctx, |
| 232 | /// 현재 컨텍스트에 패킷을 넣은 적이 있는지. |
| 233 | fed: bool, |
| 234 | /// 현재 컨텍스트가 프레임을 한 장이라도 냈는지. hw 실패 판단에 쓴다. |
| 235 | produced: bool, |
| 236 | cur_gen: Option<u8>, |
| 237 | /// 현재 세대의 코덱 설정(Annex-B 파라미터 셋). |
| 238 | config: Option<Vec<u8>>, |
| 239 | have_keyframe: bool, |
| 240 | frame: Frame, |
| 241 | /// hw 프레임을 시스템 메모리로 옮길 버퍼. |
| 242 | sw_frame: Frame, |
| 243 | scaler: Option<Scaler>, |
| 244 | } |
| 245 | |
| 246 | impl Decoder { |
| 247 | /// `prefer_hw`면 CUDA → VA-API → 소프트웨어 순으로 시도한다. |
| 248 | pub fn new(codec: VideoCodec, prefer_hw: bool) -> Result<Self, DecodeError> { |
| 249 | if prefer_hw { |
| 250 | Self::with_backends(codec, &[Backend::Cuda, Backend::Vaapi, Backend::Software]) |
| 251 | } else { |
| 252 | Self::with_backends(codec, &[Backend::Software]) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// `order` 순서대로 처음 열리는 백엔드를 쓴다. |
| 257 | pub fn with_backends(codec: VideoCodec, order: &[Backend]) -> Result<Self, DecodeError> { |
| 258 | let _hw = HwGuard::acquire(); |
| 259 | let mut last = String::from("백엔드 목록이 비어 있음"); |
| 260 | for &backend in order { |
| 261 | match Self::open_backend(codec, backend) { |
| 262 | Ok(d) => { |
| 263 | info!("비디오 디코더: {codec:?} / {backend}"); |
| 264 | return Ok(d); |
| 265 | } |
| 266 | Err(e) => { |
| 267 | info!("{backend} 디코더 사용 불가({codec:?}): {e}"); |
| 268 | last = format!("{backend}: {e}"); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | Err(DecodeError::Init(last)) |
| 273 | } |
| 274 | |
| 275 | fn open_backend(codec: VideoCodec, backend: Backend) -> Result<Self, String> { |
| 276 | let device = match backend.hw() { |
| 277 | None => None, |
| 278 | Some(_) => Some(HwDevice::create(codec, backend)?), |
| 279 | }; |
| 280 | let dec = Ctx::new(open_context(codec, device.as_ref())?); |
| 281 | Ok(Self { |
| 282 | codec, |
| 283 | device, |
| 284 | dec, |
| 285 | fed: false, |
| 286 | produced: false, |
| 287 | cur_gen: None, |
| 288 | config: None, |
| 289 | have_keyframe: false, |
| 290 | frame: Frame::empty(), |
| 291 | sw_frame: Frame::empty(), |
| 292 | scaler: None, |
| 293 | }) |
| 294 | } |
| 295 | |
| 296 | pub fn backend(&self) -> Backend { |
| 297 | self.device |
| 298 | .as_ref() |
| 299 | .map_or(Backend::Software, |d| d.backend) |
| 300 | } |
| 301 | |
| 302 | pub fn codec(&self) -> VideoCodec { |
| 303 | self.codec |
| 304 | } |
| 305 | |
| 306 | /// 패킷 하나를 넣고 지금 나온 프레임(0..n장)을 돌려준다. |
| 307 | /// |
| 308 | /// 설정을 받지 못한 세대의 패킷, 키프레임 전의 일반 프레임은 조용히 버린다. |
| 309 | pub fn decode( |
| 310 | &mut self, |
| 311 | header: &VideoPacketHeader, |
| 312 | data: &[u8], |
| 313 | ) -> Result<Vec<DecodedFrame>, DecodeError> { |
| 314 | let _hw = HwGuard::acquire(); |
| 315 | if header.is_config { |
| 316 | return self.handle_config(header.config_gen, data); |
| 317 | } |
| 318 | if self.cur_gen != Some(header.config_gen) || self.config.is_none() { |
| 319 | debug!("설정 전 세대 {} 패킷 버림", header.config_gen); |
| 320 | return Ok(Vec::new()); |
| 321 | } |
| 322 | if data.is_empty() || (!header.is_keyframe && !self.have_keyframe) { |
| 323 | debug!("키프레임 전 패킷 버림 (pts {})", header.pts_us); |
| 324 | return Ok(Vec::new()); |
| 325 | } |
| 326 | let packet = self.build_packet(header, data)?; |
| 327 | if header.is_keyframe { |
| 328 | self.have_keyframe = true; |
| 329 | } |
| 330 | self.feed(&packet, header.is_keyframe) |
| 331 | } |
| 332 | |
| 333 | fn handle_config( |
| 334 | &mut self, |
| 335 | new_gen: u8, |
| 336 | data: &[u8], |
| 337 | ) -> Result<Vec<DecodedFrame>, DecodeError> { |
| 338 | let config = normalize_config(self.codec, data); |
| 339 | if config.is_empty() { |
| 340 | warn!("빈 CONFIG 패킷 무시 (세대 {new_gen})"); |
| 341 | return Ok(Vec::new()); |
| 342 | } |
| 343 | let same_gen = self.cur_gen == Some(new_gen); |
| 344 | if same_gen && self.config.as_deref() == Some(config) { |
| 345 | return Ok(Vec::new()); |
| 346 | } |
| 347 | let mut out = Vec::new(); |
| 348 | if self.fed { |
| 349 | // 이전 세대 잔여 프레임을 비우고 컨텍스트를 새로 만든다. |
| 350 | if let Err(f) = self.run(None, &mut out) { |
| 351 | debug!("이전 세대 비우기 실패: {}", f.message()); |
| 352 | } |
| 353 | self.reopen()?; |
| 354 | } |
| 355 | if !same_gen { |
| 356 | info!("비디오 설정 세대 {new_gen} ({} 바이트)", config.len()); |
| 357 | } |
| 358 | self.cur_gen = Some(new_gen); |
| 359 | self.config = Some(config.to_vec()); |
| 360 | self.have_keyframe = false; |
| 361 | Ok(out) |
| 362 | } |
| 363 | |
| 364 | /// 키프레임이면 설정을 앞에 붙여 한 번만 복사한다. |
| 365 | fn build_packet( |
| 366 | &self, |
| 367 | header: &VideoPacketHeader, |
| 368 | data: &[u8], |
| 369 | ) -> Result<ff::Packet, DecodeError> { |
| 370 | let prefix: &[u8] = match (&self.config, header.is_keyframe) { |
| 371 | (Some(c), true) => c, |
| 372 | _ => &[], |
| 373 | }; |
| 374 | let mut packet = ff::Packet::new(prefix.len() + data.len()); |
| 375 | let buf = packet |
| 376 | .data_mut() |
| 377 | .ok_or_else(|| DecodeError::Corrupt("패킷 버퍼 할당 실패".into()))?; |
| 378 | buf[..prefix.len()].copy_from_slice(prefix); |
| 379 | buf[prefix.len()..].copy_from_slice(data); |
| 380 | let pts = i64::try_from(header.pts_us).unwrap_or(i64::MAX); |
| 381 | packet.set_pts(Some(pts)); |
| 382 | packet.set_dts(Some(pts)); |
| 383 | if header.is_keyframe { |
| 384 | packet.set_flags(codec::packet::Flags::KEY); |
| 385 | } |
| 386 | Ok(packet) |
| 387 | } |
| 388 | |
| 389 | fn feed( |
| 390 | &mut self, |
| 391 | packet: &ff::Packet, |
| 392 | is_keyframe: bool, |
| 393 | ) -> Result<Vec<DecodedFrame>, DecodeError> { |
| 394 | self.fed = true; |
| 395 | let mut out = Vec::new(); |
| 396 | let fail = match self.run(Some(packet), &mut out) { |
| 397 | Ok(()) => return Ok(out), |
| 398 | Err(f) => f, |
| 399 | }; |
| 400 | // 한 번도 프레임을 못 냈거나 전송 자체가 실패하면 hw가 이 스트림을 못 다루는 것으로 본다. |
| 401 | let hw_broken = self.device.is_some() && (matches!(fail, Fail::Hw(_)) || !self.produced); |
| 402 | if !hw_broken { |
| 403 | return Err(DecodeError::Corrupt(fail.message().to_owned())); |
| 404 | } |
| 405 | warn!( |
| 406 | "{} 디코딩 실패({}), 소프트웨어 디코더로 전환", |
| 407 | self.backend(), |
| 408 | fail.message() |
| 409 | ); |
| 410 | self.switch_to_software()?; |
| 411 | if !is_keyframe { |
| 412 | self.have_keyframe = false; |
| 413 | return Err(DecodeError::NeedKeyframe); |
| 414 | } |
| 415 | // 키프레임은 설정이 붙어 있으므로 새 디코더에 그대로 다시 넣는다. |
| 416 | out.clear(); |
| 417 | self.fed = true; |
| 418 | self.run(Some(packet), &mut out) |
| 419 | .map_err(|f| DecodeError::Corrupt(f.message().to_owned()))?; |
| 420 | Ok(out) |
| 421 | } |
| 422 | |
| 423 | fn reopen(&mut self) -> Result<(), DecodeError> { |
| 424 | match open_context(self.codec, self.device.as_ref()) { |
| 425 | Ok(dec) => { |
| 426 | self.dec = Ctx::new(dec); |
| 427 | self.fed = false; |
| 428 | self.produced = false; |
| 429 | Ok(()) |
| 430 | } |
| 431 | Err(e) if self.device.is_some() => { |
| 432 | warn!( |
| 433 | "{} 디코더 재생성 실패({e}), 소프트웨어로 전환", |
| 434 | self.backend() |
| 435 | ); |
| 436 | self.switch_to_software() |
| 437 | } |
| 438 | Err(e) => Err(DecodeError::Init(e)), |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | fn switch_to_software(&mut self) -> Result<(), DecodeError> { |
| 443 | self.dec = Ctx::new(open_context(self.codec, None).map_err(DecodeError::Init)?); |
| 444 | self.device = None; |
| 445 | self.fed = false; |
| 446 | self.produced = false; |
| 447 | Ok(()) |
| 448 | } |
| 449 | |
| 450 | /// 패킷(None이면 EOF)을 넣고 나온 프레임을 모두 꺼낸다. |
| 451 | fn run( |
| 452 | &mut self, |
| 453 | packet: Option<&ff::Packet>, |
| 454 | out: &mut Vec<DecodedFrame>, |
| 455 | ) -> Result<(), Fail> { |
| 456 | let send = |dec: &mut ff::decoder::Video| match packet { |
| 457 | Some(p) => dec.send_packet(p), |
| 458 | None => dec.send_eof(), |
| 459 | }; |
| 460 | match send(&mut self.dec) { |
| 461 | Ok(()) => {} |
| 462 | Err(e) if is_again(&e) => { |
| 463 | // 출력이 쌓여 입력을 거부함: 먼저 꺼낸 뒤 다시 넣는다. |
| 464 | self.receive_all(out)?; |
| 465 | send(&mut self.dec).map_err(|e| Fail::Codec(e.to_string()))?; |
| 466 | } |
| 467 | Err(ff::Error::Eof) => {} |
| 468 | Err(e) => return Err(Fail::Codec(e.to_string())), |
| 469 | } |
| 470 | self.receive_all(out) |
| 471 | } |
| 472 | |
| 473 | fn receive_all(&mut self, out: &mut Vec<DecodedFrame>) -> Result<(), Fail> { |
| 474 | loop { |
| 475 | match self.dec.receive_frame(&mut self.frame) { |
| 476 | Ok(()) => { |
| 477 | out.push(self.convert()?); |
| 478 | self.produced = true; |
| 479 | } |
| 480 | Err(ff::Error::Eof) => return Ok(()), |
| 481 | Err(e) if is_again(&e) => return Ok(()), |
| 482 | Err(e) => return Err(Fail::Codec(e.to_string())), |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /// `self.frame`을 시스템 메모리 평면으로 복사한다. |
| 488 | fn convert(&mut self) -> Result<DecodedFrame, Fail> { |
| 489 | let frame = &self.frame; |
| 490 | let color = color_info(frame); |
| 491 | let pts_us = frame.pts().and_then(|p| u64::try_from(p).ok()).unwrap_or(0); |
| 492 | // SAFETY: frame은 receive_frame이 채운 유효한 AVFrame. |
| 493 | let is_hw = unsafe { !(*frame.as_ptr()).hw_frames_ctx.is_null() }; |
| 494 | let src = if is_hw { |
| 495 | // SAFETY: 두 포인터 모두 유효한 AVFrame. sw_frame을 비운 뒤 넘기면 FFmpeg가 |
| 496 | // 첫 지원 형식(8비트면 NV12)으로 버퍼를 할당하고 크롭된 크기를 설정한다. |
| 497 | let r = unsafe { |
| 498 | sys::av_frame_unref(self.sw_frame.as_mut_ptr()); |
| 499 | sys::av_hwframe_transfer_data(self.sw_frame.as_mut_ptr(), frame.as_ptr(), 0) |
| 500 | }; |
| 501 | if r < 0 { |
| 502 | return Err(Fail::Hw(format!( |
| 503 | "av_hwframe_transfer_data: {}", |
| 504 | ff::Error::from(r) |
| 505 | ))); |
| 506 | } |
| 507 | &self.sw_frame |
| 508 | } else { |
| 509 | frame |
| 510 | }; |
| 511 | let (layout, planes) = to_planes(src, &mut self.scaler).map_err(Fail::Convert)?; |
| 512 | Ok(DecodedFrame { |
| 513 | width: src.width(), |
| 514 | height: src.height(), |
| 515 | layout, |
| 516 | planes, |
| 517 | color: ColorInfo { |
| 518 | full_range: color.full_range || src.format() == Pixel::YUVJ420P, |
| 519 | ..color |
| 520 | }, |
| 521 | pts_us, |
| 522 | config_gen: self.cur_gen.unwrap_or(0), |
| 523 | }) |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | /// 디코딩 경로 내부 실패. hw 전용 실패는 소프트웨어 전환 근거가 된다. |
| 528 | enum Fail { |
| 529 | Codec(String), |
| 530 | Hw(String), |
| 531 | Convert(String), |
| 532 | } |
| 533 | |
| 534 | impl Fail { |
| 535 | fn message(&self) -> &str { |
| 536 | match self { |
| 537 | Self::Codec(m) | Self::Hw(m) | Self::Convert(m) => m, |
| 538 | } |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | fn is_again(e: &ff::Error) -> bool { |
| 543 | matches!(e, ff::Error::Other { errno } if *errno == ff::util::error::EAGAIN) |
| 544 | } |
| 545 | |
| 546 | type GetFormatFn = |
| 547 | unsafe extern "C" fn(*mut sys::AVCodecContext, *const sys::AVPixelFormat) -> sys::AVPixelFormat; |
| 548 | |
| 549 | unsafe extern "C" fn get_format_cuda( |
| 550 | _ctx: *mut sys::AVCodecContext, |
| 551 | fmts: *const sys::AVPixelFormat, |
| 552 | ) -> sys::AVPixelFormat { |
| 553 | // SAFETY: FFmpeg가 AV_PIX_FMT_NONE으로 끝나는 목록을 넘긴다. |
| 554 | unsafe { pick_format(fmts, sys::AVPixelFormat::AV_PIX_FMT_CUDA) } |
| 555 | } |
| 556 | |
| 557 | unsafe extern "C" fn get_format_vaapi( |
| 558 | _ctx: *mut sys::AVCodecContext, |
| 559 | fmts: *const sys::AVPixelFormat, |
| 560 | ) -> sys::AVPixelFormat { |
| 561 | // SAFETY: get_format_cuda와 같음. |
| 562 | unsafe { pick_format(fmts, sys::AVPixelFormat::AV_PIX_FMT_VAAPI) } |
| 563 | } |
| 564 | |
| 565 | /// 목록에 hw 형식이 없으면 NONE을 돌려 디코딩을 실패시킨다(→ 소프트웨어 전환). |
| 566 | /// |
| 567 | /// # Safety |
| 568 | /// `fmts`는 AV_PIX_FMT_NONE으로 끝나는 유효한 배열이어야 한다. |
| 569 | unsafe fn pick_format( |
| 570 | mut fmts: *const sys::AVPixelFormat, |
| 571 | want: sys::AVPixelFormat, |
| 572 | ) -> sys::AVPixelFormat { |
| 573 | use sys::AVPixelFormat::AV_PIX_FMT_NONE; |
| 574 | if fmts.is_null() { |
| 575 | return AV_PIX_FMT_NONE; |
| 576 | } |
| 577 | // SAFETY: 호출자 보장. NONE을 만나기 전까지만 읽는다. |
| 578 | unsafe { |
| 579 | while *fmts != AV_PIX_FMT_NONE { |
| 580 | if *fmts == want { |
| 581 | return want; |
| 582 | } |
| 583 | fmts = fmts.add(1); |
| 584 | } |
| 585 | } |
| 586 | AV_PIX_FMT_NONE |
| 587 | } |
| 588 | |
| 589 | /// hw 디바이스 컨텍스트 참조. |
| 590 | struct HwDevice { |
| 591 | backend: Backend, |
| 592 | get_format: GetFormatFn, |
| 593 | buf: *mut sys::AVBufferRef, |
| 594 | } |
| 595 | |
| 596 | // SAFETY: AVBufferRef 참조 카운트는 원자적이고 디바이스 컨텍스트는 스레드 간 이동이 허용된다. |
| 597 | unsafe impl Send for HwDevice {} |
| 598 | |
| 599 | impl HwDevice { |
| 600 | fn create(codec: VideoCodec, backend: Backend) -> Result<Self, String> { |
| 601 | let (ty, get_format) = backend.hw().ok_or("hw 백엔드가 아님")?; |
| 602 | let dec = find_decoder(codec, true)?; |
| 603 | if !supports_device(&dec, ty) { |
| 604 | return Err(format!( |
| 605 | "{} 디코더가 이 hw 가속을 지원하지 않음", |
| 606 | dec.name() |
| 607 | )); |
| 608 | } |
| 609 | // VA-API 기본 장치는 첫 렌더 노드라서 드라이버가 없는 GPU(예: iGPU)를 고를 수 있다. |
| 610 | // 실패하면 렌더 노드를 차례로 시도한다. |
| 611 | let mut candidates: Vec<Option<CString>> = vec![None]; |
| 612 | if backend == Backend::Vaapi { |
| 613 | candidates.extend(render_nodes().into_iter().map(Some)); |
| 614 | } |
| 615 | let mut last = String::new(); |
| 616 | let mut found = None; |
| 617 | for dev in &candidates { |
| 618 | let mut buf = ptr::null_mut(); |
| 619 | let dev_ptr = dev.as_ref().map_or(ptr::null(), |d| d.as_ptr()); |
| 620 | // SAFETY: buf는 출력 인자, dev_ptr은 NULL 또는 살아 있는 C 문자열, opts는 NULL 허용. |
| 621 | let r = |
| 622 | unsafe { sys::av_hwdevice_ctx_create(&mut buf, ty, dev_ptr, ptr::null_mut(), 0) }; |
| 623 | if r >= 0 && !buf.is_null() { |
| 624 | if let Some(d) = dev { |
| 625 | info!("{backend} 장치: {}", d.to_string_lossy()); |
| 626 | } |
| 627 | found = Some(buf); |
| 628 | break; |
| 629 | } |
| 630 | last = format!("av_hwdevice_ctx_create: {}", ff::Error::from(r)); |
| 631 | } |
| 632 | let buf = found.ok_or(last)?; |
| 633 | Ok(Self { |
| 634 | backend, |
| 635 | get_format, |
| 636 | buf, |
| 637 | }) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | /// `/dev/dri/renderD*` 경로(이름순). |
| 642 | fn render_nodes() -> Vec<CString> { |
| 643 | let Ok(dir) = std::fs::read_dir("/dev/dri") else { |
| 644 | return Vec::new(); |
| 645 | }; |
| 646 | let mut nodes: Vec<String> = dir |
| 647 | .filter_map(|e| e.ok()) |
| 648 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 649 | .filter(|n| n.starts_with("renderD")) |
| 650 | .collect(); |
| 651 | nodes.sort(); |
| 652 | nodes |
| 653 | .into_iter() |
| 654 | .filter_map(|n| CString::new(format!("/dev/dri/{n}")).ok()) |
| 655 | .collect() |
| 656 | } |
| 657 | |
| 658 | impl Drop for HwDevice { |
| 659 | fn drop(&mut self) { |
| 660 | let _hw = HwGuard::acquire(); |
| 661 | // SAFETY: create에서 얻은 참조를 한 번만 해제한다. |
| 662 | unsafe { sys::av_buffer_unref(&mut self.buf) }; |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | fn supports_device(dec: &ff::Codec, ty: sys::AVHWDeviceType) -> bool { |
| 667 | let method = sys::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX as i32; |
| 668 | for i in 0.. { |
| 669 | // SAFETY: 유효한 AVCodec 포인터. 범위를 넘으면 NULL을 돌려준다. |
| 670 | let cfg = unsafe { sys::avcodec_get_hw_config(dec.as_ptr(), i) }; |
| 671 | if cfg.is_null() { |
| 672 | return false; |
| 673 | } |
| 674 | // SAFETY: NULL이 아닌 정적 설정 구조체. |
| 675 | let cfg = unsafe { &*cfg }; |
| 676 | if cfg.methods & method != 0 && cfg.device_type == ty { |
| 677 | return true; |
| 678 | } |
| 679 | } |
| 680 | false |
| 681 | } |
| 682 | |
| 683 | /// 내장 디코더를 이름으로 고른다(cuvid 등 래퍼 디코더를 피하기 위해). |
| 684 | fn find_decoder(codec: VideoCodec, hw: bool) -> Result<ff::Codec, String> { |
| 685 | let (names, id): (&[&str], _) = match (codec, hw) { |
| 686 | (VideoCodec::H264, _) => (&["h264"], codec::Id::H264), |
| 687 | (VideoCodec::H265, _) => (&["hevc"], codec::Id::HEVC), |
| 688 | // AV1 hw 가속은 내장 av1 디코더에서만, 소프트웨어는 dav1d가 빠르다. |
| 689 | (VideoCodec::Av1, true) => (&["av1"], codec::Id::AV1), |
| 690 | (VideoCodec::Av1, false) => (&["libdav1d", "libaom-av1"], codec::Id::AV1), |
| 691 | }; |
| 692 | names |
| 693 | .iter() |
| 694 | .find_map(|n| ff::decoder::find_by_name(n)) |
| 695 | .or_else(|| if hw { None } else { ff::decoder::find(id) }) |
| 696 | .ok_or_else(|| format!("{codec:?} 디코더를 찾을 수 없음")) |
| 697 | } |
| 698 | |
| 699 | fn open_context( |
| 700 | codec: VideoCodec, |
| 701 | device: Option<&HwDevice>, |
| 702 | ) -> Result<ff::decoder::Video, String> { |
| 703 | let dec_codec = find_decoder(codec, device.is_some())?; |
| 704 | let mut ctx = codec::Context::new_with_codec(dec_codec); |
| 705 | ctx.set_flags(codec::Flags::LOW_DELAY); |
| 706 | // 프레임 스레딩은 스레드 수만큼 출력이 늦어지므로 슬라이스 스레딩만 쓴다. |
| 707 | let mut threads = threading::Config::kind(threading::Type::Slice); |
| 708 | threads.count = if device.is_some() { 1 } else { 0 }; |
| 709 | ctx.set_threading(threads); |
| 710 | if let Some(dev) = device { |
| 711 | // SAFETY: 열기 전 컨텍스트 필드 설정. hw_device_ctx에는 새 참조를 넘기며 |
| 712 | // avcodec_free_context가 해제한다. |
| 713 | unsafe { |
| 714 | let p = ctx.as_mut_ptr(); |
| 715 | let r = sys::av_buffer_ref(dev.buf); |
| 716 | if r.is_null() { |
| 717 | return Err("av_buffer_ref 실패".into()); |
| 718 | } |
| 719 | (*p).hw_device_ctx = r; |
| 720 | (*p).get_format = Some(dev.get_format); |
| 721 | } |
| 722 | } |
| 723 | let mut d = ctx.decoder(); |
| 724 | d.set_packet_time_base((1, 1_000_000)); |
| 725 | d.open_as(dec_codec) |
| 726 | .and_then(|o| o.video()) |
| 727 | .map_err(|e| format!("{} 열기 실패: {e}", dec_codec.name())) |
| 728 | } |
| 729 | |
| 730 | /// MediaCodec AV1 CSD는 av1C 박스(4바이트 헤더 + OBU)일 수 있으므로 OBU만 남긴다. |
| 731 | fn normalize_config(codec: VideoCodec, data: &[u8]) -> &[u8] { |
| 732 | match (codec, data) { |
| 733 | (VideoCodec::Av1, [0x81, _, _, _, rest @ ..]) => rest, |
| 734 | _ => data, |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | fn color_info(frame: &Frame) -> ColorInfo { |
| 739 | let matrix = match frame.color_space() { |
| 740 | color::Space::BT470BG | color::Space::SMPTE170M | color::Space::FCC => ColorMatrix::Bt601, |
| 741 | _ => ColorMatrix::Bt709, |
| 742 | }; |
| 743 | ColorInfo { |
| 744 | matrix, |
| 745 | full_range: frame.color_range() == color::Range::JPEG, |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | /// SwsContext 래퍼. I420/NV12가 아닌 출력(10비트 등)을 I420으로 바꾼다. |
| 750 | struct Scaler { |
| 751 | key: (Pixel, u32, u32), |
| 752 | ctx: scaling::Context, |
| 753 | out: Frame, |
| 754 | } |
| 755 | |
| 756 | // SAFETY: SwsContext는 공유하지 않고 소유 스레드 하나에서만 쓰므로 이동은 안전하다. |
| 757 | unsafe impl Send for Scaler {} |
| 758 | |
| 759 | fn to_planes( |
| 760 | src: &Frame, |
| 761 | scaler: &mut Option<Scaler>, |
| 762 | ) -> Result<(PlaneLayout, Vec<Plane>), String> { |
| 763 | let (w, h) = (src.width(), src.height()); |
| 764 | if w == 0 || h == 0 { |
| 765 | return Err("크기가 0인 프레임".into()); |
| 766 | } |
| 767 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 768 | match src.format() { |
| 769 | Pixel::YUV420P | Pixel::YUVJ420P => Ok(( |
| 770 | PlaneLayout::I420, |
| 771 | vec![ |
| 772 | copy_plane(src, 0, w, h, 1)?, |
| 773 | copy_plane(src, 1, cw, ch, 1)?, |
| 774 | copy_plane(src, 2, cw, ch, 1)?, |
| 775 | ], |
| 776 | )), |
| 777 | Pixel::NV12 => Ok(( |
| 778 | PlaneLayout::Nv12, |
| 779 | vec![copy_plane(src, 0, w, h, 1)?, copy_plane(src, 1, cw, ch, 2)?], |
| 780 | )), |
| 781 | other => { |
| 782 | let key = (other, w, h); |
| 783 | if scaler.as_ref().is_none_or(|s| s.key != key) { |
| 784 | debug!("{other:?} 출력을 I420으로 변환"); |
| 785 | let ctx = scaling::Context::get( |
| 786 | other, |
| 787 | w, |
| 788 | h, |
| 789 | Pixel::YUV420P, |
| 790 | w, |
| 791 | h, |
| 792 | scaling::Flags::BILINEAR, |
| 793 | ) |
| 794 | .map_err(|e| format!("swscale 생성 실패({other:?}): {e}"))?; |
| 795 | *scaler = Some(Scaler { |
| 796 | key, |
| 797 | ctx, |
| 798 | out: Frame::empty(), |
| 799 | }); |
| 800 | } |
| 801 | let s = scaler.as_mut().ok_or("swscale 없음")?; |
| 802 | s.ctx |
| 803 | .run(src, &mut s.out) |
| 804 | .map_err(|e| format!("swscale 실패: {e}"))?; |
| 805 | Ok(( |
| 806 | PlaneLayout::I420, |
| 807 | vec![ |
| 808 | copy_plane(&s.out, 0, w, h, 1)?, |
| 809 | copy_plane(&s.out, 1, cw, ch, 1)?, |
| 810 | copy_plane(&s.out, 2, cw, ch, 1)?, |
| 811 | ], |
| 812 | )) |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | /// linesize 패딩을 제거해 빽빽한 평면으로 복사한다. |
| 818 | fn copy_plane( |
| 819 | src: &Frame, |
| 820 | index: usize, |
| 821 | width: u32, |
| 822 | height: u32, |
| 823 | bpt: usize, |
| 824 | ) -> Result<Plane, String> { |
| 825 | if index >= src.planes() { |
| 826 | return Err(format!("평면 {index} 없음 ({:?})", src.format())); |
| 827 | } |
| 828 | let row = width as usize * bpt; |
| 829 | let rows = height as usize; |
| 830 | let stride = src.stride(index); |
| 831 | let data = src.data(index); |
| 832 | if stride < row || data.len() < stride * (rows - 1) + row { |
| 833 | return Err(format!( |
| 834 | "평면 {index} 크기 불일치 (stride {stride}, 행 {row}B x {rows})" |
| 835 | )); |
| 836 | } |
| 837 | let mut buf = Vec::with_capacity(row * rows); |
| 838 | if stride == row { |
| 839 | buf.extend_from_slice(&data[..row * rows]); |
| 840 | } else { |
| 841 | for line in data.chunks(stride).take(rows) { |
| 842 | buf.extend_from_slice(&line[..row]); |
| 843 | } |
| 844 | } |
| 845 | Ok(Plane { |
| 846 | data: buf, |
| 847 | stride: row, |
| 848 | width, |
| 849 | height, |
| 850 | }) |
| 851 | } |