1 extern crate nihav_core;
2 extern crate nihav_codec_support;
3 extern crate nihav_registry;
4 extern crate nihav_allstuff;
7 use nihav_core::io::byteio::{FileReader, ByteReader};
8 use nihav_core::frame::*;
9 use nihav_core::options::*;
10 use nihav_core::codecs::*;
11 use nihav_core::demuxers::*;
12 use nihav_core::muxers::*;
13 use nihav_core::reorder::*;
14 use nihav_core::scale::*;
15 use nihav_core::soundcvt::*;
16 use nihav_registry::detect;
17 use nihav_registry::register;
18 use nihav_allstuff::*;
24 fn print_options(name: &str, options: &[NAOptionDefinition]) {
25 if options.is_empty() {
26 println!("No custom options.");
28 println!("Options for '{}'", name);
29 for opt in options.iter() {
37 value: Option<String>,
40 struct InputStreamOptions {
43 dec_opts: Vec<OptionArgs>,
46 struct OutputStreamOptions {
48 enc_params: EncodeParameters,
50 enc_opts: Vec<OptionArgs>,
54 Video(NAScale, NABufferType),
55 Audio(NAAudioInfo, NAChannelMap),
59 #[allow(clippy::large_enum_variant)]
63 Encode(u32, Box<dyn NAEncoder>, OutputConvert),
67 #[allow(clippy::type_complexity)]
70 input_fmt: Option<String>,
72 output_fmt: Option<String>,
73 demux_opts: Vec<OptionArgs>,
74 mux_opts: Vec<OptionArgs>,
75 istr_opts: Vec<InputStreamOptions>,
76 ostr_opts: Vec<OutputStreamOptions>,
77 decoders: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>, Box<dyn FrameReorderer>)>>,
78 encoders: Vec<OutputMode>,
85 macro_rules! parse_and_apply_options {
86 ($obj: expr, $in_opts: expr, $name: expr) => {
87 let mut opts = Vec::with_capacity($in_opts.len());
88 let opt_def = $obj.get_supported_options();
89 for opt in $in_opts.iter() {
90 let mut found = false;
91 for opt_def in opt_def.iter() {
92 if opt.name == opt_def.name {
93 let arg = if let Some(ref str) = opt.value { Some(str) } else { None };
94 let ret = opt_def.parse(&opt.name, arg);
95 if let Ok((val, _)) = ret {
98 println!("invalid option {} for {}", opt.name, $name);
104 println!(" ignoring option '{}' for {}", opt.name, $name);
107 $obj.set_options(opts.as_slice());
112 fn new() -> Self { Self::default() }
113 fn parse_istream_options(&mut self, opt0: &str, opt1: &str) -> bool {
114 let (_, strno) = opt0.split_at(9);
115 let ret = strno.parse::<u32>();
116 if ret.is_err() { return false; }
117 let streamno = ret.unwrap();
119 let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) {
122 self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() });
123 self.istr_opts.len() - 1
125 let istr = &mut self.istr_opts[sidx];
127 for opt in opt1.split(',') {
128 let oval: Vec<_> = opt.split('=').collect();
131 "drop" => { istr.drop = true; },
133 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
136 } else if oval.len() == 2 {
137 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
139 println!("unrecognized option '{}'", opt);
144 fn parse_ostream_options(&mut self, opt0: &str, opt1: &str, enc_reg: &RegisteredEncoders) -> bool {
145 let (_, strno) = opt0.split_at(9);
146 let ret = strno.parse::<u32>();
147 if ret.is_err() { return false; }
148 let streamno = ret.unwrap();
150 let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) {
153 self.ostr_opts.push(OutputStreamOptions {id: streamno, enc_name: String::new(), enc_params: EncodeParameters::default(), enc_opts: Vec::new() });
154 self.ostr_opts.len() - 1
156 let ostr = &mut self.ostr_opts[sidx];
158 for opt in opt1.split(',') {
159 let oval: Vec<_> = opt.split('=').collect();
163 if ostr.enc_params.format == NACodecTypeInfo::None {
164 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
166 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
167 vinfo.flipped = true;
169 println!("video option for audio stream");
173 if ostr.enc_params.format == NACodecTypeInfo::None {
174 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
176 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
177 vinfo.flipped = false;
179 println!("video option for audio stream");
183 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
186 } else if oval.len() == 2 {
187 //todo parse encoder options, store, init later
190 let mut parts = oval[1].split('/');
191 let num = parts.next().unwrap();
192 let den = parts.next();
193 if let Some(den) = den {
194 let rnum = num.parse::<u32>();
195 let rden = den.parse::<u32>();
196 if let (Ok(num), Ok(den)) = (rnum, rden) {
197 ostr.enc_params.tb_num = num;
198 ostr.enc_params.tb_den = den;
200 println!("invalid timebase value");
203 println!("invalid timebase format (should be num/den)");
207 if enc_reg.find_encoder(oval[1]).is_some() {
208 ostr.enc_name = oval[1].to_string();
210 println!("unknown encoder '{}'", oval[1]);
211 ostr.enc_name = oval[1].to_string();
215 if ostr.enc_params.format == NACodecTypeInfo::None {
216 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
218 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
219 let ret = oval[1].parse::<usize>();
220 if let Ok(val) = ret {
223 println!("invalid width");
226 println!("video option for audio stream");
230 if ostr.enc_params.format == NACodecTypeInfo::None {
231 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
233 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
234 let ret = oval[1].parse::<usize>();
235 if let Ok(val) = ret {
238 println!("invalid height");
241 println!("video option for audio stream");
245 if ostr.enc_params.format == NACodecTypeInfo::None {
246 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
248 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
249 let ret = oval[1].parse::<NAPixelFormaton>();
250 if let Ok(val) = ret {
253 println!("invalid pixel format");
256 println!("video option for audio stream");
260 if ostr.enc_params.format == NACodecTypeInfo::None {
261 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
263 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
264 let ret = oval[1].parse::<u32>();
265 if let Ok(val) = ret {
266 ainfo.sample_rate = val;
268 println!("invalid sampling rate");
271 println!("audio option for video stream");
275 if ostr.enc_params.format == NACodecTypeInfo::None {
276 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
278 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
279 let ret = oval[1].parse::<u8>();
280 if let Ok(val) = ret {
281 ainfo.channels = val;
283 println!("invalid number of channels");
286 println!("audio option for video stream");
290 if ostr.enc_params.format == NACodecTypeInfo::None {
291 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
293 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
294 let ret = oval[1].parse::<usize>();
295 if let Ok(val) = ret {
296 ainfo.block_len = val;
298 println!("invalid block_length");
301 println!("audio option for video stream");
305 if ostr.enc_params.format == NACodecTypeInfo::None {
306 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
308 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
309 let ret = oval[1].parse::<NASoniton>();
310 if let Ok(val) = ret {
313 println!("invalid audio format");
316 println!("audio option for video stream");
319 // todo channel map negotiation
321 if ostr.enc_params.format == NACodecTypeInfo::None {
322 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
324 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
325 let ret = oval[1].parse::<NAChannelMap>();
326 if let Ok(val) = ret {
329 println!("invalid channel map");
332 println!("audio option for video stream");
336 let ret = oval[1].parse::<u32>();
337 if let Ok(val) = ret {
338 ostr.enc_params.bitrate = val;
340 println!("invalid bitrate value");
344 let ret = oval[1].parse::<u8>();
345 if let Ok(val) = ret {
346 ostr.enc_params.quality = val;
348 println!("invalid quality value");
352 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
356 println!("unrecognized option '{}'", opt);
361 fn parse_demuxer_options(&mut self, opts: &str, dmx_reg: &RegisteredDemuxers) -> bool {
362 for opt in opts.split(',') {
363 let oval: Vec<_> = opt.split('=').collect();
365 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
366 } else if oval.len() == 2 {
367 if oval[0] == "format" {
368 if dmx_reg.find_demuxer(oval[1]).is_some() {
369 self.input_fmt = Some(oval[1].to_string());
371 println!("unknown demuxer format '{}'", oval[1]);
374 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
377 println!("unrecognized option '{}'", opt);
382 fn parse_muxer_options(&mut self, opts: &str, mux_reg: &RegisteredMuxers) -> bool {
383 for opt in opts.split(',') {
384 let oval: Vec<_> = opt.split('=').collect();
386 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
387 } else if oval.len() == 2 {
388 if oval[0] == "format" {
389 if mux_reg.find_muxer(oval[1]).is_some() {
390 self.output_fmt = Some(oval[1].to_string());
392 println!("unknown muxer format '{}'", oval[1]);
395 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
398 println!("unrecognized option '{}'", opt);
403 fn apply_decoder_options(&self, dec: &mut dyn NADecoder, str_id: u32) {
404 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == str_id) {
405 let dec_opts = dec.get_supported_options();
406 if dec_opts.is_empty() { return; }
407 let name = format!("input stream {}", str_id);
408 parse_and_apply_options!(dec, &self.istr_opts[str_idx].dec_opts, name);
411 fn register_output_stream(&mut self, cname: &str, istr: NAStreamRef, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
412 let out_id = out_sm.get_num_streams() as u32;
413 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == (istr.get_num() as u32)) {
414 if self.istr_opts[str_idx].drop {
415 self.encoders.push(OutputMode::Drop);
420 if let Some(str_idx) = self.ostr_opts.iter().position(|str| str.id == out_id) {
421 let oopts = &mut self.ostr_opts[str_idx];
422 if oopts.enc_name.as_str() == "copy" && (cname == "any" || istr.get_info().get_name() == cname) {
423 out_sm.add_stream_ref(istr);
424 self.encoders.push(OutputMode::Copy(out_id));
425 } else if cname == "any" || oopts.enc_name.as_str() == cname {
426 let enc_create = enc_reg.find_encoder(oopts.enc_name.as_str());
427 if enc_create.is_none() {
428 println!("encoder '{}' not found", oopts.enc_name.as_str());
431 let mut encoder = (enc_create.unwrap())();
432 let forced_out = oopts.enc_params.format != NACodecTypeInfo::None;
433 if oopts.enc_params.format == NACodecTypeInfo::None {
434 oopts.enc_params.format = istr.get_info().get_properties();
436 if oopts.enc_params.tb_num == 0 {
437 oopts.enc_params.tb_num = istr.tb_num;
438 oopts.enc_params.tb_den = istr.tb_den;
440 let ret_eparams = encoder.negotiate_format(&oopts.enc_params);
441 if ret_eparams.is_err() {
442 println!("cannot negotiate encoding parameters");
445 let ret_eparams = ret_eparams.unwrap();
447 //todo check for params mismatch
448 let cvt = match (&oopts.enc_params.format, &ret_eparams.format) {
449 (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => {
450 if svinfo == dvinfo && !forced_out {
453 let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height };
454 let ret = NAScale::new(ofmt, ofmt);
456 println!("cannot create scaler");
459 let scaler = ret.unwrap();
460 let ret = alloc_video_buffer(*dvinfo, 4);
462 println!("cannot create scaler buffer");
465 let cvt_buf = ret.unwrap();
466 OutputConvert::Video(scaler, cvt_buf)
469 (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => {
470 if sainfo == dainfo {
473 let dchmap = match dainfo.channels {
474 1 => NAChannelMap::from_ms_mapping(0x4),
475 2 => NAChannelMap::from_ms_mapping(0x3),
477 println!("can't generate default channel map for {} channels", dainfo.channels);
482 OutputConvert::Audio(*dainfo, dchmap)
485 _ => OutputConvert::None,
487 let ret = encoder.init(out_id, ret_eparams);
489 println!("error initialising encoder");
492 out_sm.add_stream_ref(ret.unwrap());
494 let name = format!("output stream {}", out_id);
495 parse_and_apply_options!(encoder, &oopts.enc_opts, name);
497 self.encoders.push(OutputMode::Encode(out_id, encoder, cvt));
499 println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name());
502 } else if cname == "any" || istr.get_info().get_name() == cname {
503 out_sm.add_stream_ref(istr);
504 self.encoders.push(OutputMode::Copy(out_id));
506 println!("stream {} ({}) can't be handled", istr.id, istr.get_info().get_name());
507 // todo autoselect encoder?
512 fn map_single(&mut self, cname: &str, ctype: StreamType, src_sm: &StreamManager, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
513 let mut found_stream = false;
514 for istr in src_sm.iter() {
515 if istr.get_media_type() != ctype || found_stream {
516 self.encoders.push(OutputMode::Drop);
518 if !self.register_output_stream(cname, istr, out_sm, enc_reg) {
526 fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
528 MuxerCapabilities::SingleVideo(cname) => {
529 if self.no_video { return false; }
530 self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg)
532 MuxerCapabilities::SingleAudio(cname) => {
533 if self.no_audio { return false; }
534 self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg)
536 MuxerCapabilities::SingleVideoAndAudio(vname, aname) => {
537 let mut found_vid = false;
538 let mut found_aud = false;
539 for istr in src_sm.iter() {
540 if istr.get_media_type() == StreamType::Video && !found_vid && !self.no_video {
541 if !self.register_output_stream(vname, istr, out_sm, enc_reg) {
545 } else if istr.get_media_type() == StreamType::Audio && !found_aud && !self.no_audio {
546 if !self.register_output_stream(aname, istr, out_sm, enc_reg) {
551 self.encoders.push(OutputMode::Drop);
554 found_vid | found_aud
556 MuxerCapabilities::OnlyVideo => {
557 if self.no_video { return false; }
559 let mut found_vid = false;
560 for istr in src_sm.iter() {
561 if istr.get_media_type() == StreamType::Video && !found_vid {
562 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
567 self.encoders.push(OutputMode::Drop);
572 MuxerCapabilities::OnlyAudio => {
573 if self.no_audio { return false; }
575 let mut found_aud = false;
576 for istr in src_sm.iter() {
577 if istr.get_media_type() == StreamType::Audio && !found_aud {
578 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
583 self.encoders.push(OutputMode::Drop);
588 MuxerCapabilities::Universal => {
589 for istr in src_sm.iter() {
590 if (istr.get_media_type() == StreamType::Video && self.no_video) ||
591 (istr.get_media_type() == StreamType::Audio && self.no_audio) {
592 self.encoders.push(OutputMode::Drop);
595 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
605 fn encode_frame(dst_id: u32, encoder: &mut Box<dyn NAEncoder>, cvt: &mut OutputConvert, frm: NAFrameRef) -> bool {
606 let buf = frm.get_buffer();
607 let cbuf = match cvt {
608 OutputConvert::None => buf,
609 OutputConvert::Video(ref mut scaler, ref mut dbuf) => {
610 let cur_ifmt = get_scale_fmt_from_pic(&buf);
611 let last_ifmt = scaler.get_in_fmt();
612 if cur_ifmt != last_ifmt {
613 let ofmt = scaler.get_out_fmt();
614 let ret = NAScale::new(cur_ifmt, ofmt);
616 println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt);
619 *scaler = ret.unwrap();
621 let ret = scaler.convert(&buf, dbuf);
623 println!("error converting frame for encoding");
628 OutputConvert::Audio(ref dinfo, ref dchmap) => {
629 let ret = convert_audio_frame(&buf, dinfo, dchmap);
631 println!("error converting audio for stream {}", dst_id);
637 let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf);
638 encoder.encode(&cfrm).unwrap();
642 macro_rules! next_arg {
643 ($args: expr, $arg_idx: expr) => {
644 if $arg_idx + 1 >= $args.len() {
645 println!("codec name is required");
651 #[allow(clippy::single_match)]
653 let args: Vec<_> = env::args().collect();
656 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
657 println!(" use nihav-encoder --help to list all available options");
660 if args.len() == 2 && (args[1] == "--help" || args[1] == "-h") {
661 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
662 println!(" query options:");
663 println!(" --list-{{decoders,encoders,demuxers,muxers}} - lists all available decoders/encoders/demuxers/muxers");
664 println!(" --query-{{decoder,encoder,demuxer,muxer}}-options name - lists all options recognized by that decoder/encoder/demuxer/muxer");
665 println!(" processing options:");
666 println!(" --input inputfile - set input file");
667 println!(" --input-format fmt - force input format");
668 println!(" --demuxer-options options - set input demuxer options");
669 println!(" --output outputfile - set output file");
670 println!(" --output-format fmt - force output format");
671 println!(" --muxer-options options - set output muxer options");
672 println!(" --no-audio - do not decode audio streams");
673 println!(" --no-video - do not decode video streams");
674 println!(" --start starttime - start decoding from given position");
675 println!(" --end endtime - end decoding at given position");
676 println!(" --istreamX options - set options for input stream X");
677 println!(" --ostreamX options - set options for output stream X");
679 println!(" (de)muxer and stream options are passed as comma-separated list e.g. --ostream0 width=320,height=240,flip");
683 let mut dmx_reg = RegisteredDemuxers::new();
684 nihav_register_all_demuxers(&mut dmx_reg);
685 let mut dec_reg = RegisteredDecoders::new();
686 nihav_register_all_decoders(&mut dec_reg);
688 let mut mux_reg = RegisteredMuxers::new();
689 nihav_register_all_muxers(&mut mux_reg);
690 mux_reg.add_muxer(NULL_MUXER);
691 let mut enc_reg = RegisteredEncoders::new();
692 nihav_register_all_encoders(&mut enc_reg);
693 enc_reg.add_encoder(NULL_ENCODER);
695 let mut transcoder = Transcoder::new();
698 let mut printed_info = false;
699 while arg_idx < args.len() {
700 match args[arg_idx].as_str() {
701 "--list-decoders" => {
702 if dec_reg.iter().len() > 0 {
703 println!("Registered decoders:");
704 for dec in dec_reg.iter() {
705 let cdesc = register::get_codec_description(dec.name);
706 let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" };
707 println!(" {} ({})", dec.name, full_name);
710 println!("No registered decoders.");
714 "--list-encoders" => {
715 if enc_reg.iter().len() > 0 {
716 println!("Registered encoders:");
717 for enc in enc_reg.iter() {
718 let cdesc = register::get_codec_description(enc.name);
719 let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" };
720 println!(" {} ({})", enc.name, full_name);
723 println!("No registered encoders.");
727 "--list-demuxers" => {
728 print!("Registered demuxers:");
729 for dmx in dmx_reg.iter() {
730 print!(" {}", dmx.get_name());
736 print!("Registered muxers:");
737 for mux in mux_reg.iter() {
738 print!(" {}", mux.get_name());
743 "--query-decoder-options" => {
744 next_arg!(args, arg_idx);
745 let cname = args[arg_idx].as_str();
746 if let Some(decfunc) = dec_reg.find_decoder(cname) {
747 let dec = (decfunc)();
748 let opts = dec.get_supported_options();
749 print_options(cname, opts);
751 println!("codec {} is not found", cname);
755 "--query-demuxer-options" => {
756 next_arg!(args, arg_idx);
757 let dname = args[arg_idx].as_str();
758 let mut mr = MemoryReader::new_read(&[]);
759 let mut br = ByteReader::new(&mut mr);
760 if let Some(dmx_creator) = dmx_reg.find_demuxer(dname) {
761 let dmx = dmx_creator.new_demuxer(&mut br);
762 let opts = dmx.get_supported_options();
763 print_options(dname, opts);
765 println!("demuxer {} is not found", dname);
769 "--query-encoder-options" => {
770 next_arg!(args, arg_idx);
771 let cname = args[arg_idx].as_str();
772 if let Some(encfunc) = enc_reg.find_encoder(cname) {
773 let enc = (encfunc)();
774 let opts = enc.get_supported_options();
775 print_options(cname, opts);
777 println!("codec {} is not found", cname);
781 "--query-muxer-options" => {
782 next_arg!(args, arg_idx);
783 let name = args[arg_idx].as_str();
785 let mut mw = MemoryWriter::new_write(&mut data);
786 let mut bw = ByteWriter::new(&mut mw);
787 if let Some(mux_creator) = mux_reg.find_muxer(name) {
788 let mux = mux_creator.new_muxer(&mut bw);
789 let opts = mux.get_supported_options();
790 print_options(name, opts);
792 println!("muxer {} is not found", name);
796 "--input" | "-i" => {
797 next_arg!(args, arg_idx);
798 transcoder.input_name = args[arg_idx].clone();
800 "--input-format" => {
801 next_arg!(args, arg_idx);
802 transcoder.input_fmt = Some(args[arg_idx].clone());
804 "--output" | "-o" => {
805 next_arg!(args, arg_idx);
806 transcoder.output_name = args[arg_idx].clone();
808 "--output-format" => {
809 next_arg!(args, arg_idx);
810 transcoder.output_fmt = Some(args[arg_idx].clone());
812 "--demuxer-options" => {
813 next_arg!(args, arg_idx);
814 if !transcoder.parse_demuxer_options(&args[arg_idx], &dmx_reg) {
815 println!("invalid demuxer option syntax");
819 "--no-video" | "-vn" => {
820 transcoder.no_video = true;
822 "--no-audio" | "-an" => {
823 transcoder.no_audio = true;
826 next_arg!(args, arg_idx);
827 let ret = args[arg_idx].parse::<NATimePoint>();
828 if let Ok(val) = ret {
829 transcoder.start = val;
831 println!("invalid start time");
836 next_arg!(args, arg_idx);
837 let ret = args[arg_idx].parse::<NATimePoint>();
838 if let Ok(val) = ret {
839 transcoder.end = val;
841 println!("invalid end time");
845 "--muxer-options" => {
846 next_arg!(args, arg_idx);
847 if !transcoder.parse_muxer_options(&args[arg_idx], &mux_reg) {
848 println!("invalid muxer option syntax");
853 if args[arg_idx].starts_with("--istream") {
854 let opt0 = &args[arg_idx];
855 next_arg!(args, arg_idx);
856 if !transcoder.parse_istream_options(opt0, &args[arg_idx]) {
857 println!("invalid input stream option syntax");
860 } else if args[arg_idx].starts_with("--ostream") {
861 let opt0 = &args[arg_idx];
862 next_arg!(args, arg_idx);
863 if !transcoder.parse_ostream_options(opt0, &args[arg_idx], &enc_reg) {
864 println!("invalid output stream option syntax");
867 } else if args[arg_idx].starts_with("--") {
868 println!("unknown option");
870 println!("unrecognized argument");
881 if transcoder.input_name.is_empty() {
882 println!("no input name provided");
885 if transcoder.output_name.is_empty() {
886 println!("no output name provided");
890 let res = File::open(transcoder.input_name.as_str());
892 println!("error opening input");
895 let mut file = res.unwrap();
896 let mut fr = FileReader::new_read(&mut file);
897 let mut br = ByteReader::new(&mut fr);
899 let dmx_name = if let Some(ref str) = transcoder.input_fmt {
901 } else if let Some((dmx_name, score)) = detect::detect_format(transcoder.input_name.as_str(), &mut br) {
902 println!("detected {} with score {:?}", dmx_name, score);
905 println!("cannot detect input format");
908 let ret = dmx_reg.find_demuxer(dmx_name);
910 println!("cannot find demuxer for '{}'", dmx_name);
913 let dmx_fact = ret.unwrap();
914 br.seek(SeekFrom::Start(0)).unwrap();
915 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
916 parse_and_apply_options!(dmx, &transcoder.demux_opts, "input");
917 for i in 0..dmx.get_num_streams() {
918 let s = dmx.get_stream(i).unwrap();
919 let info = s.get_info();
920 let decfunc = dec_reg.find_decoder(info.get_name());
921 println!("stream {} - {} {}", i, s, info.get_name());
922 let str_id = s.get_num() as u32;
923 if let Some(create_dec) = decfunc {
924 let mut dec = (create_dec)();
925 let mut dsupp = Box::new(NADecoderSupport::new());
926 let ret = dec.init(&mut dsupp, info.clone());
928 println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id);
931 transcoder.apply_decoder_options(dec.as_mut(), str_id);
932 let desc = register::get_codec_description(info.get_name());
933 let has_b = if let Some(desc) = desc {
936 println!("No codec description found, using B-frame reorderer.");
939 let reord: Box<dyn FrameReorderer> = if has_b { Box::new(IPBReorderer::new()) } else { Box::new(NoReorderer::new()) };
940 transcoder.decoders.push(Some((dsupp, dec, reord)));
942 println!("No decoder for stream {} ({}) is found", str_id, info.get_name());
943 transcoder.decoders.push(None);
946 if transcoder.start != NATimePoint::None {
947 let ret = dmx.seek(transcoder.start);
949 println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap());
953 let output_fmt = if let Some(ref str) = transcoder.output_fmt {
955 } else if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) {
958 println!("Cannot guess muxer for output");
961 let ret = mux_reg.find_muxer(output_fmt);
962 let ofmt = output_fmt.to_string();
965 println!("cannot find muxer '{}'", output_fmt);
967 let mux_creator = ret.unwrap();
969 let mux_caps = mux_creator.get_capabilities();
970 let mut out_sm = StreamManager::new();
971 if !transcoder.negotiate_stream_map(dmx.get_stream_manager(), mux_caps, &mut out_sm, &enc_reg) {
972 println!("cannot determine stream map");
976 let ret = File::create(transcoder.output_name.as_str());
978 println!("cannot open output file");
981 let mut fw = FileWriter::new_write(ret.unwrap());
982 let mut bw = ByteWriter::new(&mut fw);
983 let ret = create_muxer(mux_creator, out_sm, &mut bw);
984 if let Err(err) = ret {
985 println!("cannot create muxer instance {:?}", err);
988 let mut mux = ret.unwrap();
989 parse_and_apply_options!(mux, &transcoder.mux_opts, "output");
991 println!("Output {} muxer {}", transcoder.output_name, ofmt);
992 for ostr in mux.get_streams() {
993 println!(" #{}: {} {}", ostr.get_num(), ostr, ostr.get_info().get_name());
997 let pktres = dmx.get_frame();
998 if let Err(DemuxerError::EOF) = pktres { break; }
1000 println!("demuxing error");
1003 let mut pkt = pktres.unwrap();
1004 if transcoder.start != NATimePoint::None && pkt.ts.less_than(transcoder.start) { continue; }
1005 let src_id = pkt.get_stream().get_num();
1006 match transcoder.encoders[src_id] {
1007 OutputMode::Drop => {},
1008 OutputMode::Copy(dst_id) => {
1009 let dstr = mux.get_stream(dst_id as usize).unwrap();
1010 pkt.reassign(dstr, pkt.get_time_information());
1011 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1012 if mux.mux_frame(pkt).is_err() {
1013 println!("error muxing packet");
1017 OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) => {
1018 if let Some((ref mut dsupp, ref mut decoder, ref mut reorderer)) = transcoder.decoders[src_id] {
1019 let ret = decoder.decode(dsupp, &pkt);
1020 if let (true, Err(DecoderError::MissingReference)) = (transcoder.start != NATimePoint::None, &ret) {
1024 println!("error decoding stream {}", src_id);
1027 let frm = ret.unwrap();
1028 reorderer.add_frame(frm);
1029 while let Some(frm) = reorderer.get_frame() {
1030 if !encode_frame(dst_id, encoder, cvt, frm) {
1033 while let Ok(Some(pkt)) = encoder.get_packet() {
1034 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1035 mux.mux_frame(pkt).unwrap();
1039 println!("no decoder for stream {}", src_id);
1045 'reord_flush_loop: for str in dmx.get_streams() {
1046 let src_id = str.get_num();
1047 if let OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) = transcoder.encoders[src_id] {
1048 if let Some((_, _, ref mut reorderer)) = transcoder.decoders[src_id] {
1049 while let Some(frm) = reorderer.get_last_frames() {
1050 if !encode_frame(dst_id, encoder, cvt, frm) {
1053 while let Ok(Some(pkt)) = encoder.get_packet() {
1054 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'reord_flush_loop; }
1055 mux.mux_frame(pkt).unwrap();
1061 'flush_loop: for enc in transcoder.encoders.iter_mut() {
1063 OutputMode::Encode(str_id, ref mut encoder, _) => {
1064 let ret = encoder.flush();
1066 println!("error flushing encoder for stream {}", str_id);
1069 while let Ok(Some(pkt)) = encoder.get_packet() {
1070 if mux.mux_frame(pkt).is_err() {
1071 println!("error muxing packet");
1081 let ret = mux.end();
1083 println!("error at finalising muxing");