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 scale_opts: Vec<(String, String)>,
78 decoders: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>, Box<dyn FrameReorderer>)>>,
79 encoders: Vec<OutputMode>,
86 macro_rules! parse_and_apply_options {
87 ($obj: expr, $in_opts: expr, $name: expr) => {
88 let mut opts = Vec::with_capacity($in_opts.len());
89 let opt_def = $obj.get_supported_options();
90 for opt in $in_opts.iter() {
91 let mut found = false;
92 for opt_def in opt_def.iter() {
93 let mut matches = opt.name == opt_def.name;
94 if !matches && opt.name.starts_with("no") {
95 let (_, name) = opt.name.split_at(2);
96 matches = name == opt_def.name;
99 let arg = if let Some(ref str) = opt.value { Some(str) } else { None };
100 let ret = opt_def.parse(&opt.name, arg);
101 if let Ok((val, _)) = ret {
104 println!("invalid option {} for {}", opt.name, $name);
110 println!(" ignoring option '{}' for {}", opt.name, $name);
113 $obj.set_options(opts.as_slice());
118 fn new() -> Self { Self::default() }
119 fn parse_istream_options(&mut self, opt0: &str, opt1: &str) -> bool {
120 let (_, strno) = opt0.split_at(9);
121 let ret = strno.parse::<u32>();
122 if ret.is_err() { return false; }
123 let streamno = ret.unwrap();
125 let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) {
128 self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() });
129 self.istr_opts.len() - 1
131 let istr = &mut self.istr_opts[sidx];
133 for opt in opt1.split(',') {
134 let oval: Vec<_> = opt.split('=').collect();
137 "drop" => { istr.drop = true; },
139 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
142 } else if oval.len() == 2 {
143 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
145 println!("unrecognized option '{}'", opt);
150 fn parse_ostream_options(&mut self, opt0: &str, opt1: &str, enc_reg: &RegisteredEncoders) -> bool {
151 let (_, strno) = opt0.split_at(9);
152 let ret = strno.parse::<u32>();
153 if ret.is_err() { return false; }
154 let streamno = ret.unwrap();
156 let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) {
159 self.ostr_opts.push(OutputStreamOptions {id: streamno, enc_name: String::new(), enc_params: EncodeParameters::default(), enc_opts: Vec::new() });
160 self.ostr_opts.len() - 1
162 let ostr = &mut self.ostr_opts[sidx];
164 for opt in opt1.split(',') {
165 let oval: Vec<_> = opt.split('=').collect();
169 if ostr.enc_params.format == NACodecTypeInfo::None {
170 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
172 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
173 vinfo.flipped = true;
175 println!("video option for audio stream");
179 if ostr.enc_params.format == NACodecTypeInfo::None {
180 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
182 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
183 vinfo.flipped = false;
185 println!("video option for audio stream");
189 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
192 } else if oval.len() == 2 {
193 //todo parse encoder options, store, init later
196 let mut parts = oval[1].split('/');
197 let num = parts.next().unwrap();
198 let den = parts.next();
199 if let Some(den) = den {
200 let rnum = num.parse::<u32>();
201 let rden = den.parse::<u32>();
202 if let (Ok(num), Ok(den)) = (rnum, rden) {
203 ostr.enc_params.tb_num = num;
204 ostr.enc_params.tb_den = den;
206 println!("invalid timebase value");
209 println!("invalid timebase format (should be num/den)");
213 if enc_reg.find_encoder(oval[1]).is_some() {
214 ostr.enc_name = oval[1].to_string();
216 println!("unknown encoder '{}'", oval[1]);
217 ostr.enc_name = oval[1].to_string();
221 if ostr.enc_params.format == NACodecTypeInfo::None {
222 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
224 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
225 let ret = oval[1].parse::<usize>();
226 if let Ok(val) = ret {
229 println!("invalid width");
232 println!("video option for audio stream");
236 if ostr.enc_params.format == NACodecTypeInfo::None {
237 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
239 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
240 let ret = oval[1].parse::<usize>();
241 if let Ok(val) = ret {
244 println!("invalid height");
247 println!("video option for audio stream");
251 if ostr.enc_params.format == NACodecTypeInfo::None {
252 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
254 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
255 let ret = oval[1].parse::<NAPixelFormaton>();
256 if let Ok(val) = ret {
259 println!("invalid pixel format");
262 println!("video option for audio stream");
266 if ostr.enc_params.format == NACodecTypeInfo::None {
267 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
269 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
270 let ret = oval[1].parse::<u32>();
271 if let Ok(val) = ret {
272 ainfo.sample_rate = val;
274 println!("invalid sampling rate");
277 println!("audio option for video stream");
281 if ostr.enc_params.format == NACodecTypeInfo::None {
282 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
284 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
285 let ret = oval[1].parse::<u8>();
286 if let Ok(val) = ret {
287 ainfo.channels = val;
289 println!("invalid number of channels");
292 println!("audio option for video stream");
296 if ostr.enc_params.format == NACodecTypeInfo::None {
297 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
299 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
300 let ret = oval[1].parse::<usize>();
301 if let Ok(val) = ret {
302 ainfo.block_len = val;
304 println!("invalid block_length");
307 println!("audio option for video stream");
311 if ostr.enc_params.format == NACodecTypeInfo::None {
312 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
314 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
315 let ret = oval[1].parse::<NASoniton>();
316 if let Ok(val) = ret {
319 println!("invalid audio format");
322 println!("audio option for video stream");
325 // todo channel map negotiation
327 if ostr.enc_params.format == NACodecTypeInfo::None {
328 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
330 if let NACodecTypeInfo::Audio(ref mut ainfo) = ostr.enc_params.format {
331 let ret = oval[1].parse::<NAChannelMap>();
332 if let Ok(val) = ret {
335 println!("invalid channel map");
338 println!("audio option for video stream");
342 let ret = oval[1].parse::<u32>();
343 if let Ok(val) = ret {
344 ostr.enc_params.bitrate = val;
346 println!("invalid bitrate value");
350 let ret = oval[1].parse::<u8>();
351 if let Ok(val) = ret {
352 ostr.enc_params.quality = val;
354 println!("invalid quality value");
358 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
362 println!("unrecognized option '{}'", opt);
367 fn parse_demuxer_options(&mut self, opts: &str, dmx_reg: &RegisteredDemuxers) -> bool {
368 for opt in opts.split(',') {
369 let oval: Vec<_> = opt.split('=').collect();
371 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
372 } else if oval.len() == 2 {
373 if oval[0] == "format" {
374 if dmx_reg.find_demuxer(oval[1]).is_some() {
375 self.input_fmt = Some(oval[1].to_string());
377 println!("unknown demuxer format '{}'", oval[1]);
380 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
383 println!("unrecognized option '{}'", opt);
388 fn parse_muxer_options(&mut self, opts: &str, mux_reg: &RegisteredMuxers) -> bool {
389 for opt in opts.split(',') {
390 let oval: Vec<_> = opt.split('=').collect();
392 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
393 } else if oval.len() == 2 {
394 if oval[0] == "format" {
395 if mux_reg.find_muxer(oval[1]).is_some() {
396 self.output_fmt = Some(oval[1].to_string());
398 println!("unknown muxer format '{}'", oval[1]);
401 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
404 println!("unrecognized option '{}'", opt);
409 fn parse_scale_options(&mut self, opts: &str) -> bool {
410 for opt in opts.split(',') {
411 let oval: Vec<_> = opt.split('=').collect();
413 self.scale_opts.push((oval[0].to_string(), "".to_string()));
414 } else if oval.len() == 2 {
415 self.scale_opts.push((oval[0].to_string(), oval[1].to_string()));
417 println!("unrecognized option '{}'", opt);
423 fn apply_decoder_options(&self, dec: &mut dyn NADecoder, str_id: u32) {
424 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == str_id) {
425 let dec_opts = dec.get_supported_options();
426 if dec_opts.is_empty() { return; }
427 let name = format!("input stream {}", str_id);
428 parse_and_apply_options!(dec, &self.istr_opts[str_idx].dec_opts, name);
431 fn register_output_stream(&mut self, cname: &str, istr: NAStreamRef, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
432 let out_id = out_sm.get_num_streams() as u32;
433 if let Some(str_idx) = self.istr_opts.iter().position(|str| str.id == (istr.get_num() as u32)) {
434 if self.istr_opts[str_idx].drop {
435 self.encoders.push(OutputMode::Drop);
440 if let Some(str_idx) = self.ostr_opts.iter().position(|str| str.id == out_id) {
441 let oopts = &mut self.ostr_opts[str_idx];
442 if oopts.enc_name.as_str() == "copy" && (cname == "any" || istr.get_info().get_name() == cname) {
443 out_sm.add_stream_ref(istr);
444 self.encoders.push(OutputMode::Copy(out_id));
445 } else if cname == "any" || oopts.enc_name.as_str() == cname {
446 let enc_create = enc_reg.find_encoder(oopts.enc_name.as_str());
447 if enc_create.is_none() {
448 println!("encoder '{}' not found", oopts.enc_name.as_str());
451 let mut encoder = (enc_create.unwrap())();
452 let forced_out = oopts.enc_params.format != NACodecTypeInfo::None;
453 if oopts.enc_params.format == NACodecTypeInfo::None {
454 oopts.enc_params.format = istr.get_info().get_properties();
456 if oopts.enc_params.tb_num == 0 {
457 oopts.enc_params.tb_num = istr.tb_num;
458 oopts.enc_params.tb_den = istr.tb_den;
460 let ret_eparams = encoder.negotiate_format(&oopts.enc_params);
461 if ret_eparams.is_err() {
462 println!("cannot negotiate encoding parameters");
465 let ret_eparams = ret_eparams.unwrap();
467 //todo check for params mismatch
468 let cvt = match (&oopts.enc_params.format, &ret_eparams.format) {
469 (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => {
470 if svinfo == dvinfo && !forced_out {
473 let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height };
474 let ret = NAScale::new_with_options(ofmt, ofmt, &self.scale_opts);
476 println!("cannot create scaler");
479 let scaler = ret.unwrap();
480 let ret = alloc_video_buffer(*dvinfo, 4);
482 println!("cannot create scaler buffer");
485 let cvt_buf = ret.unwrap();
486 OutputConvert::Video(scaler, cvt_buf)
489 (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => {
490 if sainfo == dainfo {
493 let dchmap = match dainfo.channels {
494 1 => NAChannelMap::from_ms_mapping(0x4),
495 2 => NAChannelMap::from_ms_mapping(0x3),
497 println!("can't generate default channel map for {} channels", dainfo.channels);
502 OutputConvert::Audio(*dainfo, dchmap)
505 _ => OutputConvert::None,
507 let ret = encoder.init(out_id, ret_eparams);
509 println!("error initialising encoder");
512 out_sm.add_stream_ref(ret.unwrap());
514 let name = format!("output stream {}", out_id);
515 parse_and_apply_options!(encoder, &oopts.enc_opts, name);
517 self.encoders.push(OutputMode::Encode(out_id, encoder, cvt));
519 println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name());
522 } else if cname == "any" || istr.get_info().get_name() == cname {
523 out_sm.add_stream_ref(istr);
524 self.encoders.push(OutputMode::Copy(out_id));
526 println!("stream {} ({}) can't be handled", istr.id, istr.get_info().get_name());
527 // todo autoselect encoder?
532 fn map_single(&mut self, cname: &str, ctype: StreamType, src_sm: &StreamManager, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
533 let mut found_stream = false;
534 for istr in src_sm.iter() {
535 if istr.get_media_type() != ctype || found_stream {
536 self.encoders.push(OutputMode::Drop);
538 if !self.register_output_stream(cname, istr, out_sm, enc_reg) {
546 fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
548 MuxerCapabilities::SingleVideo(cname) => {
549 if self.no_video { return false; }
550 self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg)
552 MuxerCapabilities::SingleAudio(cname) => {
553 if self.no_audio { return false; }
554 self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg)
556 MuxerCapabilities::SingleVideoAndAudio(vname, aname) => {
557 let mut found_vid = false;
558 let mut found_aud = false;
559 for istr in src_sm.iter() {
560 if istr.get_media_type() == StreamType::Video && !found_vid && !self.no_video {
561 if !self.register_output_stream(vname, istr, out_sm, enc_reg) {
565 } else if istr.get_media_type() == StreamType::Audio && !found_aud && !self.no_audio {
566 if !self.register_output_stream(aname, istr, out_sm, enc_reg) {
571 self.encoders.push(OutputMode::Drop);
574 found_vid | found_aud
576 MuxerCapabilities::OnlyVideo => {
577 if self.no_video { return false; }
579 let mut found_vid = false;
580 for istr in src_sm.iter() {
581 if istr.get_media_type() == StreamType::Video && !found_vid {
582 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
587 self.encoders.push(OutputMode::Drop);
592 MuxerCapabilities::OnlyAudio => {
593 if self.no_audio { return false; }
595 let mut found_aud = false;
596 for istr in src_sm.iter() {
597 if istr.get_media_type() == StreamType::Audio && !found_aud {
598 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
603 self.encoders.push(OutputMode::Drop);
608 MuxerCapabilities::Universal => {
609 for istr in src_sm.iter() {
610 if (istr.get_media_type() == StreamType::Video && self.no_video) ||
611 (istr.get_media_type() == StreamType::Audio && self.no_audio) {
612 self.encoders.push(OutputMode::Drop);
615 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
625 fn encode_frame(dst_id: u32, encoder: &mut Box<dyn NAEncoder>, cvt: &mut OutputConvert, frm: NAFrameRef, scale_opts: &[(String, String)]) -> bool {
626 let buf = frm.get_buffer();
627 let cbuf = match cvt {
628 OutputConvert::None => buf,
629 OutputConvert::Video(ref mut scaler, ref mut dbuf) => {
630 let cur_ifmt = get_scale_fmt_from_pic(&buf);
631 let last_ifmt = scaler.get_in_fmt();
632 if cur_ifmt != last_ifmt {
633 let ofmt = scaler.get_out_fmt();
634 let ret = NAScale::new_with_options(cur_ifmt, ofmt, scale_opts);
636 println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt);
639 *scaler = ret.unwrap();
641 let ret = scaler.convert(&buf, dbuf);
643 println!("error converting frame for encoding");
648 OutputConvert::Audio(ref dinfo, ref dchmap) => {
649 let ret = convert_audio_frame(&buf, dinfo, dchmap);
651 println!("error converting audio for stream {}", dst_id);
657 let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf);
658 encoder.encode(&cfrm).unwrap();
662 macro_rules! next_arg {
663 ($args: expr, $arg_idx: expr) => {
664 if $arg_idx + 1 >= $args.len() {
665 println!("codec name is required");
671 #[allow(clippy::single_match)]
673 let args: Vec<_> = env::args().collect();
676 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
677 println!(" use nihav-encoder --help to list all available options");
680 if args.len() == 2 && (args[1] == "--help" || args[1] == "-h") {
681 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
682 println!(" query options:");
683 println!(" --list-{{decoders,encoders,demuxers,muxers}} - lists all available decoders/encoders/demuxers/muxers");
684 println!(" --query-{{decoder,encoder,demuxer,muxer}}-options name - lists all options recognized by that decoder/encoder/demuxer/muxer");
685 println!(" processing options:");
686 println!(" --input inputfile - set input file");
687 println!(" --input-format fmt - force input format");
688 println!(" --demuxer-options options - set input demuxer options");
689 println!(" --scale-options options - set scaler options");
690 println!(" --output outputfile - set output file");
691 println!(" --output-format fmt - force output format");
692 println!(" --muxer-options options - set output muxer options");
693 println!(" --no-audio - do not decode audio streams");
694 println!(" --no-video - do not decode video streams");
695 println!(" --start starttime - start decoding from given position");
696 println!(" --end endtime - end decoding at given position");
697 println!(" --istreamX options - set options for input stream X");
698 println!(" --ostreamX options - set options for output stream X");
700 println!(" (de)muxer and stream options are passed as comma-separated list e.g. --ostream0 width=320,height=240,flip");
704 let mut dmx_reg = RegisteredDemuxers::new();
705 nihav_register_all_demuxers(&mut dmx_reg);
706 let mut dec_reg = RegisteredDecoders::new();
707 nihav_register_all_decoders(&mut dec_reg);
709 let mut mux_reg = RegisteredMuxers::new();
710 nihav_register_all_muxers(&mut mux_reg);
711 mux_reg.add_muxer(NULL_MUXER);
712 let mut enc_reg = RegisteredEncoders::new();
713 nihav_register_all_encoders(&mut enc_reg);
714 enc_reg.add_encoder(NULL_ENCODER);
716 let mut transcoder = Transcoder::new();
719 let mut printed_info = false;
720 while arg_idx < args.len() {
721 match args[arg_idx].as_str() {
722 "--list-decoders" => {
723 if dec_reg.iter().len() > 0 {
724 println!("Registered decoders:");
725 for dec in dec_reg.iter() {
726 let cdesc = register::get_codec_description(dec.name);
727 let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" };
728 println!(" {} ({})", dec.name, full_name);
731 println!("No registered decoders.");
735 "--list-encoders" => {
736 if enc_reg.iter().len() > 0 {
737 println!("Registered encoders:");
738 for enc in enc_reg.iter() {
739 let cdesc = register::get_codec_description(enc.name);
740 let full_name = if let Some(cd) = cdesc { cd.get_full_name() } else { "???" };
741 println!(" {} ({})", enc.name, full_name);
744 println!("No registered encoders.");
748 "--list-demuxers" => {
749 print!("Registered demuxers:");
750 for dmx in dmx_reg.iter() {
751 print!(" {}", dmx.get_name());
757 print!("Registered muxers:");
758 for mux in mux_reg.iter() {
759 print!(" {}", mux.get_name());
764 "--query-decoder-options" => {
765 next_arg!(args, arg_idx);
766 let cname = args[arg_idx].as_str();
767 if let Some(decfunc) = dec_reg.find_decoder(cname) {
768 let dec = (decfunc)();
769 let opts = dec.get_supported_options();
770 print_options(cname, opts);
772 println!("codec {} is not found", cname);
776 "--query-demuxer-options" => {
777 next_arg!(args, arg_idx);
778 let dname = args[arg_idx].as_str();
779 let mut mr = MemoryReader::new_read(&[]);
780 let mut br = ByteReader::new(&mut mr);
781 if let Some(dmx_creator) = dmx_reg.find_demuxer(dname) {
782 let dmx = dmx_creator.new_demuxer(&mut br);
783 let opts = dmx.get_supported_options();
784 print_options(dname, opts);
786 println!("demuxer {} is not found", dname);
790 "--query-encoder-options" => {
791 next_arg!(args, arg_idx);
792 let cname = args[arg_idx].as_str();
793 if let Some(encfunc) = enc_reg.find_encoder(cname) {
794 let enc = (encfunc)();
795 let opts = enc.get_supported_options();
796 print_options(cname, opts);
798 println!("codec {} is not found", cname);
802 "--query-muxer-options" => {
803 next_arg!(args, arg_idx);
804 let name = args[arg_idx].as_str();
806 let mut mw = MemoryWriter::new_write(&mut data);
807 let mut bw = ByteWriter::new(&mut mw);
808 if let Some(mux_creator) = mux_reg.find_muxer(name) {
809 let mux = mux_creator.new_muxer(&mut bw);
810 let opts = mux.get_supported_options();
811 print_options(name, opts);
813 println!("muxer {} is not found", name);
817 "--input" | "-i" => {
818 next_arg!(args, arg_idx);
819 transcoder.input_name = args[arg_idx].clone();
821 "--input-format" => {
822 next_arg!(args, arg_idx);
823 transcoder.input_fmt = Some(args[arg_idx].clone());
825 "--output" | "-o" => {
826 next_arg!(args, arg_idx);
827 transcoder.output_name = args[arg_idx].clone();
829 "--output-format" => {
830 next_arg!(args, arg_idx);
831 transcoder.output_fmt = Some(args[arg_idx].clone());
833 "--demuxer-options" => {
834 next_arg!(args, arg_idx);
835 if !transcoder.parse_demuxer_options(&args[arg_idx], &dmx_reg) {
836 println!("invalid demuxer option syntax");
840 "--scale-options" => {
841 next_arg!(args, arg_idx);
842 if !transcoder.parse_scale_options(&args[arg_idx]) {
843 println!("invalid scale option syntax");
847 "--no-video" | "-vn" => {
848 transcoder.no_video = true;
850 "--no-audio" | "-an" => {
851 transcoder.no_audio = true;
854 next_arg!(args, arg_idx);
855 let ret = args[arg_idx].parse::<NATimePoint>();
856 if let Ok(val) = ret {
857 transcoder.start = val;
859 println!("invalid start time");
864 next_arg!(args, arg_idx);
865 let ret = args[arg_idx].parse::<NATimePoint>();
866 if let Ok(val) = ret {
867 transcoder.end = val;
869 println!("invalid end time");
873 "--muxer-options" => {
874 next_arg!(args, arg_idx);
875 if !transcoder.parse_muxer_options(&args[arg_idx], &mux_reg) {
876 println!("invalid muxer option syntax");
881 if args[arg_idx].starts_with("--istream") {
882 let opt0 = &args[arg_idx];
883 next_arg!(args, arg_idx);
884 if !transcoder.parse_istream_options(opt0, &args[arg_idx]) {
885 println!("invalid input stream option syntax");
888 } else if args[arg_idx].starts_with("--ostream") {
889 let opt0 = &args[arg_idx];
890 next_arg!(args, arg_idx);
891 if !transcoder.parse_ostream_options(opt0, &args[arg_idx], &enc_reg) {
892 println!("invalid output stream option syntax");
895 } else if args[arg_idx].starts_with("--") {
896 println!("unknown option");
898 println!("unrecognized argument");
909 if transcoder.input_name.is_empty() {
910 println!("no input name provided");
913 if transcoder.output_name.is_empty() {
914 println!("no output name provided");
918 let res = File::open(transcoder.input_name.as_str());
920 println!("error opening input");
923 let mut file = res.unwrap();
924 let mut fr = FileReader::new_read(&mut file);
925 let mut br = ByteReader::new(&mut fr);
927 let dmx_name = if let Some(ref str) = transcoder.input_fmt {
929 } else if let Some((dmx_name, score)) = detect::detect_format(transcoder.input_name.as_str(), &mut br) {
930 println!("detected {} with score {:?}", dmx_name, score);
933 println!("cannot detect input format");
936 let ret = dmx_reg.find_demuxer(dmx_name);
938 println!("cannot find demuxer for '{}'", dmx_name);
941 let dmx_fact = ret.unwrap();
942 br.seek(SeekFrom::Start(0)).unwrap();
943 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
944 parse_and_apply_options!(dmx, &transcoder.demux_opts, "input");
945 for i in 0..dmx.get_num_streams() {
946 let s = dmx.get_stream(i).unwrap();
947 let info = s.get_info();
948 let decfunc = dec_reg.find_decoder(info.get_name());
949 println!("stream {} - {} {}", i, s, info.get_name());
950 let str_id = s.get_num() as u32;
951 if let Some(create_dec) = decfunc {
952 let mut dec = (create_dec)();
953 let mut dsupp = Box::new(NADecoderSupport::new());
954 let ret = dec.init(&mut dsupp, info.clone());
956 println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id);
959 transcoder.apply_decoder_options(dec.as_mut(), str_id);
960 let desc = register::get_codec_description(info.get_name());
961 let has_b = if let Some(desc) = desc {
964 println!("No codec description found, using B-frame reorderer.");
967 let reord: Box<dyn FrameReorderer> = if has_b { Box::new(IPBReorderer::new()) } else { Box::new(NoReorderer::new()) };
968 transcoder.decoders.push(Some((dsupp, dec, reord)));
970 println!("No decoder for stream {} ({}) is found", str_id, info.get_name());
971 transcoder.decoders.push(None);
974 if transcoder.start != NATimePoint::None {
975 let ret = dmx.seek(transcoder.start);
977 println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap());
981 let output_fmt = if let Some(ref str) = transcoder.output_fmt {
983 } else if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) {
986 println!("Cannot guess muxer for output");
989 let ret = mux_reg.find_muxer(output_fmt);
990 let ofmt = output_fmt.to_string();
993 println!("cannot find muxer '{}'", output_fmt);
995 let mux_creator = ret.unwrap();
997 let mux_caps = mux_creator.get_capabilities();
998 let mut out_sm = StreamManager::new();
999 if !transcoder.negotiate_stream_map(dmx.get_stream_manager(), mux_caps, &mut out_sm, &enc_reg) {
1000 println!("cannot determine stream map");
1004 let ret = File::create(transcoder.output_name.as_str());
1006 println!("cannot open output file");
1009 let mut fw = FileWriter::new_write(ret.unwrap());
1010 let mut bw = ByteWriter::new(&mut fw);
1011 let ret = create_muxer(mux_creator, out_sm, &mut bw);
1012 if let Err(err) = ret {
1013 println!("cannot create muxer instance {:?}", err);
1016 let mut mux = ret.unwrap();
1017 parse_and_apply_options!(mux, &transcoder.mux_opts, "output");
1019 println!("Output {} muxer {}", transcoder.output_name, ofmt);
1020 for ostr in mux.get_streams() {
1021 println!(" #{}: {} {}", ostr.get_num(), ostr, ostr.get_info().get_name());
1025 let pktres = dmx.get_frame();
1026 if let Err(DemuxerError::EOF) = pktres { break; }
1027 if pktres.is_err() {
1028 println!("demuxing error");
1031 let mut pkt = pktres.unwrap();
1032 if transcoder.start != NATimePoint::None && pkt.ts.less_than(transcoder.start) { continue; }
1033 let src_id = pkt.get_stream().get_num();
1034 match transcoder.encoders[src_id] {
1035 OutputMode::Drop => {},
1036 OutputMode::Copy(dst_id) => {
1037 let dstr = mux.get_stream(dst_id as usize).unwrap();
1038 pkt.reassign(dstr, pkt.get_time_information());
1039 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1040 if mux.mux_frame(pkt).is_err() {
1041 println!("error muxing packet");
1045 OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) => {
1046 if let Some((ref mut dsupp, ref mut decoder, ref mut reorderer)) = transcoder.decoders[src_id] {
1047 let ret = decoder.decode(dsupp, &pkt);
1048 if let (true, Err(DecoderError::MissingReference)) = (transcoder.start != NATimePoint::None, &ret) {
1052 println!("error decoding stream {}", src_id);
1055 let frm = ret.unwrap();
1056 reorderer.add_frame(frm);
1057 while let Some(frm) = reorderer.get_frame() {
1058 if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) {
1061 while let Ok(Some(pkt)) = encoder.get_packet() {
1062 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
1063 mux.mux_frame(pkt).unwrap();
1067 println!("no decoder for stream {}", src_id);
1073 'reord_flush_loop: for str in dmx.get_streams() {
1074 let src_id = str.get_num();
1075 if let OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) = transcoder.encoders[src_id] {
1076 if let Some((_, _, ref mut reorderer)) = transcoder.decoders[src_id] {
1077 while let Some(frm) = reorderer.get_last_frames() {
1078 if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) {
1081 while let Ok(Some(pkt)) = encoder.get_packet() {
1082 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'reord_flush_loop; }
1083 mux.mux_frame(pkt).unwrap();
1089 'flush_loop: for enc in transcoder.encoders.iter_mut() {
1091 OutputMode::Encode(str_id, ref mut encoder, _) => {
1092 let ret = encoder.flush();
1094 println!("error flushing encoder for stream {}", str_id);
1097 while let Ok(Some(pkt)) = encoder.get_packet() {
1098 if mux.mux_frame(pkt).is_err() {
1099 println!("error muxing packet");
1109 let ret = mux.end();
1111 println!("error at finalising muxing");