| 1 | extern crate nihav_core; |
| 2 | extern crate nihav_codec_support; |
| 3 | extern crate nihav_registry; |
| 4 | extern crate nihav_allstuff; |
| 5 | |
| 6 | use std::fs::File; |
| 7 | use std::io::{BufReader, Write}; |
| 8 | use nihav_core::io::byteio::{FileReader, ByteReader}; |
| 9 | use nihav_core::frame::*; |
| 10 | use nihav_core::options::*; |
| 11 | use nihav_core::codecs::*; |
| 12 | use nihav_core::demuxers::*; |
| 13 | use nihav_core::muxers::*; |
| 14 | use nihav_core::reorder::*; |
| 15 | use nihav_core::scale::*; |
| 16 | use nihav_registry::detect; |
| 17 | use nihav_registry::register; |
| 18 | use std::env; |
| 19 | use std::time::{Duration, Instant}; |
| 20 | |
| 21 | mod demux; |
| 22 | use crate::demux::*; |
| 23 | mod null; |
| 24 | mod acvt; |
| 25 | use crate::acvt::*; |
| 26 | |
| 27 | fn format_time(ms: u64) -> String { |
| 28 | let s = ms / 1000; |
| 29 | let ds = (ms % 1000) / 100; |
| 30 | let (min, s) = (s / 60, s % 60); |
| 31 | let (h, min) = (min / 60, min % 60); |
| 32 | if h == 0 { |
| 33 | if min == 0 { |
| 34 | format!("{}.{}", s, ds) |
| 35 | } else { |
| 36 | format!("{}:{:02}.{}", min, s, ds) |
| 37 | } |
| 38 | } else { |
| 39 | format!("{}:{:02}:{:02}.{}", h, min, s, ds) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn print_options(name: &str, options: &[NAOptionDefinition]) { |
| 44 | if options.is_empty() { |
| 45 | println!("No custom options."); |
| 46 | } else { |
| 47 | println!("Options for '{}'", name); |
| 48 | for opt in options.iter() { |
| 49 | println!(" {}", opt); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn parse_bitrate(strval: &str) -> Result<u32, ()> { |
| 55 | let mut val = 0; |
| 56 | let mut has_suffix = false; |
| 57 | for ch in strval.chars() { |
| 58 | match ch { |
| 59 | _ if has_suffix => return Err(()), |
| 60 | '0'..='9' => { |
| 61 | if val >= std::u32::MAX / 100 { |
| 62 | return Err(()); |
| 63 | } |
| 64 | val = val * 10 + ch.to_digit(10).unwrap_or(0); |
| 65 | }, |
| 66 | 'k' | 'K' => { |
| 67 | if val >= std::u32::MAX / 1000 { |
| 68 | return Err(()); |
| 69 | } |
| 70 | val *= 1000; |
| 71 | has_suffix = true; |
| 72 | }, |
| 73 | 'm' | 'M' => { |
| 74 | if val >= std::u32::MAX / 1000000 { |
| 75 | return Err(()); |
| 76 | } |
| 77 | val *= 1000000; |
| 78 | has_suffix = true; |
| 79 | }, |
| 80 | _ => return Err(()), |
| 81 | }; |
| 82 | } |
| 83 | Ok(val) |
| 84 | } |
| 85 | |
| 86 | struct OptionArgs { |
| 87 | name: String, |
| 88 | value: Option<String>, |
| 89 | } |
| 90 | |
| 91 | struct InputStreamOptions { |
| 92 | id: u32, |
| 93 | drop: bool, |
| 94 | dec_opts: Vec<OptionArgs>, |
| 95 | } |
| 96 | |
| 97 | struct OutputStreamOptions { |
| 98 | id: u32, |
| 99 | enc_params: EncodeParameters, |
| 100 | enc_name: String, |
| 101 | enc_opts: Vec<OptionArgs>, |
| 102 | } |
| 103 | |
| 104 | enum OutputConvert { |
| 105 | Video(NAScale, NABufferType), |
| 106 | Audio(AudioConverter), |
| 107 | None, |
| 108 | } |
| 109 | |
| 110 | #[allow(clippy::large_enum_variant)] |
| 111 | enum OutputMode { |
| 112 | Drop, |
| 113 | Copy(u32), |
| 114 | Encode(u32, Box<dyn NAEncoder>, OutputConvert), |
| 115 | } |
| 116 | |
| 117 | #[derive(Default)] |
| 118 | #[allow(clippy::type_complexity)] |
| 119 | struct Transcoder { |
| 120 | input_name: String, |
| 121 | input_fmt: Option<String>, |
| 122 | output_name: String, |
| 123 | output_fmt: Option<String>, |
| 124 | demux_opts: Vec<OptionArgs>, |
| 125 | mux_opts: Vec<OptionArgs>, |
| 126 | istr_opts: Vec<InputStreamOptions>, |
| 127 | ostr_opts: Vec<OutputStreamOptions>, |
| 128 | scale_opts: Vec<(String, String)>, |
| 129 | decoders: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>, Box<dyn FrameReorderer>)>>, |
| 130 | encoders: Vec<OutputMode>, |
| 131 | no_video: bool, |
| 132 | no_audio: bool, |
| 133 | start: NATimePoint, |
| 134 | end: NATimePoint, |
| 135 | verbose: u8, |
| 136 | } |
| 137 | |
| 138 | macro_rules! parse_and_apply_options { |
| 139 | ($obj: expr, $in_opts: expr, $name: expr) => { |
| 140 | let mut opts = Vec::with_capacity($in_opts.len()); |
| 141 | let opt_def = $obj.get_supported_options(); |
| 142 | for opt in $in_opts.iter() { |
| 143 | let mut found = false; |
| 144 | for opt_def in opt_def.iter() { |
| 145 | let mut matches = opt.name == opt_def.name; |
| 146 | if !matches && opt.name.starts_with("no") { |
| 147 | let (_, name) = opt.name.split_at(2); |
| 148 | matches = name == opt_def.name; |
| 149 | } |
| 150 | if matches { |
| 151 | let arg = if let Some(ref str) = opt.value { Some(str) } else { None }; |
| 152 | let ret = opt_def.parse(&opt.name, arg); |
| 153 | if let Ok((val, _)) = ret { |
| 154 | opts.push(val); |
| 155 | } else { |
| 156 | println!("invalid option {} for {}", opt.name, $name); |
| 157 | } |
| 158 | found = true; |
| 159 | } |
| 160 | } |
| 161 | if !found { |
| 162 | println!(" ignoring option '{}' for {}", opt.name, $name); |
| 163 | } |
| 164 | } |
| 165 | $obj.set_options(opts.as_slice()); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | impl Transcoder { |
| 170 | fn new() -> Self { Self::default() } |
| 171 | fn parse_istream_options(&mut self, opt0: &str, opt1: &str) -> bool { |
| 172 | let (_, strno) = opt0.split_at(9); |
| 173 | let ret = strno.parse::<u32>(); |
| 174 | if ret.is_err() { return false; } |
| 175 | let streamno = ret.unwrap(); |
| 176 | |
| 177 | let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) { |
| 178 | idx |
| 179 | } else { |
| 180 | self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() }); |
| 181 | self.istr_opts.len() - 1 |
| 182 | }; |
| 183 | let istr = &mut self.istr_opts[sidx]; |
| 184 | |
| 185 | for opt in opt1.split(',') { |
| 186 | let oval: Vec<_> = opt.split('=').collect(); |
| 187 | if oval.len() == 1 { |
| 188 | match oval[0] { |
| 189 | "drop" => { istr.drop = true; }, |
| 190 | _ => { |
| 191 | istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None }); |
| 192 | }, |
| 193 | }; |
| 194 | } else if oval.len() == 2 { |
| 195 | istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) }); |
| 196 | } else { |
| 197 | println!("unrecognized option '{}'", opt); |
| 198 | } |
| 199 | } |
| 200 | true |
| 201 | } |
| 202 | fn parse_ostream_options(&mut self, opt0: &str, opt1: &str, enc_reg: &RegisteredEncoders) -> bool { |
| 203 | let (_, strno) = opt0.split_at(9); |
| 204 | let ret = strno.parse::<u32>(); |
| 205 | if ret.is_err() { return false; } |
| 206 | let streamno = ret.unwrap(); |
| 207 | |
| 208 | let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) { |
| 209 | idx |
| 210 | } else { |
| 211 | self.ostr_opts.push(OutputStreamOptions {id: streamno, enc_name: String::new(), enc_params: EncodeParameters::default(), enc_opts: Vec::new() }); |
| 212 | self.ostr_opts.len() - 1 |
| 213 | }; |
| 214 | let ostr = &mut self.ostr_opts[sidx]; |
| 215 | |
| 216 | for opt in opt1.split(',') { |
| 217 | let oval: Vec<_> = opt.split('=').collect(); |
| 218 | if oval.len() == 1 { |
| 219 | match oval[0] { |
| 220 | "flip" => { |
| 221 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 222 | ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT)); |
| 223 | } |
| 224 | if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format { |
| 225 | vinfo.flipped = true; |
| 226 | } else { |
| 227 | println!("video option for audio stream"); |
| 228 | } |
| 229 | }, |
| 230 | "noflip" => { |
| 231 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 232 | ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT)); |
| 233 | } |
| 234 | if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format { |
| 235 | vinfo.flipped = false; |
| 236 | } else { |
| 237 | println!("video option for audio stream"); |
| 238 | } |
| 239 | }, |
| 240 | _ => { |
| 241 | ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None }); |
| 242 | }, |
| 243 | }; |
| 244 | } else if oval.len() == 2 { |
| 245 | //todo parse encoder options, store, init later |
| 246 | match oval[0] { |
| 247 | "timebase" => { |
| 248 | let mut parts = oval[1].split('/'); |
| 249 | let num = parts.next().unwrap(); |
| 250 | let den = parts.next(); |
| 251 | if let Some(den) = den { |
| 252 | let rnum = num.parse::<u32>(); |
| 253 | let rden = den.parse::<u32>(); |
| 254 | if let (Ok(num), Ok(den)) = (rnum, rden) { |
| 255 | ostr.enc_params.tb_num = num; |
| 256 | ostr.enc_params.tb_den = den; |
| 257 | } else { |
| 258 | println!("invalid timebase value"); |
| 259 | } |
| 260 | } else { |
| 261 | println!("invalid timebase format (should be num/den)"); |
| 262 | } |
| 263 | }, |
| 264 | "encoder" => { |
| 265 | if enc_reg.find_encoder(oval[1]).is_some() { |
| 266 | ostr.enc_name = oval[1].to_string(); |
| 267 | } else { |
| 268 | println!("unknown encoder '{}'", oval[1]); |
| 269 | ostr.enc_name = oval[1].to_string(); |
| 270 | } |
| 271 | }, |
| 272 | "width" => { |
| 273 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 274 | ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT)); |
| 275 | } |
| 276 | if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format { |
| 277 | let ret = oval[1].parse::<usize>(); |
| 278 | if let Ok(val) = ret { |
| 279 | vinfo.width = val; |
| 280 | } else { |
| 281 | println!("invalid width"); |
| 282 | } |
| 283 | } else { |
| 284 | println!("video option for audio stream"); |
| 285 | } |
| 286 | }, |
| 287 | "height" => { |
| 288 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 289 | ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT)); |
| 290 | } |
| 291 | if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format { |
| 292 | let ret = oval[1].parse::<usize>(); |
| 293 | if let Ok(val) = ret { |
| 294 | vinfo.height = val; |
| 295 | } else { |
| 296 | println!("invalid height"); |
| 297 | } |
| 298 | } else { |
| 299 | println!("video option for audio stream"); |
| 300 | } |
| 301 | }, |
| 302 | "pixfmt" => { |
| 303 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 304 | ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT)); |
| 305 | } |
| 306 | if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format { |
| 307 | let ret = oval[1].parse::<NAPixelFormaton>(); |
| 308 | if let Ok(val) = ret { |
| 309 | vinfo.format = val; |
| 310 | } else { |
| 311 | println!("invalid pixel format"); |
| 312 | } |
| 313 | } else { |
| 314 | println!("video option for audio stream"); |
| 315 | } |
| 316 | }, |
| 317 | "srate" => { |
| 318 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 319 | ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0)); |
| 320 | } |
| 321 | if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format { |
| 322 | let ret = oval[1].parse::<u32>(); |
| 323 | if let Ok(val) = ret { |
| 324 | ainfo.sample_rate = val; |
| 325 | } else { |
| 326 | println!("invalid sampling rate"); |
| 327 | } |
| 328 | } else { |
| 329 | println!("audio option for video stream"); |
| 330 | } |
| 331 | }, |
| 332 | "channels" => { |
| 333 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 334 | ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0)); |
| 335 | } |
| 336 | if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format { |
| 337 | let ret = oval[1].parse::<u8>(); |
| 338 | if let Ok(val) = ret { |
| 339 | ainfo.channels = val; |
| 340 | } else { |
| 341 | println!("invalid number of channels"); |
| 342 | } |
| 343 | } else { |
| 344 | println!("audio option for video stream"); |
| 345 | } |
| 346 | }, |
| 347 | "block_len" => { |
| 348 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 349 | ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0)); |
| 350 | } |
| 351 | if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format { |
| 352 | let ret = oval[1].parse::<usize>(); |
| 353 | if let Ok(val) = ret { |
| 354 | ainfo.block_len = val; |
| 355 | } else { |
| 356 | println!("invalid block_length"); |
| 357 | } |
| 358 | } else { |
| 359 | println!("audio option for video stream"); |
| 360 | } |
| 361 | }, |
| 362 | "sfmt" => { |
| 363 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 364 | ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0)); |
| 365 | } |
| 366 | if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format { |
| 367 | let ret = oval[1].parse::<NASoniton>(); |
| 368 | if let Ok(val) = ret { |
| 369 | ainfo.format = val; |
| 370 | } else { |
| 371 | println!("invalid audio format"); |
| 372 | } |
| 373 | } else { |
| 374 | println!("audio option for video stream"); |
| 375 | } |
| 376 | }, |
| 377 | // todo channel map negotiation |
| 378 | /*"chmap" => { |
| 379 | if ostr.enc_params.format == NACodecTypeInfo::None { |
| 380 | ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0)); |
| 381 | } |
| 382 | if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format { |
| 383 | let ret = oval[1].parse::<NAChannelMap>(); |
| 384 | if let Ok(val) = ret { |
| 385 | ainfo.chmap = val; |
| 386 | } else { |
| 387 | println!("invalid channel map"); |
| 388 | } |
| 389 | } else { |
| 390 | println!("audio option for video stream"); |
| 391 | } |
| 392 | },*/ |
| 393 | "bitrate" => { |
| 394 | let ret = parse_bitrate(oval[1]); |
| 395 | if let Ok(val) = ret { |
| 396 | ostr.enc_params.bitrate = val; |
| 397 | } else { |
| 398 | println!("invalid bitrate value"); |
| 399 | } |
| 400 | }, |
| 401 | "quality" => { |
| 402 | let ret = oval[1].parse::<u8>(); |
| 403 | if let Ok(val) = ret { |
| 404 | ostr.enc_params.quality = val; |
| 405 | } else { |
| 406 | println!("invalid quality value"); |
| 407 | } |
| 408 | }, |
| 409 | _ => { |
| 410 | ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) }); |
| 411 | }, |
| 412 | } |
| 413 | } else { |
| 414 | println!("unrecognized option '{}'", opt); |
| 415 | } |
| 416 | } |
| 417 | true |
| 418 | } |
| 419 | fn parse_demuxer_options(&mut self, opts: &str, dmx_reg: &RegisteredDemuxers) -> bool { |
| 420 | for opt in opts.split(',') { |
| 421 | let oval: Vec<_> = opt.split('=').collect(); |
| 422 | if oval.len() == 1 { |
| 423 | self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None }); |
| 424 | } else if oval.len() == 2 { |
| 425 | if oval[0] == "format" { |
| 426 | if dmx_reg.find_demuxer(oval[1]).is_some() { |
| 427 | self.input_fmt = Some(oval[1].to_string()); |
| 428 | } else { |
| 429 | println!("unknown demuxer format '{}'", oval[1]); |
| 430 | } |
| 431 | } else { |
| 432 | self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) }); |
| 433 | } |
| 434 | } else { |
| 435 | println!("unrecognized option '{}'", opt); |
| 436 | } |
| 437 | } |
| 438 | true |
| 439 | } |
| 440 | fn parse_muxer_options(&mut self, opts: &str, mux_reg: &RegisteredMuxers) -> bool { |
| 441 | for opt in opts.split(',') { |
| 442 | let oval: Vec<_> = opt.split('=').collect(); |
| 443 | if oval.len() == 1 { |
| 444 | self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None }); |
| 445 | } else if oval.len() == 2 { |
| 446 | if oval[0] == "format" { |
| 447 | if mux_reg.find_muxer(oval[1]).is_some() { |
| 448 | self.output_fmt = Some(oval[1].to_string()); |
| 449 | } else { |
| 450 | println!("unknown muxer format '{}'", oval[1]); |
| 451 | } |
| 452 | } else { |
| 453 | self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) }); |
| 454 | } |
| 455 | } else { |
| 456 | println!("unrecognized option '{}'", opt); |
| 457 | } |
| 458 | } |
| 459 | true |
| 460 | } |
| 461 | fn parse_scale_options(&mut self, opts: &str) -> bool { |
| 462 | for opt in opts.split(',') { |
| 463 | let oval: Vec<_> = opt.split('=').collect(); |
| 464 | if oval.len() == 1 { |
| 465 | self.scale_opts.push((oval[0].to_string(), "".to_string())); |
| 466 | } else if oval.len() == 2 { |
| 467 | self.scale_opts.push((oval[0].to_string(), oval[1].to_string())); |
| 468 | } else { |
| 469 | println!("unrecognized option '{}'", opt); |
| 470 | return false; |
| 471 | } |
| 472 | } |
| 473 | true |
| 474 | } |
| 475 | fn apply_decoder_options(&self, dec: &mut dyn NADecoder, str_id: u32) { |
| 476 | if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == str_id) { |
| 477 | let dec_opts = dec.get_supported_options(); |
| 478 | if dec_opts.is_empty() { return; } |
| 479 | let name = format!("input stream {}", str_id); |
| 480 | parse_and_apply_options!(dec, &self.istr_opts[str_idx].dec_opts, name); |
| 481 | } |
| 482 | } |
| 483 | fn register_output_stream(&mut self, cname: &str, istr: NAStreamRef, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool { |
| 484 | let out_id = out_sm.get_num_streams() as u32; |
| 485 | if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == (istr.get_num() as u32)) { |
| 486 | if self.istr_opts[str_idx].drop { |
| 487 | self.encoders.push(OutputMode::Drop); |
| 488 | return true; |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | if let Some(str_idx) = self.ostr_opts.iter().position(|str| str.id == out_id) { |
| 493 | let oopts = &mut self.ostr_opts[str_idx]; |
| 494 | if oopts.enc_name.as_str() == "copy" && (cname == "any" || istr.get_info().get_name() == cname) { |
| 495 | out_sm.add_stream_ref(istr); |
| 496 | self.encoders.push(OutputMode::Copy(out_id)); |
| 497 | } else if cname == "any" || oopts.enc_name.as_str() == cname { |
| 498 | let enc_create = enc_reg.find_encoder(oopts.enc_name.as_str()); |
| 499 | if enc_create.is_none() { |
| 500 | println!("encoder '{}' not found", oopts.enc_name.as_str()); |
| 501 | return false; |
| 502 | } |
| 503 | let mut encoder = (enc_create.unwrap())(); |
| 504 | let forced_out = oopts.enc_params.format != NACodecTypeInfo::None; |
| 505 | if oopts.enc_params.format == NACodecTypeInfo::None { |
| 506 | oopts.enc_params.format = istr.get_info().get_properties(); |
| 507 | } |
| 508 | if oopts.enc_params.tb_num == 0 { |
| 509 | oopts.enc_params.tb_num = istr.tb_num; |
| 510 | oopts.enc_params.tb_den = istr.tb_den; |
| 511 | } |
| 512 | let ret_eparams = encoder.negotiate_format(&oopts.enc_params); |
| 513 | if ret_eparams.is_err() { |
| 514 | println!("cannot negotiate encoding parameters"); |
| 515 | return false; |
| 516 | } |
| 517 | let ret_eparams = ret_eparams.unwrap(); |
| 518 | |
| 519 | //todo check for params mismatch |
| 520 | let cvt = match (&oopts.enc_params.format, &ret_eparams.format) { |
| 521 | (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => { |
| 522 | if svinfo == dvinfo && !forced_out { |
| 523 | OutputConvert::None |
| 524 | } else { |
| 525 | let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height }; |
| 526 | let ret = NAScale::new_with_options(ofmt, ofmt, &self.scale_opts); |
| 527 | if ret.is_err() { |
| 528 | println!("cannot create scaler"); |
| 529 | return false; |
| 530 | } |
| 531 | let scaler = ret.unwrap(); |
| 532 | let ret = alloc_video_buffer(*dvinfo, 4); |
| 533 | if ret.is_err() { |
| 534 | println!("cannot create scaler buffer"); |
| 535 | return false; |
| 536 | } |
| 537 | let cvt_buf = ret.unwrap(); |
| 538 | OutputConvert::Video(scaler, cvt_buf) |
| 539 | } |
| 540 | }, |
| 541 | (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => { |
| 542 | if sainfo == dainfo { |
| 543 | OutputConvert::None |
| 544 | } else { |
| 545 | let dchmap = match dainfo.channels { |
| 546 | 1 => NAChannelMap::from_ms_mapping(0x4), |
| 547 | 2 => NAChannelMap::from_ms_mapping(0x3), |
| 548 | _ => { |
| 549 | println!("can't generate default channel map for {} channels", dainfo.channels); |
| 550 | return false; |
| 551 | }, |
| 552 | }; |
| 553 | let acvt = AudioConverter::new(sainfo, dainfo, dchmap); |
| 554 | //todo channelmap |
| 555 | OutputConvert::Audio(acvt) |
| 556 | } |
| 557 | }, |
| 558 | _ => OutputConvert::None, |
| 559 | }; |
| 560 | let ret = encoder.init(out_id, ret_eparams); |
| 561 | if ret.is_err() { |
| 562 | println!("error initialising encoder"); |
| 563 | return false; |
| 564 | } |
| 565 | out_sm.add_stream_ref(ret.unwrap()); |
| 566 | |
| 567 | let name = format!("output stream {}", out_id); |
| 568 | parse_and_apply_options!(encoder, &oopts.enc_opts, name); |
| 569 | |
| 570 | self.encoders.push(OutputMode::Encode(out_id, encoder, cvt)); |
| 571 | } else { |
| 572 | println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name()); |
| 573 | return false; |
| 574 | } |
| 575 | } else if cname == "any" || istr.get_info().get_name() == cname { |
| 576 | out_sm.add_stream_ref(istr); |
| 577 | self.encoders.push(OutputMode::Copy(out_id)); |
| 578 | } else { |
| 579 | let mut oopts = OutputStreamOptions {id: out_id, enc_name: cname.to_owned(), enc_params: EncodeParameters::default(), enc_opts: Vec::new() }; |
| 580 | |
| 581 | let enc_create = enc_reg.find_encoder(cname); |
| 582 | if enc_create.is_none() { |
| 583 | println!("encoder '{}' not found", oopts.enc_name.as_str()); |
| 584 | return false; |
| 585 | } |
| 586 | let mut encoder = (enc_create.unwrap())(); |
| 587 | oopts.enc_params.format = istr.get_info().get_properties(); |
| 588 | oopts.enc_params.tb_num = istr.tb_num; |
| 589 | oopts.enc_params.tb_den = istr.tb_den; |
| 590 | let ret_eparams = encoder.negotiate_format(&oopts.enc_params); |
| 591 | if ret_eparams.is_err() { |
| 592 | println!("cannot negotiate encoding parameters"); |
| 593 | return false; |
| 594 | } |
| 595 | let ret_eparams = ret_eparams.unwrap(); |
| 596 | |
| 597 | //todo check for params mismatch |
| 598 | let cvt = match (&oopts.enc_params.format, &ret_eparams.format) { |
| 599 | (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => { |
| 600 | if svinfo == dvinfo { |
| 601 | OutputConvert::None |
| 602 | } else { |
| 603 | let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height }; |
| 604 | let ret = NAScale::new_with_options(ofmt, ofmt, &self.scale_opts); |
| 605 | if ret.is_err() { |
| 606 | println!("cannot create scaler"); |
| 607 | return false; |
| 608 | } |
| 609 | let scaler = ret.unwrap(); |
| 610 | let ret = alloc_video_buffer(*dvinfo, 4); |
| 611 | if ret.is_err() { |
| 612 | println!("cannot create scaler buffer"); |
| 613 | return false; |
| 614 | } |
| 615 | let cvt_buf = ret.unwrap(); |
| 616 | OutputConvert::Video(scaler, cvt_buf) |
| 617 | } |
| 618 | }, |
| 619 | (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => { |
| 620 | if sainfo == dainfo { |
| 621 | OutputConvert::None |
| 622 | } else { |
| 623 | let dchmap = match dainfo.channels { |
| 624 | 1 => NAChannelMap::from_ms_mapping(0x4), |
| 625 | 2 => NAChannelMap::from_ms_mapping(0x3), |
| 626 | _ => { |
| 627 | println!("can't generate default channel map for {} channels", dainfo.channels); |
| 628 | return false; |
| 629 | }, |
| 630 | }; |
| 631 | //todo channelmap |
| 632 | let acvt = AudioConverter::new(sainfo, dainfo, dchmap); |
| 633 | OutputConvert::Audio(acvt) |
| 634 | } |
| 635 | }, |
| 636 | _ => OutputConvert::None, |
| 637 | }; |
| 638 | let ret = encoder.init(out_id, ret_eparams); |
| 639 | if ret.is_err() { |
| 640 | println!("error initialising encoder"); |
| 641 | return false; |
| 642 | } |
| 643 | out_sm.add_stream_ref(ret.unwrap()); |
| 644 | self.encoders.push(OutputMode::Encode(out_id, encoder, cvt)); |
| 645 | self.ostr_opts.push(oopts); |
| 646 | } |
| 647 | true |
| 648 | } |
| 649 | fn map_single(&mut self, cname: &str, ctype: StreamType, src_sm: &StreamManager, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool { |
| 650 | let mut found_stream = false; |
| 651 | for istr in src_sm.iter() { |
| 652 | if istr.get_media_type() != ctype || found_stream { |
| 653 | self.encoders.push(OutputMode::Drop); |
| 654 | } else { |
| 655 | if !self.register_output_stream(cname, istr, out_sm, enc_reg) { |
| 656 | return false; |
| 657 | } |
| 658 | found_stream = true; |
| 659 | } |
| 660 | } |
| 661 | found_stream |
| 662 | } |
| 663 | fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool { |
| 664 | match mux_caps { |
| 665 | MuxerCapabilities::SingleVideo(cname) => { |
| 666 | if self.no_video { return false; } |
| 667 | self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg) |
| 668 | }, |
| 669 | MuxerCapabilities::SingleAudio(cname) => { |
| 670 | if self.no_audio { return false; } |
| 671 | self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg) |
| 672 | }, |
| 673 | MuxerCapabilities::SingleVideoAndAudio(vname, aname) => { |
| 674 | let mut found_vid = false; |
| 675 | let mut found_aud = false; |
| 676 | for istr in src_sm.iter() { |
| 677 | if istr.get_media_type() == StreamType::Video && !found_vid && !self.no_video { |
| 678 | if !self.register_output_stream(vname, istr, out_sm, enc_reg) { |
| 679 | return false; |
| 680 | } |
| 681 | found_vid = true; |
| 682 | } else if istr.get_media_type() == StreamType::Audio && !found_aud && !self.no_audio { |
| 683 | if !self.register_output_stream(aname, istr, out_sm, enc_reg) { |
| 684 | return false; |
| 685 | } |
| 686 | found_aud = true; |
| 687 | } else { |
| 688 | self.encoders.push(OutputMode::Drop); |
| 689 | } |
| 690 | } |
| 691 | found_vid | found_aud |
| 692 | }, |
| 693 | MuxerCapabilities::OnlyVideo => { |
| 694 | if self.no_video { return false; } |
| 695 | |
| 696 | let mut found_vid = false; |
| 697 | for istr in src_sm.iter() { |
| 698 | if istr.get_media_type() == StreamType::Video && !found_vid { |
| 699 | if !self.register_output_stream("any", istr, out_sm, enc_reg) { |
| 700 | return false; |
| 701 | } |
| 702 | found_vid = true; |
| 703 | } else { |
| 704 | self.encoders.push(OutputMode::Drop); |
| 705 | } |
| 706 | } |
| 707 | found_vid |
| 708 | }, |
| 709 | MuxerCapabilities::OnlyAudio => { |
| 710 | if self.no_audio { return false; } |
| 711 | |
| 712 | let mut found_aud = false; |
| 713 | for istr in src_sm.iter() { |
| 714 | if istr.get_media_type() == StreamType::Audio && !found_aud { |
| 715 | if !self.register_output_stream("any", istr, out_sm, enc_reg) { |
| 716 | return false; |
| 717 | } |
| 718 | found_aud = true; |
| 719 | } else { |
| 720 | self.encoders.push(OutputMode::Drop); |
| 721 | } |
| 722 | } |
| 723 | found_aud |
| 724 | }, |
| 725 | MuxerCapabilities::Universal => { |
| 726 | for istr in src_sm.iter() { |
| 727 | if (istr.get_media_type() == StreamType::Video && self.no_video) || |
| 728 | (istr.get_media_type() == StreamType::Audio && self.no_audio) { |
| 729 | self.encoders.push(OutputMode::Drop); |
| 730 | continue; |
| 731 | } |
| 732 | if !self.register_output_stream("any", istr, out_sm, enc_reg) { |
| 733 | return false; |
| 734 | } |
| 735 | } |
| 736 | true |
| 737 | }, |
| 738 | } |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | fn encode_frame(dst_id: u32, encoder: &mut Box<dyn NAEncoder>, cvt: &mut OutputConvert, frm: NAFrameRef, scale_opts: &[(String, String)]) -> bool { |
| 743 | let buf = frm.get_buffer(); |
| 744 | let cbuf = if let NABufferType::None = buf { |
| 745 | if (encoder.get_capabilities() & ENC_CAPS_SKIPFRAME) == 0 { |
| 746 | println!("encoder does not support skip frames, skipping"); |
| 747 | return true; |
| 748 | } |
| 749 | buf |
| 750 | } else { |
| 751 | match cvt { |
| 752 | OutputConvert::None => buf, |
| 753 | OutputConvert::Video(ref mut scaler, ref mut dbuf) => { |
| 754 | let cur_ifmt = get_scale_fmt_from_pic(&buf); |
| 755 | let last_ifmt = scaler.get_in_fmt(); |
| 756 | if cur_ifmt != last_ifmt { |
| 757 | let ofmt = scaler.get_out_fmt(); |
| 758 | let ret = NAScale::new_with_options(cur_ifmt, ofmt, scale_opts); |
| 759 | if ret.is_err() { |
| 760 | println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt); |
| 761 | return false; |
| 762 | } |
| 763 | *scaler = ret.unwrap(); |
| 764 | } |
| 765 | let ret = scaler.convert(&buf, dbuf); |
| 766 | if ret.is_err() { |
| 767 | println!("error converting frame for encoding"); |
| 768 | return false; |
| 769 | } |
| 770 | dbuf.clone() |
| 771 | }, |
| 772 | OutputConvert::Audio(ref mut acvt) => { |
| 773 | if !acvt.queue_frame(buf, frm.get_time_information()) { |
| 774 | println!("error converting audio for stream {}", dst_id); |
| 775 | return false; |
| 776 | } |
| 777 | return true; |
| 778 | }, |
| 779 | } |
| 780 | }; |
| 781 | let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf); |
| 782 | encoder.encode(&cfrm).unwrap(); |
| 783 | true |
| 784 | } |
| 785 | |
| 786 | macro_rules! next_arg { |
| 787 | ($args: expr, $arg_idx: expr) => { |
| 788 | if $arg_idx + 1 >= $args.len() { |
| 789 | println!("codec name is required"); |
| 790 | } |
| 791 | $arg_idx += 1; |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[allow(clippy::single_match)] |
| 796 | fn main() { |
| 797 | let args: Vec<_> = env::args().collect(); |
| 798 | |
| 799 | if args.len() == 1 { |
| 800 | println!("usage: nihav-encoder [options] --input inputfile --output outputfile"); |
| 801 | println!(" use nihav-encoder --help to list all available options"); |
| 802 | return; |
| 803 | } |
| 804 | if args.len() == 2 && (args[1] == "--help" || args[1] == "-h") { |
| 805 | println!("usage: nihav-encoder [options] --input inputfile --output outputfile"); |
| 806 | println!(" query options:"); |
| 807 | println!(" --list-{{decoders,encoders,demuxers,muxers}} - lists all available decoders/encoders/demuxers/muxers"); |
| 808 | println!(" --query-{{decoder,encoder,demuxer,muxer}}-options name - lists all options recognized by that decoder/encoder/demuxer/muxer"); |
| 809 | println!(" processing options:"); |
| 810 | println!(" --verbose - show time for the currently processed input"); |
| 811 | println!(" --input inputfile - set input file"); |
| 812 | println!(" --input-format fmt - force input format"); |
| 813 | println!(" --demuxer-options options - set input demuxer options"); |
| 814 | println!(" --scale-options options - set scaler options"); |
| 815 | println!(" --output outputfile - set output file"); |
| 816 | println!(" --output-format fmt - force output format"); |
| 817 | println!(" --muxer-options options - set output muxer options"); |
| 818 | println!(" --no-audio - do not decode audio streams"); |
| 819 | println!(" --no-video - do not decode video streams"); |
| 820 | println!(" --start starttime - start decoding from given position"); |
| 821 | println!(" --end endtime - end decoding at given position"); |
| 822 | println!(" --istreamX options - set options for input stream X"); |
| 823 | println!(" --ostreamX options - set options for output stream X"); |
| 824 | println!(); |
| 825 | println!(" (de)muxer and stream options are passed as comma-separated list e.g. --ostream0 width=320,height=240,flip"); |
| 826 | return; |
| 827 | } |
| 828 | |
| 829 | let full_reg = FullRegister::new(); |
| 830 | |
| 831 | let mut transcoder = Transcoder::new(); |
| 832 | |
| 833 | let mut arg_idx = 1; |
| 834 | let mut printed_info = false; |
| 835 | while arg_idx < args.len() { |
| 836 | match args[arg_idx].as_str() { |
| 837 | "--list-decoders" => { |
| 838 | if full_reg.dec_reg.iter().len() > 0 { |
| 839 | println!("Registered decoders:"); |
| 840 | for dec in full_reg.dec_reg.iter() { |
| 841 | let cdesc = register::get_codec_description(dec.name); |
| 842 | let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" }; |
| 843 | println!(" {} ({})", dec.name, full_name); |
| 844 | } |
| 845 | } else { |
| 846 | println!("No registered decoders."); |
| 847 | } |
| 848 | printed_info = true; |
| 849 | }, |
| 850 | "--list-encoders" => { |
| 851 | if full_reg.enc_reg.iter().len() > 0 { |
| 852 | println!("Registered encoders:"); |
| 853 | for enc in full_reg.enc_reg.iter() { |
| 854 | let cdesc = register::get_codec_description(enc.name); |
| 855 | let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" }; |
| 856 | println!(" {} ({})", enc.name, full_name); |
| 857 | } |
| 858 | } else { |
| 859 | println!("No registered encoders."); |
| 860 | } |
| 861 | printed_info = true; |
| 862 | }, |
| 863 | "--list-demuxers" => { |
| 864 | print!("Registered demuxers:"); |
| 865 | for dmx in full_reg.dmx_reg.iter() { |
| 866 | print!(" {}", dmx.get_name()); |
| 867 | } |
| 868 | println!(); |
| 869 | printed_info = true; |
| 870 | }, |
| 871 | "--list-muxers" => { |
| 872 | print!("Registered muxers:"); |
| 873 | for mux in full_reg.mux_reg.iter() { |
| 874 | print!(" {}", mux.get_name()); |
| 875 | } |
| 876 | println!(); |
| 877 | printed_info = true; |
| 878 | }, |
| 879 | "--query-decoder-options" => { |
| 880 | next_arg!(args, arg_idx); |
| 881 | let cname = args[arg_idx].as_str(); |
| 882 | if let Some(decfunc) = full_reg.dec_reg.find_decoder(cname) { |
| 883 | let dec = (decfunc)(); |
| 884 | let opts = dec.get_supported_options(); |
| 885 | print_options(cname, opts); |
| 886 | } else { |
| 887 | println!("codec {} is not found", cname); |
| 888 | } |
| 889 | printed_info = true; |
| 890 | }, |
| 891 | "--query-demuxer-options" => { |
| 892 | next_arg!(args, arg_idx); |
| 893 | let dname = args[arg_idx].as_str(); |
| 894 | let mut mr = MemoryReader::new_read(&[]); |
| 895 | let mut br = ByteReader::new(&mut mr); |
| 896 | if let Some(dmx_creator) = full_reg.dmx_reg.find_demuxer(dname) { |
| 897 | let dmx = dmx_creator.new_demuxer(&mut br); |
| 898 | let opts = dmx.get_supported_options(); |
| 899 | print_options(dname, opts); |
| 900 | } else { |
| 901 | println!("demuxer {} is not found", dname); |
| 902 | } |
| 903 | printed_info = true; |
| 904 | }, |
| 905 | "--query-encoder-options" => { |
| 906 | next_arg!(args, arg_idx); |
| 907 | let cname = args[arg_idx].as_str(); |
| 908 | if let Some(encfunc) = full_reg.enc_reg.find_encoder(cname) { |
| 909 | let enc = (encfunc)(); |
| 910 | let opts = enc.get_supported_options(); |
| 911 | print_options(cname, opts); |
| 912 | } else { |
| 913 | println!("codec {} is not found", cname); |
| 914 | } |
| 915 | printed_info = true; |
| 916 | }, |
| 917 | "--query-muxer-options" => { |
| 918 | next_arg!(args, arg_idx); |
| 919 | let name = args[arg_idx].as_str(); |
| 920 | let mut data = []; |
| 921 | let mut mw = MemoryWriter::new_write(&mut data); |
| 922 | let mut bw = ByteWriter::new(&mut mw); |
| 923 | if let Some(mux_creator) = full_reg.mux_reg.find_muxer(name) { |
| 924 | let mux = mux_creator.new_muxer(&mut bw); |
| 925 | let opts = mux.get_supported_options(); |
| 926 | print_options(name, opts); |
| 927 | } else { |
| 928 | println!("muxer {} is not found", name); |
| 929 | } |
| 930 | printed_info = true; |
| 931 | }, |
| 932 | "--input" | "-i" => { |
| 933 | next_arg!(args, arg_idx); |
| 934 | transcoder.input_name = args[arg_idx].clone(); |
| 935 | }, |
| 936 | "--input-format" => { |
| 937 | next_arg!(args, arg_idx); |
| 938 | transcoder.input_fmt = Some(args[arg_idx].clone()); |
| 939 | }, |
| 940 | "--output" | "-o" => { |
| 941 | next_arg!(args, arg_idx); |
| 942 | transcoder.output_name = args[arg_idx].clone(); |
| 943 | }, |
| 944 | "--output-format" => { |
| 945 | next_arg!(args, arg_idx); |
| 946 | transcoder.output_fmt = Some(args[arg_idx].clone()); |
| 947 | }, |
| 948 | "--demuxer-options" => { |
| 949 | next_arg!(args, arg_idx); |
| 950 | if !transcoder.parse_demuxer_options(&args[arg_idx], &full_reg.dmx_reg) { |
| 951 | println!("invalid demuxer option syntax"); |
| 952 | return; |
| 953 | } |
| 954 | }, |
| 955 | "--scale-options" => { |
| 956 | next_arg!(args, arg_idx); |
| 957 | if !transcoder.parse_scale_options(&args[arg_idx]) { |
| 958 | println!("invalid scale option syntax"); |
| 959 | return; |
| 960 | } |
| 961 | }, |
| 962 | "--no-video" | "-vn" => { |
| 963 | transcoder.no_video = true; |
| 964 | }, |
| 965 | "--no-audio" | "-an" => { |
| 966 | transcoder.no_audio = true; |
| 967 | }, |
| 968 | "--start" => { |
| 969 | next_arg!(args, arg_idx); |
| 970 | let ret = args[arg_idx].parse::<NATimePoint>(); |
| 971 | if let Ok(val) = ret { |
| 972 | transcoder.start = val; |
| 973 | } else { |
| 974 | println!("invalid start time"); |
| 975 | return; |
| 976 | } |
| 977 | }, |
| 978 | "--end" => { |
| 979 | next_arg!(args, arg_idx); |
| 980 | let ret = args[arg_idx].parse::<NATimePoint>(); |
| 981 | if let Ok(val) = ret { |
| 982 | transcoder.end = val; |
| 983 | } else { |
| 984 | println!("invalid end time"); |
| 985 | return; |
| 986 | } |
| 987 | }, |
| 988 | "--muxer-options" => { |
| 989 | next_arg!(args, arg_idx); |
| 990 | if !transcoder.parse_muxer_options(&args[arg_idx], &full_reg.mux_reg) { |
| 991 | println!("invalid muxer option syntax"); |
| 992 | return; |
| 993 | } |
| 994 | }, |
| 995 | "--verbose" | "-v" => transcoder.verbose = 1, |
| 996 | "-vv" => transcoder.verbose = 2, |
| 997 | "-v-" => transcoder.verbose = 0, |
| 998 | _ => { |
| 999 | if args[arg_idx].starts_with("--istream") { |
| 1000 | let opt0 = &args[arg_idx]; |
| 1001 | next_arg!(args, arg_idx); |
| 1002 | if !transcoder.parse_istream_options(opt0, &args[arg_idx]) { |
| 1003 | println!("invalid input stream option syntax"); |
| 1004 | return; |
| 1005 | } |
| 1006 | } else if args[arg_idx].starts_with("--ostream") { |
| 1007 | let opt0 = &args[arg_idx]; |
| 1008 | next_arg!(args, arg_idx); |
| 1009 | if !transcoder.parse_ostream_options(opt0, &args[arg_idx], &full_reg.enc_reg) { |
| 1010 | println!("invalid output stream option syntax"); |
| 1011 | return; |
| 1012 | } |
| 1013 | } else if args[arg_idx].starts_with("--") { |
| 1014 | println!("unknown option"); |
| 1015 | } else { |
| 1016 | println!("unrecognized argument"); |
| 1017 | } |
| 1018 | }, |
| 1019 | }; |
| 1020 | arg_idx += 1; |
| 1021 | } |
| 1022 | |
| 1023 | if printed_info { |
| 1024 | return; |
| 1025 | } |
| 1026 | |
| 1027 | if transcoder.input_name.is_empty() { |
| 1028 | println!("no input name provided"); |
| 1029 | return; |
| 1030 | } |
| 1031 | if transcoder.output_name.is_empty() { |
| 1032 | println!("no output name provided"); |
| 1033 | return; |
| 1034 | } |
| 1035 | |
| 1036 | let res = File::open(transcoder.input_name.as_str()); |
| 1037 | if res.is_err() { |
| 1038 | println!("error opening input"); |
| 1039 | return; |
| 1040 | } |
| 1041 | let file = res.unwrap(); |
| 1042 | let file = BufReader::new(file); |
| 1043 | let mut fr = FileReader::new_read(file); |
| 1044 | let mut br = ByteReader::new(&mut fr); |
| 1045 | let (is_raw, start, end) = if transcoder.input_fmt.is_none() { |
| 1046 | detect_tags(&mut br) |
| 1047 | } else { |
| 1048 | (false, 0, None) |
| 1049 | }; |
| 1050 | |
| 1051 | let mut nfr: Box<dyn ByteIO>; |
| 1052 | if start != 0 || end.is_some() { |
| 1053 | let file = fr.finish(); |
| 1054 | nfr = Box::new(BoundedFileReader::new_read(file, start, end).unwrap()); |
| 1055 | } else { |
| 1056 | nfr = Box::new(fr); |
| 1057 | } |
| 1058 | let mut br = ByteReader::new(nfr.as_mut()); |
| 1059 | |
| 1060 | let mut dmx = DemuxerObject::create(&mut br, &full_reg, transcoder.input_name.as_str(), &transcoder.input_fmt, is_raw); |
| 1061 | if dmx.is_none() { |
| 1062 | println!("cannot find demuxer for '{}'", transcoder.input_name.as_str()); |
| 1063 | return; |
| 1064 | } |
| 1065 | let duration = dmx.get_duration(); |
| 1066 | let duration_string = if duration != 0 { format_time(duration) } else { String::new() }; |
| 1067 | |
| 1068 | parse_and_apply_options!(dmx, &transcoder.demux_opts, "input"); |
| 1069 | for i in 0..dmx.get_num_streams() { |
| 1070 | let s = dmx.get_stream(i).unwrap(); |
| 1071 | let info = s.get_info(); |
| 1072 | let decfunc = full_reg.dec_reg.find_decoder(info.get_name()); |
| 1073 | println!("stream {} - {} {}", i, s, info.get_name()); |
| 1074 | let str_id = s.get_num() as u32; |
| 1075 | if let Some(create_dec) = decfunc { |
| 1076 | let mut dec = (create_dec)(); |
| 1077 | let mut dsupp = Box::new(NADecoderSupport::new()); |
| 1078 | let ret = dec.init(&mut dsupp, info.clone()); |
| 1079 | if ret.is_err() { |
| 1080 | println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id); |
| 1081 | return; |
| 1082 | } |
| 1083 | transcoder.apply_decoder_options(dec.as_mut(), str_id); |
| 1084 | let desc = register::get_codec_description(info.get_name()); |
| 1085 | let has_b = if let Some(desc) = desc { |
| 1086 | desc.has_reorder() |
| 1087 | } else { |
| 1088 | println!("No codec description found, using B-frame reorderer."); |
| 1089 | true |
| 1090 | }; |
| 1091 | let reord: Box<dyn FrameReorderer> = if has_b { Box::new(IPBReorderer::new()) } else { Box::new(NoReorderer::new()) }; |
| 1092 | transcoder.decoders.push(Some((dsupp, dec, reord))); |
| 1093 | } else { |
| 1094 | println!("No decoder for stream {} ({}) is found", str_id, info.get_name()); |
| 1095 | transcoder.decoders.push(None); |
| 1096 | } |
| 1097 | } |
| 1098 | if transcoder.start != NATimePoint::None { |
| 1099 | let ret = dmx.seek(transcoder.start); |
| 1100 | if ret.is_err() { |
| 1101 | println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap()); |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | let output_fmt = if let Some(ref str) = transcoder.output_fmt { |
| 1106 | str |
| 1107 | } else if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) { |
| 1108 | str |
| 1109 | } else { |
| 1110 | println!("Cannot guess muxer for output"); |
| 1111 | return; |
| 1112 | }; |
| 1113 | let ret = full_reg.mux_reg.find_muxer(output_fmt); |
| 1114 | let ofmt = output_fmt.to_string(); |
| 1115 | |
| 1116 | if ret.is_none() { |
| 1117 | println!("cannot find muxer '{}'", output_fmt); |
| 1118 | } |
| 1119 | let mux_creator = ret.unwrap(); |
| 1120 | |
| 1121 | let mux_caps = mux_creator.get_capabilities(); |
| 1122 | let mut out_sm = StreamManager::new(); |
| 1123 | if !transcoder.negotiate_stream_map(dmx.get_stream_manager(), mux_caps, &mut out_sm, &full_reg.enc_reg) { |
| 1124 | println!("cannot determine stream map"); |
| 1125 | return; |
| 1126 | } |
| 1127 | |
| 1128 | let ret = File::create(transcoder.output_name.as_str()); |
| 1129 | if ret.is_err() { |
| 1130 | println!("cannot open output file"); |
| 1131 | return; |
| 1132 | } |
| 1133 | let mut fw = FileWriter::new_write(ret.unwrap()); |
| 1134 | let mut bw = ByteWriter::new(&mut fw); |
| 1135 | let ret = create_muxer(mux_creator, out_sm, &mut bw); |
| 1136 | if let Err(err) = ret { |
| 1137 | println!("cannot create muxer instance {:?}", err); |
| 1138 | return; |
| 1139 | } |
| 1140 | let mut mux = ret.unwrap(); |
| 1141 | parse_and_apply_options!(mux, &transcoder.mux_opts, "output"); |
| 1142 | |
| 1143 | println!("Output {} muxer {}", transcoder.output_name, ofmt); |
| 1144 | for ostr in mux.get_streams() { |
| 1145 | println!(" #{}: {} {}", ostr.get_num(), ostr, ostr.get_info().get_name()); |
| 1146 | } |
| 1147 | |
| 1148 | let mut time = Instant::now(); |
| 1149 | let show_interval = Duration::from_millis(100); |
| 1150 | let mut adata_size = 0; |
| 1151 | let mut vdata_size = 0; |
| 1152 | 'main_loop: loop { |
| 1153 | let pktres = dmx.get_frame(); |
| 1154 | if let Err(DemuxerError::EOF) = pktres { break; } |
| 1155 | if pktres.is_err() { |
| 1156 | println!("demuxing error"); |
| 1157 | break; |
| 1158 | } |
| 1159 | let mut pkt = pktres.unwrap(); |
| 1160 | if transcoder.start != NATimePoint::None && pkt.ts.less_than(transcoder.start) { continue; } |
| 1161 | let src_id = pkt.get_stream().get_num(); |
| 1162 | if transcoder.verbose > 0 && time.elapsed() >= show_interval { |
| 1163 | if let Some(pts) = pkt.get_pts() { |
| 1164 | let cur_time = format_time(NATimeInfo::ts_to_time(pts, 1000, pkt.ts.tb_num, pkt.ts.tb_den)); |
| 1165 | print!(" {}", cur_time); |
| 1166 | } else { |
| 1167 | print!(" ???"); |
| 1168 | } |
| 1169 | if !duration_string.is_empty() { |
| 1170 | print!(" / {}", duration_string); |
| 1171 | } |
| 1172 | if transcoder.verbose > 1 { |
| 1173 | print!(" data sizes V: {} A: {}", vdata_size, adata_size); |
| 1174 | } |
| 1175 | print!("\r"); |
| 1176 | std::io::stdout().flush().unwrap(); |
| 1177 | time = Instant::now(); |
| 1178 | } |
| 1179 | match transcoder.encoders[src_id] { |
| 1180 | OutputMode::Drop => {}, |
| 1181 | OutputMode::Copy(dst_id) => { |
| 1182 | let dstr = mux.get_stream(dst_id as usize).unwrap(); |
| 1183 | pkt.reassign(dstr, pkt.get_time_information()); |
| 1184 | if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; } |
| 1185 | let pkt_size = pkt.get_buffer().len(); |
| 1186 | match pkt.get_stream().get_media_type() { |
| 1187 | StreamType::Video => { vdata_size += pkt_size; }, |
| 1188 | StreamType::Audio => { adata_size += pkt_size; }, |
| 1189 | _ => {}, |
| 1190 | }; |
| 1191 | if mux.mux_frame(pkt).is_err() { |
| 1192 | println!("error muxing packet"); |
| 1193 | break; |
| 1194 | } |
| 1195 | }, |
| 1196 | OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) => { |
| 1197 | if let Some((ref mut dsupp, ref mut decoder, ref mut reorderer)) = transcoder.decoders[src_id] { |
| 1198 | let ret = decoder.decode(dsupp, &pkt); |
| 1199 | if let (true, Err(DecoderError::MissingReference)) = (transcoder.start != NATimePoint::None, &ret) { |
| 1200 | continue; |
| 1201 | } |
| 1202 | if ret.is_err() { |
| 1203 | println!("error decoding stream {}", src_id); |
| 1204 | break; |
| 1205 | } |
| 1206 | let frm = ret.unwrap(); |
| 1207 | let tinfo = frm.get_info(); |
| 1208 | reorderer.add_frame(frm); |
| 1209 | while let Some(frm) = reorderer.get_frame() { |
| 1210 | if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) { |
| 1211 | break; |
| 1212 | } |
| 1213 | while let Ok(Some(pkt)) = encoder.get_packet() { |
| 1214 | if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; } |
| 1215 | let pkt_size = pkt.get_buffer().len(); |
| 1216 | match pkt.get_stream().get_media_type() { |
| 1217 | StreamType::Video => { vdata_size += pkt_size; }, |
| 1218 | StreamType::Audio => { adata_size += pkt_size; }, |
| 1219 | _ => {}, |
| 1220 | }; |
| 1221 | mux.mux_frame(pkt).unwrap(); |
| 1222 | } |
| 1223 | } |
| 1224 | if let OutputConvert::Audio(ref mut acvt) = cvt { |
| 1225 | while let Some(ofrm) = acvt.get_frame(tinfo.clone()) { |
| 1226 | if encoder.encode(&ofrm).is_err() { |
| 1227 | break; |
| 1228 | } |
| 1229 | while let Ok(Some(pkt)) = encoder.get_packet() { |
| 1230 | if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; } |
| 1231 | let pkt_size = pkt.get_buffer().len(); |
| 1232 | adata_size += pkt_size; |
| 1233 | mux.mux_frame(pkt).unwrap(); |
| 1234 | } |
| 1235 | } |
| 1236 | } |
| 1237 | } else { |
| 1238 | println!("no decoder for stream {}", src_id); |
| 1239 | break; |
| 1240 | } |
| 1241 | }, |
| 1242 | }; |
| 1243 | } |
| 1244 | 'reord_flush_loop: for str in dmx.get_streams() { |
| 1245 | let src_id = str.get_num(); |
| 1246 | if let OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) = transcoder.encoders[src_id] { |
| 1247 | if let Some((_, _, ref mut reorderer)) = transcoder.decoders[src_id] { |
| 1248 | while let Some(frm) = reorderer.get_last_frames() { |
| 1249 | if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) { |
| 1250 | break; |
| 1251 | } |
| 1252 | while let Ok(Some(pkt)) = encoder.get_packet() { |
| 1253 | if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'reord_flush_loop; } |
| 1254 | mux.mux_frame(pkt).unwrap(); |
| 1255 | } |
| 1256 | } |
| 1257 | } |
| 1258 | } |
| 1259 | } |
| 1260 | 'flush_loop: for enc in transcoder.encoders.iter_mut() { |
| 1261 | match enc { |
| 1262 | OutputMode::Encode(str_id, ref mut encoder, _) => { |
| 1263 | let ret = encoder.flush(); |
| 1264 | if ret.is_err() { |
| 1265 | println!("error flushing encoder for stream {}", str_id); |
| 1266 | break; |
| 1267 | } else { |
| 1268 | while let Ok(Some(pkt)) = encoder.get_packet() { |
| 1269 | if mux.mux_frame(pkt).is_err() { |
| 1270 | println!("error muxing packet"); |
| 1271 | break 'flush_loop; |
| 1272 | } |
| 1273 | } |
| 1274 | } |
| 1275 | }, |
| 1276 | _ => {}, |
| 1277 | }; |
| 1278 | } |
| 1279 | if transcoder.verbose > 0 { |
| 1280 | println!(); |
| 1281 | } |
| 1282 | |
| 1283 | let ret = mux.end(); |
| 1284 | if ret.is_err() { |
| 1285 | println!("error at finalising muxing"); |
| 1286 | } |
| 1287 | } |