]> git.nihav.org Git - nihav-encoder.git/blob - src/main.rs
6b9086f08913a4a15023ffcdb51fb31342c7185c
[nihav-encoder.git] / src / main.rs
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 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::*;
19 use std::env;
20
21 mod null;
22 use crate::null::*;
23
24 fn print_options(name: &str, options: &[NAOptionDefinition]) {
25 if options.is_empty() {
26 println!("No custom options.");
27 } else {
28 println!("Options for '{}'", name);
29 for opt in options.iter() {
30 println!(" {}", opt);
31 }
32 }
33 }
34
35 struct OptionArgs {
36 name: String,
37 value: Option<String>,
38 }
39
40 struct InputStreamOptions {
41 id: u32,
42 drop: bool,
43 dec_opts: Vec<OptionArgs>,
44 }
45
46 struct OutputStreamOptions {
47 id: u32,
48 enc_params: EncodeParameters,
49 enc_name: String,
50 enc_opts: Vec<OptionArgs>,
51 }
52
53 enum OutputConvert {
54 Video(NAScale, NABufferType),
55 Audio(NAAudioInfo, NAChannelMap),
56 None,
57 }
58
59 enum OutputMode {
60 Drop,
61 Copy(u32),
62 Encode(u32, Box<dyn NAEncoder>, OutputConvert),
63 }
64
65 #[derive(Default)]
66 struct Transcoder {
67 input_name: String,
68 input_fmt: Option<String>,
69 output_name: 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>,
77 no_video: bool,
78 no_audio: bool,
79 start: NATimePoint,
80 end: NATimePoint,
81 }
82
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);
93 if ret.is_err() {
94 println!("invalid option {} for {}", opt.name, $name);
95 } else {
96 let (val, _) = ret.unwrap();
97 opts.push(val);
98 }
99 found = true;
100 }
101 }
102 if !found {
103 println!(" ignoring option '{}' for {}", opt.name, $name);
104 }
105 }
106 $obj.set_options(opts.as_slice());
107 }
108 }
109
110 impl Transcoder {
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();
117
118 let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) {
119 idx
120 } else {
121 self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() });
122 self.istr_opts.len() - 1
123 };
124 let istr = &mut self.istr_opts[sidx];
125
126 for opt in opt1.split(',') {
127 let oval: Vec<_> = opt.split('=').collect();
128 if oval.len() == 1 {
129 match oval[0] {
130 "drop" => { istr.drop = true; },
131 _ => {
132 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
133 },
134 };
135 } else if oval.len() == 2 {
136 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
137 } else {
138 println!("unrecognized option '{}'", opt);
139 }
140 }
141 true
142 }
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();
148
149 let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) {
150 idx
151 } else {
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
154 };
155 let ostr = &mut self.ostr_opts[sidx];
156
157 for opt in opt1.split(',') {
158 let oval: Vec<_> = opt.split('=').collect();
159 if oval.len() == 1 {
160 match oval[0] {
161 "flip" => {
162 if ostr.enc_params.format == NACodecTypeInfo::None {
163 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
164 }
165 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
166 vinfo.flipped = true;
167 } else {
168 println!("video option for audio stream");
169 }
170 },
171 "noflip" => {
172 if ostr.enc_params.format == NACodecTypeInfo::None {
173 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
174 }
175 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
176 vinfo.flipped = false;
177 } else {
178 println!("video option for audio stream");
179 }
180 },
181 _ => {
182 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
183 },
184 };
185 } else if oval.len() == 2 {
186 //todo parse encoder options, store, init later
187 match oval[0] {
188 "timebase" => {
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;
198 } else {
199 println!("invalid timebase value");
200 }
201 } else {
202 println!("invalid timebase format (should be num/den)");
203 }
204 },
205 "encoder" => {
206 if enc_reg.find_encoder(oval[1]).is_some() {
207 ostr.enc_name = oval[1].to_string();
208 } else {
209 println!("unknown encoder '{}'", oval[1]);
210 ostr.enc_name = oval[1].to_string();
211 }
212 },
213 "width" => {
214 if ostr.enc_params.format == NACodecTypeInfo::None {
215 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
216 }
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 {
220 vinfo.width = val;
221 } else {
222 println!("invalid width");
223 }
224 } else {
225 println!("video option for audio stream");
226 }
227 },
228 "height" => {
229 if ostr.enc_params.format == NACodecTypeInfo::None {
230 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
231 }
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 {
235 vinfo.height = val;
236 } else {
237 println!("invalid height");
238 }
239 } else {
240 println!("video option for audio stream");
241 }
242 },
243 "pixfmt" => {
244 if ostr.enc_params.format == NACodecTypeInfo::None {
245 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
246 }
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 {
250 vinfo.format = val;
251 } else {
252 println!("invalid pixel format");
253 }
254 } else {
255 println!("video option for audio stream");
256 }
257 },
258 "srate" => {
259 if ostr.enc_params.format == NACodecTypeInfo::None {
260 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
261 }
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;
266 } else {
267 println!("invalid sampling rate");
268 }
269 } else {
270 println!("audio option for video stream");
271 }
272 },
273 "channels" => {
274 if ostr.enc_params.format == NACodecTypeInfo::None {
275 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
276 }
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;
281 } else {
282 println!("invalid number of channels");
283 }
284 } else {
285 println!("audio option for video stream");
286 }
287 },
288 "block_len" => {
289 if ostr.enc_params.format == NACodecTypeInfo::None {
290 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
291 }
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;
296 } else {
297 println!("invalid block_length");
298 }
299 } else {
300 println!("audio option for video stream");
301 }
302 },
303 "sfmt" => {
304 if ostr.enc_params.format == NACodecTypeInfo::None {
305 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
306 }
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 {
310 ainfo.format = val;
311 } else {
312 println!("invalid audio format");
313 }
314 } else {
315 println!("audio option for video stream");
316 }
317 },
318 // todo channel map negotiation
319 /*"chmap" => {
320 if ostr.enc_params.format == NACodecTypeInfo::None {
321 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
322 }
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 {
326 ainfo.chmap = val;
327 } else {
328 println!("invalid channel map");
329 }
330 } else {
331 println!("audio option for video stream");
332 }
333 },*/
334 "bitrate" => {
335 let ret = oval[1].parse::<u32>();
336 if let Ok(val) = ret {
337 ostr.enc_params.bitrate = val;
338 } else {
339 println!("invalid bitrate value");
340 }
341 },
342 "quality" => {
343 let ret = oval[1].parse::<u8>();
344 if let Ok(val) = ret {
345 ostr.enc_params.quality = val;
346 } else {
347 println!("invalid quality value");
348 }
349 },
350 _ => {
351 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
352 },
353 }
354 } else {
355 println!("unrecognized option '{}'", opt);
356 }
357 }
358 true
359 }
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();
363 if oval.len() == 1 {
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());
369 } else {
370 println!("unknown demuxer format '{}'", oval[1]);
371 }
372 } else {
373 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
374 }
375 } else {
376 println!("unrecognized option '{}'", opt);
377 }
378 }
379 true
380 }
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();
384 if oval.len() == 1 {
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());
390 } else {
391 println!("unknown muxer format '{}'", oval[1]);
392 }
393 } else {
394 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
395 }
396 } else {
397 println!("unrecognized option '{}'", opt);
398 }
399 }
400 true
401 }
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);
408 }
409 }
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);
415 return true;
416 }
417 }
418
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());
428 return false;
429 }
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();
434 }
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;
438 }
439 let ret_eparams = encoder.negotiate_format(&oopts.enc_params);
440 if ret_eparams.is_err() {
441 println!("cannot negotiate encoding parameters");
442 return false;
443 }
444 let ret_eparams = ret_eparams.unwrap();
445
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 {
450 OutputConvert::None
451 } else {
452 let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height };
453 let ret = NAScale::new(ofmt, ofmt);
454 if ret.is_err() {
455 println!("cannot create scaler");
456 return false;
457 }
458 let scaler = ret.unwrap();
459 let ret = alloc_video_buffer(*dvinfo, 4);
460 if ret.is_err() {
461 println!("cannot create scaler buffer");
462 return false;
463 }
464 let cvt_buf = ret.unwrap();
465 OutputConvert::Video(scaler, cvt_buf)
466 }
467 },
468 (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => {
469 if sainfo == dainfo {
470 OutputConvert::None
471 } else {
472 let dchmap = match dainfo.channels {
473 1 => NAChannelMap::from_ms_mapping(0x4),
474 2 => NAChannelMap::from_ms_mapping(0x3),
475 _ => {
476 println!("can't generate default channel map for {} channels", dainfo.channels);
477 return false;
478 },
479 };
480 //todo channelmap
481 OutputConvert::Audio(*dainfo, dchmap)
482 }
483 },
484 _ => OutputConvert::None,
485 };
486 let ret = encoder.init(out_id, ret_eparams);
487 if ret.is_err() {
488 println!("error initialising encoder");
489 return false;
490 }
491 out_sm.add_stream_ref(ret.unwrap());
492
493 let name = format!("output stream {}", out_id);
494 parse_and_apply_options!(encoder, &oopts.enc_opts, name);
495
496 self.encoders.push(OutputMode::Encode(out_id, encoder, cvt));
497 } else {
498 println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name());
499 return false;
500 }
501 } else {
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));
505 } else {
506 println!("stream {} ({}) can't be handled", istr.id, istr.get_info().get_name());
507 // todo autoselect encoder?
508 return false;
509 }
510 }
511 true
512 }
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);
518 } else {
519 if !self.register_output_stream(cname, istr, out_sm, enc_reg) {
520 return false;
521 }
522 found_stream = true;
523 }
524 }
525 found_stream
526 }
527 fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
528 match mux_caps {
529 MuxerCapabilities::SingleVideo(cname) => {
530 if self.no_video { return false; }
531 self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg)
532 },
533 MuxerCapabilities::SingleAudio(cname) => {
534 if self.no_audio { return false; }
535 self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg)
536 },
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) {
543 return false;
544 }
545 found_vid = true;
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) {
548 return false;
549 }
550 found_aud = true;
551 } else {
552 self.encoders.push(OutputMode::Drop);
553 }
554 }
555 found_vid | found_aud
556 },
557 MuxerCapabilities::OnlyVideo => {
558 if self.no_video { return false; }
559
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) {
564 return false;
565 }
566 found_vid = true;
567 } else {
568 self.encoders.push(OutputMode::Drop);
569 }
570 }
571 found_vid
572 },
573 MuxerCapabilities::OnlyAudio => {
574 if self.no_audio { return false; }
575
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) {
580 return false;
581 }
582 found_aud = true;
583 } else {
584 self.encoders.push(OutputMode::Drop);
585 }
586 }
587 found_aud
588 },
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);
594 continue;
595 }
596 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
597 return false;
598 }
599 }
600 true
601 },
602 }
603 }
604 }
605
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);
616 if ret.is_err() {
617 println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt);
618 return false;
619 }
620 *scaler = ret.unwrap();
621 }
622 let ret = scaler.convert(&buf, dbuf);
623 if ret.is_err() {
624 println!("error converting frame for encoding");
625 return false;
626 }
627 dbuf.clone()
628 },
629 OutputConvert::Audio(ref dinfo, ref dchmap) => {
630 let ret = convert_audio_frame(&buf, dinfo, dchmap);
631 if ret.is_err() {
632 println!("error converting audio for stream {}", dst_id);
633 return false;
634 }
635 ret.unwrap()
636 },
637 };
638 let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf);
639 encoder.encode(&cfrm).unwrap();
640 true
641 }
642
643 macro_rules! next_arg {
644 ($args: expr, $arg_idx: expr) => {
645 if $arg_idx + 1 >= $args.len() {
646 println!("codec name is required");
647 }
648 $arg_idx += 1;
649 }
650 }
651
652 fn main() {
653 let args: Vec<_> = env::args().collect();
654
655 if args.len() == 1 {
656 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
657 println!(" use nihav-encoder --help to list all available options");
658 return;
659 }
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");
678 println!();
679 println!(" (de)muxer and stream options are passed as comma-separated list e.g. --ostream0 width=320,height=240,flip");
680 return;
681 }
682
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);
687
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);
694
695 let mut transcoder = Transcoder::new();
696
697 let mut arg_idx = 1;
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);
708 }
709 } else {
710 println!("No registered decoders.");
711 }
712 printed_info = true;
713 },
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);
721 }
722 } else {
723 println!("No registered encoders.");
724 }
725 printed_info = true;
726 },
727 "--list-demuxers" => {
728 print!("Registered demuxers:");
729 for dmx in dmx_reg.iter() {
730 print!(" {}", dmx.get_name());
731 }
732 println!();
733 printed_info = true;
734 },
735 "--list-muxers" => {
736 print!("Registered muxers:");
737 for mux in mux_reg.iter() {
738 print!(" {}", mux.get_name());
739 }
740 println!();
741 printed_info = true;
742 },
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);
750 } else {
751 println!("codec {} is not found", cname);
752 }
753 printed_info = true;
754 },
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);
764 } else {
765 println!("demuxer {} is not found", dname);
766 }
767 printed_info = true;
768 },
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);
776 } else {
777 println!("codec {} is not found", cname);
778 }
779 printed_info = true;
780 },
781 "--query-muxer-options" => {
782 next_arg!(args, arg_idx);
783 let name = args[arg_idx].as_str();
784 let mut data = [];
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);
791 } else {
792 println!("muxer {} is not found", name);
793 }
794 printed_info = true;
795 },
796 "--input" | "-i" => {
797 next_arg!(args, arg_idx);
798 transcoder.input_name = args[arg_idx].clone();
799 },
800 "--input-format" => {
801 next_arg!(args, arg_idx);
802 transcoder.input_fmt = Some(args[arg_idx].clone());
803 },
804 "--output" | "-o" => {
805 next_arg!(args, arg_idx);
806 transcoder.output_name = args[arg_idx].clone();
807 },
808 "--output-format" => {
809 next_arg!(args, arg_idx);
810 transcoder.output_fmt = Some(args[arg_idx].clone());
811 },
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");
816 return;
817 }
818 },
819 "--no-video" | "-vn" => {
820 transcoder.no_video = true;
821 },
822 "--no-audio" | "-an" => {
823 transcoder.no_audio = true;
824 },
825 "--start" => {
826 next_arg!(args, arg_idx);
827 let ret = args[arg_idx].parse::<NATimePoint>();
828 if let Ok(val) = ret {
829 transcoder.start = val;
830 } else {
831 println!("invalid start time");
832 return;
833 }
834 },
835 "--end" => {
836 next_arg!(args, arg_idx);
837 let ret = args[arg_idx].parse::<NATimePoint>();
838 if let Ok(val) = ret {
839 transcoder.end = val;
840 } else {
841 println!("invalid end time");
842 return;
843 }
844 },
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");
849 return;
850 }
851 },
852 _ => {
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");
858 return;
859 }
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");
865 return;
866 }
867 } else if args[arg_idx].starts_with("--") {
868 println!("unknown option");
869 } else {
870 println!("unrecognized argument");
871 }
872 },
873 };
874 arg_idx += 1;
875 }
876
877 if printed_info {
878 return;
879 }
880
881 if transcoder.input_name.len() == 0 {
882 println!("no input name provided");
883 return;
884 }
885 if transcoder.output_name.len() == 0 {
886 println!("no output name provided");
887 return;
888 }
889
890 let res = File::open(transcoder.input_name.as_str());
891 if res.is_err() {
892 println!("error opening input");
893 return;
894 }
895 let mut file = res.unwrap();
896 let mut fr = FileReader::new_read(&mut file);
897 let mut br = ByteReader::new(&mut fr);
898
899 let dmx_name = if let Some(ref str) = transcoder.input_fmt {
900 str.as_str()
901 } else {
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);
904 dmx_name
905 } else {
906 println!("cannot detect input format");
907 return;
908 }
909 };
910 let ret = dmx_reg.find_demuxer(dmx_name);
911 if ret.is_none() {
912 println!("cannot find demuxer for '{}'", dmx_name);
913 return;
914 }
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());
929 if ret.is_err() {
930 println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id);
931 return;
932 }
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 {
936 desc.has_reorder()
937 } else {
938 println!("No codec description found, using B-frame reorderer.");
939 true
940 };
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)));
943 } else {
944 println!("No decoder for stream {} ({}) is found", str_id, info.get_name());
945 transcoder.decoders.push(None);
946 }
947 }
948 if transcoder.start != NATimePoint::None {
949 let ret = dmx.seek(transcoder.start);
950 if ret.is_err() {
951 println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap());
952 }
953 }
954
955 let output_fmt = if let Some(ref str) = transcoder.output_fmt {
956 str
957 } else {
958 if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) {
959 str
960 } else {
961 println!("Cannot guess muxer for output");
962 return;
963 }
964 };
965 let ret = mux_reg.find_muxer(output_fmt);
966 let ofmt = output_fmt.to_string();
967
968 if ret.is_none() {
969 println!("cannot find muxer '{}'", output_fmt);
970 }
971 let mux_creator = ret.unwrap();
972
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");
977 return;
978 }
979
980 let ret = File::create(transcoder.output_name.as_str());
981 if ret.is_err() {
982 println!("cannot open output file");
983 return;
984 }
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);
990 return;
991 }
992 let mut mux = ret.unwrap();
993 parse_and_apply_options!(mux, &transcoder.mux_opts, "output");
994
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());
998 }
999
1000 'main_loop: loop {
1001 let pktres = dmx.get_frame();
1002 if let Err(DemuxerError::EOF) = pktres { break; }
1003 if pktres.is_err() {
1004 println!("demuxing error");
1005 break;
1006 }
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");
1018 break;
1019 }
1020 },
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) {
1025 continue;
1026 }
1027 if ret.is_err() {
1028 println!("error decoding stream {}", src_id);
1029 break;
1030 }
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) {
1035 break;
1036 }
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();
1040 }
1041 }
1042 } else {
1043 println!("no decoder for stream {}", src_id);
1044 break;
1045 }
1046 },
1047 };
1048 }
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) {
1055 break;
1056 }
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();
1060 }
1061 }
1062 }
1063 }
1064 }
1065 'flush_loop: for enc in transcoder.encoders.iter_mut() {
1066 match enc {
1067 OutputMode::Encode(str_id, ref mut encoder, _) => {
1068 let ret = encoder.flush();
1069 if ret.is_err() {
1070 println!("error flushing encoder for stream {}", str_id);
1071 break;
1072 } else {
1073 while let Ok(Some(pkt)) = encoder.get_packet() {
1074 if mux.mux_frame(pkt).is_err() {
1075 println!("error muxing packet");
1076 break 'flush_loop;
1077 }
1078 }
1079 }
1080 },
1081 _ => {},
1082 };
1083 }
1084
1085 let ret = mux.end();
1086 if ret.is_err() {
1087 println!("error at finalising muxing");
1088 }
1089 }