| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | #![forbid(unsafe_code)] |
| 20 | |
| 21 | use std::collections::HashMap; |
| 22 | use std::fmt; |
| 23 | |
| 24 | pub use ec_core::{Packet, TimeBase}; |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | #[derive(Debug)] |
| 31 | #[non_exhaustive] |
| 32 | pub enum Error { |
| 33 | |
| 34 | NeedMore, |
| 35 | |
| 36 | Eof, |
| 37 | |
| 38 | Unsupported(String), |
| 39 | |
| 40 | InvalidData(String), |
| 41 | |
| 42 | CodecNotFound(String), |
| 43 | |
| 44 | Io(std::io::Error), |
| 45 | |
| 46 | Other(String), |
| 47 | } |
| 48 | |
| 49 | impl fmt::Display for Error { |
| 50 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 51 | match self { |
| 52 | Error::NeedMore => write!(f, "more input needed"), |
| 53 | Error::Eof => write!(f, "end of stream"), |
| 54 | Error::Unsupported(what) => write!(f, "unsupported: {what}"), |
| 55 | Error::InvalidData(what) => write!(f, "invalid data: {what}"), |
| 56 | Error::CodecNotFound(id) => write!(f, "no codec {id}"), |
| 57 | Error::Io(e) => write!(f, "{e}"), |
| 58 | Error::Other(what) => write!(f, "{what}"), |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl std::error::Error for Error {} |
| 64 | |
| 65 | impl From<std::io::Error> for Error { |
| 66 | fn from(e: std::io::Error) -> Error { |
| 67 | Error::Io(e) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | impl From<ec_core::Error> for Error { |
| 72 | fn from(e: ec_core::Error) -> Error { |
| 73 | match e { |
| 74 | ec_core::Error::NeedMore => Error::NeedMore, |
| 75 | ec_core::Error::Eof => Error::Eof, |
| 76 | ec_core::Error::Unsupported { what, why } => { |
| 77 | Error::Unsupported(format!("{what}: {why}")) |
| 78 | } |
| 79 | ec_core::Error::Corrupt { context } => Error::InvalidData(context), |
| 80 | ec_core::Error::Io(e) => Error::Io(e), |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | |
| 86 | pub type Result<T> = std::result::Result<T, Error>; |
| 87 | |
| 88 | |
| 89 | #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 90 | pub struct CodecId(pub String); |
| 91 | |
| 92 | impl CodecId { |
| 93 | |
| 94 | pub fn new(s: impl Into<String>) -> CodecId { |
| 95 | CodecId(s.into()) |
| 96 | } |
| 97 | |
| 98 | |
| 99 | pub fn as_str(&self) -> &str { |
| 100 | &self.0 |
| 101 | } |
| 102 | |
| 103 | |
| 104 | pub fn to_ec(&self) -> Option<ec_core::CodecId> { |
| 105 | use ec_core::CodecId::*; |
| 106 | Some(match self.0.as_str() { |
| 107 | "h264" | "avc1" => H264, |
| 108 | "h265" | "hevc" => H265, |
| 109 | "vp8" => Vp8, |
| 110 | "vp9" => Vp9, |
| 111 | "av1" => Av1, |
| 112 | "aac" => Aac, |
| 113 | "ac3" => Ac3, |
| 114 | "eac3" => EAc3, |
| 115 | "alac" => Alac, |
| 116 | "flac" => Flac, |
| 117 | "mp3" => Mp3, |
| 118 | "opus" => Opus, |
| 119 | "vorbis" => Vorbis, |
| 120 | "srt" | "subrip" => Srt, |
| 121 | "webvtt" | "vtt" => WebVtt, |
| 122 | "ass" | "ssa" => Ass, |
| 123 | "pgs" => Pgs, |
| 124 | "tx3g" => Tx3g, |
| 125 | _ => return None, |
| 126 | }) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | impl fmt::Display for CodecId { |
| 131 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 132 | f.write_str(&self.0) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | |
| 137 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 138 | pub enum MediaType { |
| 139 | |
| 140 | Audio, |
| 141 | |
| 142 | Video, |
| 143 | |
| 144 | Subtitle, |
| 145 | |
| 146 | Data, |
| 147 | |
| 148 | #[default] |
| 149 | Unknown, |
| 150 | } |
| 151 | |
| 152 | |
| 153 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 154 | pub struct CodecParameters { |
| 155 | |
| 156 | pub codec_id: CodecId, |
| 157 | |
| 158 | pub media_type: MediaType, |
| 159 | |
| 160 | pub sample_rate: Option<u32>, |
| 161 | |
| 162 | pub channels: Option<u16>, |
| 163 | |
| 164 | pub width: Option<u32>, |
| 165 | |
| 166 | pub height: Option<u32>, |
| 167 | |
| 168 | pub extradata: Vec<u8>, |
| 169 | } |
| 170 | |
| 171 | impl CodecParameters { |
| 172 | |
| 173 | pub fn audio(codec_id: CodecId) -> CodecParameters { |
| 174 | CodecParameters { |
| 175 | codec_id, |
| 176 | media_type: MediaType::Audio, |
| 177 | ..CodecParameters::default() |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | |
| 182 | pub fn video(codec_id: CodecId) -> CodecParameters { |
| 183 | CodecParameters { |
| 184 | codec_id, |
| 185 | media_type: MediaType::Video, |
| 186 | ..CodecParameters::default() |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | |
| 191 | pub fn subtitle(codec_id: CodecId) -> CodecParameters { |
| 192 | CodecParameters { |
| 193 | codec_id, |
| 194 | media_type: MediaType::Subtitle, |
| 195 | ..CodecParameters::default() |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | |
| 200 | pub fn data(codec_id: CodecId) -> CodecParameters { |
| 201 | CodecParameters { |
| 202 | codec_id, |
| 203 | media_type: MediaType::Data, |
| 204 | ..CodecParameters::default() |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | |
| 210 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 211 | pub struct StreamInfo { |
| 212 | |
| 213 | pub index: u32, |
| 214 | |
| 215 | pub time_base: TimeBase, |
| 216 | |
| 217 | pub duration: Option<i64>, |
| 218 | |
| 219 | pub start_time: Option<i64>, |
| 220 | |
| 221 | pub params: CodecParameters, |
| 222 | } |
| 223 | |
| 224 | |
| 225 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 226 | pub struct VideoFrame { |
| 227 | |
| 228 | pub width: u32, |
| 229 | |
| 230 | pub height: u32, |
| 231 | |
| 232 | pub pts: Option<i64>, |
| 233 | |
| 234 | pub planes: Vec<VideoPlane>, |
| 235 | } |
| 236 | |
| 237 | |
| 238 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 239 | pub struct VideoPlane { |
| 240 | |
| 241 | pub stride: usize, |
| 242 | |
| 243 | pub data: Vec<u8>, |
| 244 | } |
| 245 | |
| 246 | |
| 247 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 248 | pub struct AudioFrame { |
| 249 | |
| 250 | pub samples: u32, |
| 251 | |
| 252 | pub pts: Option<i64>, |
| 253 | |
| 254 | pub data: Vec<Vec<u8>>, |
| 255 | } |
| 256 | |
| 257 | |
| 258 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 259 | pub enum Frame { |
| 260 | |
| 261 | Video(VideoFrame), |
| 262 | |
| 263 | Audio(AudioFrame), |
| 264 | } |
| 265 | |
| 266 | impl From<ec_core::Frame> for Frame { |
| 267 | fn from(frame: ec_core::Frame) -> Frame { |
| 268 | match frame { |
| 269 | ec_core::Frame::Video(video) => Frame::Video(VideoFrame { |
| 270 | width: video.width, |
| 271 | height: video.height, |
| 272 | pts: video.pts.map(|t| t.ticks), |
| 273 | planes: video |
| 274 | .planes |
| 275 | .into_iter() |
| 276 | .map(|plane| VideoPlane { |
| 277 | stride: plane.stride, |
| 278 | data: plane.data.to_vec(), |
| 279 | }) |
| 280 | .collect(), |
| 281 | }), |
| 282 | ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame { |
| 283 | samples: audio.samples as u32, |
| 284 | pts: audio.pts.map(|t| t.ticks), |
| 285 | data: audio.data.iter().map(|buf| buf.to_vec()).collect(), |
| 286 | }), |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | |
| 292 | pub trait Decoder: Send { |
| 293 | |
| 294 | fn codec_id(&self) -> &CodecId; |
| 295 | |
| 296 | |
| 297 | fn send_packet(&mut self, packet: &Packet) -> Result<()>; |
| 298 | |
| 299 | |
| 300 | |
| 301 | fn receive_frame(&mut self) -> Result<Frame>; |
| 302 | } |
| 303 | |
| 304 | |
| 305 | pub trait Muxer: Send { |
| 306 | |
| 307 | fn format_name(&self) -> &str; |
| 308 | |
| 309 | |
| 310 | fn write_header(&mut self) -> Result<()>; |
| 311 | |
| 312 | |
| 313 | fn write_packet(&mut self, packet: &Packet) -> Result<()>; |
| 314 | |
| 315 | |
| 316 | fn write_trailer(&mut self) -> Result<()>; |
| 317 | } |
| 318 | |
| 319 | |
| 320 | pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>; |
| 321 | |
| 322 | |
| 323 | #[derive(Clone)] |
| 324 | pub struct CodecInfo { |
| 325 | |
| 326 | pub id: CodecId, |
| 327 | |
| 328 | pub decoder_factory: Option<DecoderFactory>, |
| 329 | } |
| 330 | |
| 331 | impl CodecInfo { |
| 332 | |
| 333 | pub fn new(id: CodecId) -> CodecInfo { |
| 334 | CodecInfo { |
| 335 | id, |
| 336 | decoder_factory: None, |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | |
| 341 | pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo { |
| 342 | self.decoder_factory = Some(factory); |
| 343 | self |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | #[derive(Clone, Default)] |
| 352 | pub struct CodecRegistry { |
| 353 | by_id: HashMap<CodecId, Vec<CodecInfo>>, |
| 354 | } |
| 355 | |
| 356 | impl CodecRegistry { |
| 357 | |
| 358 | pub fn new() -> CodecRegistry { |
| 359 | CodecRegistry::default() |
| 360 | } |
| 361 | |
| 362 | |
| 363 | pub fn register(&mut self, info: CodecInfo) { |
| 364 | self.by_id.entry(info.id.clone()).or_default().push(info); |
| 365 | } |
| 366 | |
| 367 | |
| 368 | pub fn has_decoder(&self, id: &CodecId) -> bool { |
| 369 | self.by_id |
| 370 | .get(id) |
| 371 | .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some())) |
| 372 | } |
| 373 | |
| 374 | |
| 375 | pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> { |
| 376 | let factory = self |
| 377 | .by_id |
| 378 | .get(¶ms.codec_id) |
| 379 | .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory)) |
| 380 | .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?; |
| 381 | factory(params) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | |
| 386 | |
| 387 | pub struct EcDecoder { |
| 388 | id: CodecId, |
| 389 | inner: Box<dyn ec_core::Decoder>, |
| 390 | } |
| 391 | |
| 392 | impl EcDecoder { |
| 393 | |
| 394 | pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder { |
| 395 | EcDecoder { id, inner } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | impl Decoder for EcDecoder { |
| 400 | fn codec_id(&self) -> &CodecId { |
| 401 | &self.id |
| 402 | } |
| 403 | |
| 404 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 405 | Ok(self.inner.send_packet(packet)?) |
| 406 | } |
| 407 | |
| 408 | fn receive_frame(&mut self) -> Result<Frame> { |
| 409 | Ok(self.inner.receive_frame()?.into()) |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | #[cfg(test)] |
| 414 | mod tests { |
| 415 | use super::*; |
| 416 | |
| 417 | |
| 418 | struct Stub(CodecId); |
| 419 | |
| 420 | impl Decoder for Stub { |
| 421 | fn codec_id(&self) -> &CodecId { |
| 422 | &self.0 |
| 423 | } |
| 424 | |
| 425 | fn send_packet(&mut self, _packet: &Packet) -> Result<()> { |
| 426 | Ok(()) |
| 427 | } |
| 428 | |
| 429 | fn receive_frame(&mut self) -> Result<Frame> { |
| 430 | Err(Error::NeedMore) |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> { |
| 435 | Ok(Box::new(Stub(params.codec_id.clone()))) |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn the_registry_hands_back_what_was_registered_and_names_what_was_not() { |
| 440 | let mut registry = CodecRegistry::new(); |
| 441 | registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub)); |
| 442 | let params = CodecParameters::audio(CodecId::new("ac3")); |
| 443 | let mut decoder = registry.first_decoder(¶ms).unwrap(); |
| 444 | assert_eq!(decoder.codec_id().as_str(), "ac3"); |
| 445 | assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore))); |
| 446 | assert!(registry.has_decoder(&CodecId::new("ac3"))); |
| 447 | |
| 448 | let missing = CodecParameters::audio(CodecId::new("truehd")); |
| 449 | assert!(matches!( |
| 450 | registry.first_decoder(&missing), |
| 451 | Err(Error::CodecNotFound(id)) if id == "truehd" |
| 452 | )); |
| 453 | } |
| 454 | |
| 455 | #[test] |
| 456 | fn frames_and_errors_cross_the_boundary_intact() { |
| 457 | let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4); |
| 458 | let video = |
| 459 | ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap(); |
| 460 | let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else { |
| 461 | panic!("a video frame stays a video frame"); |
| 462 | }; |
| 463 | assert_eq!((frame.width, frame.height), (1, 1)); |
| 464 | assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]); |
| 465 | assert_eq!(frame.planes[0].stride, 4); |
| 466 | |
| 467 | |
| 468 | assert!(matches!( |
| 469 | Error::from(ec_core::Error::NeedMore), |
| 470 | Error::NeedMore |
| 471 | )); |
| 472 | assert_eq!( |
| 473 | Error::from(ec_core::Error::corrupt("torn")).to_string(), |
| 474 | "invalid data: torn" |
| 475 | ); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn a_packet_is_written_the_way_the_replica_writes_one() { |
| 480 | let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]); |
| 481 | assert_eq!(packet.data.len(), 8); |
| 482 | assert_eq!(packet.time_base, TimeBase::new(1, 90_000)); |
| 483 | } |
| 484 | } |