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),
62 Encode(u32, Box<dyn NAEncoder>, OutputConvert),
68 input_fmt: Option<String>,
70 output_fmt: Option<String>,
71 demux_opts: Vec<OptionArgs>,
72 mux_opts: Vec<OptionArgs>,
73 istr_opts: Vec<InputStreamOptions>,
74 ostr_opts: Vec<OutputStreamOptions>,
75 decoders: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>, Box<dyn FrameReorderer>)>>,
76 encoders: Vec<OutputMode>,
83 macro_rules! parse_and_apply_options {
84 ($obj: expr, $in_opts: expr, $name: expr) => {
85 let mut opts = Vec::with_capacity($in_opts.len());
86 let opt_def = $obj.get_supported_options();
87 for opt in $in_opts.iter() {
88 let mut found = false;
89 for opt_def in opt_def.iter() {
90 if opt.name == opt_def.name {
91 let arg = if let Some(ref str) = opt.value { Some(str) } else { None };
92 let ret = opt_def.parse(&opt.name, arg);
94 println!("invalid option {} for {}", opt.name, $name);
96 let (val, _) = ret.unwrap();
103 println!(" ignoring option '{}' for {}", opt.name, $name);
106 $obj.set_options(opts.as_slice());
111 fn new() -> Self { Self::default() }
112 fn parse_istream_options(&mut self, opt0: &str, opt1: &str) -> bool {
113 let (_, strno) = opt0.split_at(9);
114 let ret = strno.parse::<u32>();
115 if ret.is_err() { return false; }
116 let streamno = ret.unwrap();
118 let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) {
121 self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() });
122 self.istr_opts.len() - 1
124 let istr = &mut self.istr_opts[sidx];
126 for opt in opt1.split(',') {
127 let oval: Vec<_> = opt.split('=').collect();
130 "drop" => { istr.drop = true; },
132 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
135 } else if oval.len() == 2 {
136 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
138 println!("unrecognized option '{}'", opt);
143 fn parse_ostream_options(&mut self, opt0: &str, opt1: &str, enc_reg: &RegisteredEncoders) -> bool {
144 let (_, strno) = opt0.split_at(9);
145 let ret = strno.parse::<u32>();
146 if ret.is_err() { return false; }
147 let streamno = ret.unwrap();
149 let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) {
152 self.ostr_opts.push(OutputStreamOptions {id: streamno, enc_name: String::new(), enc_params: EncodeParameters::default(), enc_opts: Vec::new() });
153 self.ostr_opts.len() - 1
155 let ostr = &mut self.ostr_opts[sidx];
157 for opt in opt1.split(',') {
158 let oval: Vec<_> = opt.split('=').collect();
162 if ostr.enc_params.format == NACodecTypeInfo::None {
163 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
165 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
166 vinfo.flipped = true;
168 println!("video option for audio stream");
172 if ostr.enc_params.format == NACodecTypeInfo::None {
173 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
175 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
176 vinfo.flipped = false;
178 println!("video option for audio stream");
182 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
185 } else if oval.len() == 2 {
186 //todo parse encoder options, store, init later
189 let mut parts = oval[1].split('/');
190 let num = parts.next().unwrap();
191 let den = parts.next();
192 if let Some(den) = den {
193 let rnum = num.parse::<u32>();
194 let rden = den.parse::<u32>();
195 if let (Ok(num), Ok(den)) = (rnum, rden) {
196 ostr.enc_params.tb_num = num;
197 ostr.enc_params.tb_den = den;
199 println!("invalid timebase value");
202 println!("invalid timebase format (should be num/den)");
206 if enc_reg.find_encoder(oval[1]).is_some() {
207 ostr.enc_name = oval[1].to_string();
209 println!("unknown encoder '{}'", oval[1]);
210 ostr.enc_name = oval[1].to_string();
214 if ostr.enc_params.format == NACodecTypeInfo::None {
215 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
217 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
218 let ret = oval[1].parse::<usize>();
219 if let Ok(val) = ret {
222 println!("invalid width");
225 println!("video option for audio stream");
229 if ostr.enc_params.format == NACodecTypeInfo::None {
230 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
232 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
233 let ret = oval[1].parse::<usize>();
234 if let Ok(val) = ret {
237 println!("invalid height");
240 println!("video option for audio stream");
244 if ostr.enc_params.format == NACodecTypeInfo::None {
245 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
247 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
248 let ret = oval[1].parse::<NAPixelFormaton>();
249 if let Ok(val) = ret {
252 println!("invalid pixel format");
255 println!("video option for audio stream");
259 if ostr.enc_params.format == NACodecTypeInfo::None {
260 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
262 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
263 let ret = oval[1].parse::<u32>();
264 if let Ok(val) = ret {
265 ainfo.sample_rate = val;
267 println!("invalid sampling rate");
270 println!("audio option for video stream");
274 if ostr.enc_params.format == NACodecTypeInfo::None {
275 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
277 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
278 let ret = oval[1].parse::<u8>();
279 if let Ok(val) = ret {
280 ainfo.channels = val;
282 println!("invalid number of channels");
285 println!("audio option for video stream");
289 if ostr.enc_params.format == NACodecTypeInfo::None {
290 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
292 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
293 let ret = oval[1].parse::<usize>();
294 if let Ok(val) = ret {
295 ainfo.block_len = val;
297 println!("invalid block_length");
300 println!("audio option for video stream");
304 if ostr.enc_params.format == NACodecTypeInfo::None {
305 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
307 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
308 let ret = oval[1].parse::<NASoniton>();
309 if let Ok(val) = ret {
312 println!("invalid audio format");
315 println!("audio option for video stream");
318 // todo channel map negotiation
320 if ostr.enc_params.format == NACodecTypeInfo::None {
321 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
323 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
324 let ret = oval[1].parse::<NAChannelMap>();
325 if let Ok(val) = ret {
328 println!("invalid channel map");
331 println!("audio option for video stream");
335 let ret = oval[1].parse::<u32>();
336 if let Ok(val) = ret {
337 ostr.enc_params.bitrate = val;
339 println!("invalid bitrate value");
343 let ret = oval[1].parse::<u8>();
344 if let Ok(val) = ret {
345 ostr.enc_params.quality = val;
347 println!("invalid quality value");
351 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
355 println!("unrecognized option '{}'", opt);
360 fn parse_demuxer_options(&mut self, opts: &str, dmx_reg: &RegisteredDemuxers) -> bool {
361 for opt in opts.split(',') {
362 let oval: Vec<_> = opt.split('=').collect();
364 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
365 } else if oval.len() == 2 {
366 if oval[0] == "format" {
367 if dmx_reg.find_demuxer(oval[1]).is_some() {
368 self.input_fmt = Some(oval[1].to_string());
370 println!("unknown demuxer format '{}'", oval[1]);
373 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
376 println!("unrecognized option '{}'", opt);
381 fn parse_muxer_options(&mut self, opts: &str, mux_reg: &RegisteredMuxers) -> bool {
382 for opt in opts.split(',') {
383 let oval: Vec<_> = opt.split('=').collect();
385 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
386 } else if oval.len() == 2 {
387 if oval[0] == "format" {
388 if mux_reg.find_muxer(oval[1]).is_some() {
389 self.output_fmt = Some(oval[1].to_string());
391 println!("unknown muxer format '{}'", oval[1]);
394 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
397 println!("unrecognized option '{}'", opt);
402 fn apply_decoder_options(&self, dec: &mut NADecoder, str_id: u32) {
403 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == str_id) {
404 let dec_opts = dec.get_supported_options();
405 if dec_opts.is_empty() { return; }
406 let name = format!("input stream {}", str_id);
407 parse_and_apply_options!(dec, &self.istr_opts[str_idx].dec_opts, name);
410 fn register_output_stream(&mut self, cname: &str, istr: NAStreamRef, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
411 let out_id = out_sm.get_num_streams() as u32;
412 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == (istr.get_num() as u32)) {
413 if self.istr_opts[str_idx].drop {
414 self.encoders.push(OutputMode::Drop);
419 if let Some(str_idx) = self.ostr_opts.iter().position(|str| str.id == out_id) {
420 let oopts = &mut self.ostr_opts[str_idx];
421 if oopts.enc_name.as_str() == "copy" && (cname == "any" || istr.get_info().get_name() == cname) {
422 out_sm.add_stream_ref(istr.clone());
423 self.encoders.push(OutputMode::Copy(out_id));
424 } else if cname == "any" || oopts.enc_name.as_str() == cname {
425 let enc_create = enc_reg.find_encoder(oopts.enc_name.as_str());
426 if enc_create.is_none() {
427 println!("encoder '{}' not found", oopts.enc_name.as_str());
430 let mut encoder = (enc_create.unwrap())();
431 let forced_out = oopts.enc_params.format != NACodecTypeInfo::None;
432 if oopts.enc_params.format == NACodecTypeInfo::None {
433 oopts.enc_params.format = istr.get_info().get_properties();
435 if oopts.enc_params.tb_num == 0 {
436 oopts.enc_params.tb_num = istr.tb_num;
437 oopts.enc_params.tb_den = istr.tb_den;
439 let ret_eparams = encoder.negotiate_format(&oopts.enc_params);
440 if ret_eparams.is_err() {
441 println!("cannot negotiate encoding parameters");
444 let ret_eparams = ret_eparams.unwrap();
446 //todo check for params mismatch
447 let cvt = match (&oopts.enc_params.format, &ret_eparams.format) {
448 (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => {
449 if svinfo == dvinfo && !forced_out {
452 let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height };
453 let ret = NAScale::new(ofmt, ofmt);
455 println!("cannot create scaler");
458 let scaler = ret.unwrap();
459 let ret = alloc_video_buffer(*dvinfo, 4);
461 println!("cannot create scaler buffer");
464 let cvt_buf = ret.unwrap();
465 OutputConvert::Video(scaler, cvt_buf)
468 (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => {
469 if sainfo == dainfo {
472 let dchmap = match dainfo.channels {
473 1 => NAChannelMap::from_ms_mapping(0x4),
474 2 => NAChannelMap::from_ms_mapping(0x3),
476 println!("can't generate default channel map for {} channels", dainfo.channels);
481 OutputConvert::Audio(*dainfo, dchmap)
484 _ => OutputConvert::None,
486 let ret = encoder.init(out_id, ret_eparams);
488 println!("error initialising encoder");
491 out_sm.add_stream_ref(ret.unwrap());
493 let name = format!("output stream {}", out_id);
494 parse_and_apply_options!(encoder, &oopts.enc_opts, name);
496 self.encoders.push(OutputMode::Encode(out_id, encoder, cvt));
498 println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name());
502 if cname == "any" || istr.get_info().get_name() == cname {
503 out_sm.add_stream_ref(istr.clone());
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?
513 fn map_single(&mut self, cname: &str, ctype: StreamType, src_sm: &StreamManager, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
514 let mut found_stream = false;
515 for istr in src_sm.iter() {
516 if istr.get_media_type() != ctype || found_stream {
517 self.encoders.push(OutputMode::Drop);
519 if !self.register_output_stream(cname, istr, out_sm, enc_reg) {
527 fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
529 MuxerCapabilities::SingleVideo(cname) => {
530 if self.no_video { return false; }
531 self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg)
533 MuxerCapabilities::SingleAudio(cname) => {
534 if self.no_audio { return false; }
535 self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg)
537 MuxerCapabilities::SingleVideoAndAudio(vname, aname) => {
538 let mut found_vid = false;
539 let mut found_aud = false;
540 for istr in src_sm.iter() {
541 if istr.get_media_type() == StreamType::Video && !found_vid && !self.no_video {
542 if !self.register_output_stream(vname, istr, out_sm, enc_reg) {
546 } else if istr.get_media_type() == StreamType::Audio && !found_aud && !self.no_audio {
547 if !self.register_output_stream(aname, istr, out_sm, enc_reg) {
552 self.encoders.push(OutputMode::Drop);
555 found_vid | found_aud
557 MuxerCapabilities::OnlyVideo => {
558 if self.no_video { return false; }
560 let mut found_vid = false;
561 for istr in src_sm.iter() {
562 if istr.get_media_type() == StreamType::Video && !found_vid {
563 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
568 self.encoders.push(OutputMode::Drop);
573 MuxerCapabilities::OnlyAudio => {
574 if self.no_audio { return false; }
576 let mut found_aud = false;
577 for istr in src_sm.iter() {
578 if istr.get_media_type() == StreamType::Audio && !found_aud {
579 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
584 self.encoders.push(OutputMode::Drop);
589 MuxerCapabilities::Universal => {
590 for istr in src_sm.iter() {
591 if (istr.get_media_type() == StreamType::Video && self.no_video) ||
592 (istr.get_media_type() == StreamType::Audio && self.no_audio) {
593 self.encoders.push(OutputMode::Drop);
596 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
606 fn encode_frame(dst_id: u32, encoder: &mut Box<NAEncoder>, cvt: &mut OutputConvert, frm: NAFrameRef) -> bool {
607 let buf = frm.get_buffer();
608 let cbuf = match cvt {
609 OutputConvert::None => buf,
610 OutputConvert::Video(ref mut scaler, ref mut dbuf) => {
611 let cur_ifmt = get_scale_fmt_from_pic(&buf);
612 let last_ifmt = scaler.get_in_fmt();
613 if cur_ifmt != last_ifmt {
614 let ofmt = scaler.get_out_fmt();
615 let ret = NAScale::new(cur_ifmt, ofmt);
617 println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt);
620 *scaler = ret.unwrap();
622 let ret = scaler.convert(&buf, dbuf);
624 println!("error converting frame for encoding");
629 OutputConvert::Audio(ref dinfo, ref dchmap) => {
630 let ret = convert_audio_frame(&buf, dinfo, dchmap);
632 println!("error converting audio for stream {}", dst_id);
638 let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf);
639 encoder.encode(&cfrm).unwrap();
643 macro_rules! next_arg {
644 ($args: expr, $arg_idx: expr) => {
645 if $arg_idx + 1 >= $args.len() {
646 println!("codec name is required");
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.len() == 0 {
882 println!("no input name provided");
885 if transcoder.output_name.len() == 0 {
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 {
902 if let Some((dmx_name, score)) = detect::detect_format(transcoder.input_name.as_str(), &mut br) {
903 println!("detected {} with score {:?}", dmx_name, score);
906 println!("cannot detect input format");
910 let ret = dmx_reg.find_demuxer(dmx_name);
912 println!("cannot find demuxer for '{}'", dmx_name);
915 let dmx_fact = ret.unwrap();
916 br.seek(SeekFrom::Start(0)).unwrap();
917 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
918 parse_and_apply_options!(dmx, &transcoder.demux_opts, "input");
919 for i in 0..dmx.get_num_streams() {
920 let s = dmx.get_stream(i).unwrap();
921 let info = s.get_info();
922 let decfunc = dec_reg.find_decoder(info.get_name());
923 println!("stream {} - {} {}", i, s, info.get_name());
924 let str_id = s.get_num() as u32;
925 if let Some(create_dec) = decfunc {
926 let mut dec = (create_dec)();
927 let mut dsupp = Box::new(NADecoderSupport::new());
928 let ret = dec.init(&mut dsupp, info.clone());
930 println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id);
933 transcoder.apply_decoder_options(dec.as_mut(), str_id);
934 let desc = register::get_codec_description(info.get_name());
935 let has_b = if let Some(desc) = desc {
938 println!("No codec description found, using B-frame reorderer.");
941 let reord: Box<dyn FrameReorderer> = if has_b { Box::new(IPBReorderer::new()) } else { Box::new(NoReorderer::new()) };
942 transcoder.decoders.push(Some((dsupp, dec, reord)));
944 println!("No decoder for stream {} ({}) is found", str_id, info.get_name());
945 transcoder.decoders.push(None);
948 if transcoder.start != NATimePoint::None {
949 let ret = dmx.seek(transcoder.start);
951 println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap());
955 let output_fmt = if let Some(ref str) = transcoder.output_fmt {
958 if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) {
961 println!("Cannot guess muxer for output");
965 let ret = mux_reg.find_muxer(output_fmt);
966 let ofmt = output_fmt.to_string();
969 println!("cannot find muxer '{}'", output_fmt);
971 let mux_creator = ret.unwrap();
973 let mux_caps = mux_creator.get_capabilities();
974 let mut out_sm = StreamManager::new();
975 if !transcoder.negotiate_stream_map(dmx.get_stream_manager(), mux_caps, &mut out_sm, &enc_reg) {
976 println!("cannot determine stream map");
980 let ret = File::create(transcoder.output_name.as_str());
982 println!("cannot open output file");
985 let mut fw = FileWriter::new_write(ret.unwrap());
986 let mut bw = ByteWriter::new(&mut fw);
987 let ret = create_muxer(mux_creator, out_sm, &mut bw);
988 if let Err(err) = ret {
989 println!("cannot create muxer instance {:?}", err);
992 let mut mux = ret.unwrap();
993 parse_and_apply_options!(mux, &transcoder.mux_opts, "output");
995 println!("Output {} muxer {}", transcoder.output_name, ofmt);
996 for ostr in mux.get_streams() {
997 println!(" #{}: {} {}", ostr.get_num(), ostr, ostr.get_info().get_name());
1001 let pktres = dmx.get_frame();
1002 if let Err(DemuxerError::EOF) = pktres { break; }
1003 if pktres.is_err() {
1004 println!("demuxing error");
1007 let mut pkt = pktres.unwrap();
1008 if transcoder.start != NATimePoint::None && pkt.ts.less_than(transcoder.start) { continue; }
1009 let src_id = pkt.get_stream().get_num();
1010 match transcoder.encoders[src_id] {
1011 OutputMode::Drop => {},
1012 OutputMode::Copy(dst_id) => {
1013 let dstr = mux.get_stream(dst_id as usize).unwrap();
1014 pkt.reassign(dstr, pkt.get_time_information());
1015 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1016 if mux.mux_frame(pkt).is_err() {
1017 println!("error muxing packet");
1021 OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) => {
1022 if let Some((ref mut dsupp, ref mut decoder, ref mut reorderer)) = transcoder.decoders[src_id] {
1023 let ret = decoder.decode(dsupp, &pkt);
1024 if let (true, Err(DecoderError::MissingReference)) = (transcoder.start != NATimePoint::None, &ret) {
1028 println!("error decoding stream {}", src_id);
1031 let frm = ret.unwrap();
1032 reorderer.add_frame(frm);
1033 while let Some(frm) = reorderer.get_frame() {
1034 if !encode_frame(dst_id, encoder, cvt, frm) {
1037 while let Ok(Some(pkt)) = encoder.get_packet() {
1038 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1039 mux.mux_frame(pkt).unwrap();
1043 println!("no decoder for stream {}", src_id);
1049 'reord_flush_loop: for str in dmx.get_streams() {
1050 let src_id = str.get_num();
1051 if let OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) = transcoder.encoders[src_id] {
1052 if let Some((_, _, ref mut reorderer)) = transcoder.decoders[src_id] {
1053 while let Some(frm) = reorderer.get_last_frames() {
1054 if !encode_frame(dst_id, encoder, cvt, frm) {
1057 while let Ok(Some(pkt)) = encoder.get_packet() {
1058 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'reord_flush_loop; }
1059 mux.mux_frame(pkt).unwrap();
1065 'flush_loop: for enc in transcoder.encoders.iter_mut() {
1067 OutputMode::Encode(str_id, ref mut encoder, _) => {
1068 let ret = encoder.flush();
1070 println!("error flushing encoder for stream {}", str_id);
1073 while let Ok(Some(pkt)) = encoder.get_packet() {
1074 if mux.mux_frame(pkt).is_err() {
1075 println!("error muxing packet");
1085 let ret = mux.end();
1087 println!("error at finalising muxing");