leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

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