]> git.nihav.org Git - nihav-encoder.git/blame - src/main.rs
support scale options
[nihav-encoder.git] / src / main.rs
CommitLineData
6dc69f51
KS
1extern crate nihav_core;
2extern crate nihav_codec_support;
3extern crate nihav_registry;
4extern crate nihav_allstuff;
5
6use std::fs::File;
7use nihav_core::io::byteio::{FileReader, ByteReader};
8use nihav_core::frame::*;
9use nihav_core::options::*;
10use nihav_core::codecs::*;
11use nihav_core::demuxers::*;
12use nihav_core::muxers::*;
d9fe2b71 13use nihav_core::reorder::*;
6dc69f51
KS
14use nihav_core::scale::*;
15use nihav_core::soundcvt::*;
16use nihav_registry::detect;
e6cb09af 17use nihav_registry::register;
6dc69f51
KS
18use nihav_allstuff::*;
19use std::env;
20
93521506 21mod null;
b267d37e 22use crate::null::*;
93521506 23
6dc69f51
KS
24fn 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
35struct OptionArgs {
36 name: String,
37 value: Option<String>,
38}
39
40struct InputStreamOptions {
41 id: u32,
42 drop: bool,
43 dec_opts: Vec<OptionArgs>,
44}
45
46struct OutputStreamOptions {
47 id: u32,
48 enc_params: EncodeParameters,
49 enc_name: String,
50 enc_opts: Vec<OptionArgs>,
51}
52
53enum OutputConvert {
54 Video(NAScale, NABufferType),
55 Audio(NAAudioInfo, NAChannelMap),
56 None,
57}
58
86c54d88 59#[allow(clippy::large_enum_variant)]
6dc69f51
KS
60enum OutputMode {
61 Drop,
62 Copy(u32),
63 Encode(u32, Box<dyn NAEncoder>, OutputConvert),
64}
65
66#[derive(Default)]
86c54d88 67#[allow(clippy::type_complexity)]
6dc69f51
KS
68struct Transcoder {
69 input_name: String,
70 input_fmt: Option<String>,
71 output_name: 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>,
df37d3b1 77 scale_opts: Vec<(String, String)>,
d9fe2b71 78 decoders: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>, Box<dyn FrameReorderer>)>>,
6dc69f51
KS
79 encoders: Vec<OutputMode>,
80 no_video: bool,
81 no_audio: bool,
951916e8
KS
82 start: NATimePoint,
83 end: NATimePoint,
6dc69f51
KS
84}
85
86macro_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() {
3e2a4e88
KS
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;
97 }
98 if matches {
6dc69f51
KS
99 let arg = if let Some(ref str) = opt.value { Some(str) } else { None };
100 let ret = opt_def.parse(&opt.name, arg);
86c54d88 101 if let Ok((val, _)) = ret {
6dc69f51 102 opts.push(val);
86c54d88
KS
103 } else {
104 println!("invalid option {} for {}", opt.name, $name);
6dc69f51
KS
105 }
106 found = true;
107 }
108 }
109 if !found {
110 println!(" ignoring option '{}' for {}", opt.name, $name);
111 }
112 }
113 $obj.set_options(opts.as_slice());
114 }
115}
116
117impl Transcoder {
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();
124
125 let sidx = if let Some(idx) = self.istr_opts.iter().position(|str| str.id == streamno) {
126 idx
127 } else {
128 self.istr_opts.push(InputStreamOptions {id: streamno, drop: false, dec_opts: Vec::new() });
129 self.istr_opts.len() - 1
130 };
131 let istr = &mut self.istr_opts[sidx];
830c03a1 132
6dc69f51
KS
133 for opt in opt1.split(',') {
134 let oval: Vec<_> = opt.split('=').collect();
135 if oval.len() == 1 {
136 match oval[0] {
137 "drop" => { istr.drop = true; },
138 _ => {
139 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
140 },
141 };
142 } else if oval.len() == 2 {
143 istr.dec_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
144 } else {
145 println!("unrecognized option '{}'", opt);
146 }
147 }
148 true
149 }
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();
155
156 let sidx = if let Some(idx) = self.ostr_opts.iter().position(|str| str.id == streamno) {
157 idx
158 } else {
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
161 };
162 let ostr = &mut self.ostr_opts[sidx];
830c03a1 163
6dc69f51
KS
164 for opt in opt1.split(',') {
165 let oval: Vec<_> = opt.split('=').collect();
166 if oval.len() == 1 {
167 match oval[0] {
168 "flip" => {
169 if ostr.enc_params.format == NACodecTypeInfo::None {
170 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
171 }
172 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
173 vinfo.flipped = true;
174 } else {
175 println!("video option for audio stream");
176 }
177 },
178 "noflip" => {
179 if ostr.enc_params.format == NACodecTypeInfo::None {
180 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
181 }
182 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
183 vinfo.flipped = false;
184 } else {
185 println!("video option for audio stream");
186 }
187 },
188 _ => {
189 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: None });
190 },
191 };
192 } else if oval.len() == 2 {
193//todo parse encoder options, store, init later
194 match oval[0] {
ca3b31d7
KS
195 "timebase" => {
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;
205 } else {
206 println!("invalid timebase value");
207 }
208 } else {
209 println!("invalid timebase format (should be num/den)");
210 }
211 },
6dc69f51
KS
212 "encoder" => {
213 if enc_reg.find_encoder(oval[1]).is_some() {
214 ostr.enc_name = oval[1].to_string();
215 } else {
216 println!("unknown encoder '{}'", oval[1]);
c0052668 217 ostr.enc_name = oval[1].to_string();
6dc69f51
KS
218 }
219 },
220 "width" => {
221 if ostr.enc_params.format == NACodecTypeInfo::None {
222 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
223 }
224 if let NACodecTypeInfo::Video(ref mut vinfo) = ostr.enc_params.format {
225 let ret = oval[1].parse::<usize>();
226 if let Ok(val) = ret {
227 vinfo.width = val;
228 } else {
229 println!("invalid width");
230 }
231 } else {
232 println!("video option for audio stream");
233 }
234 },
235 "height" => {
236 if ostr.enc_params.format == NACodecTypeInfo::None {
237 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
238 }
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 {
242 vinfo.height = val;
243 } else {
244 println!("invalid height");
245 }
246 } else {
247 println!("video option for audio stream");
248 }
249 },
e176bfee
KS
250 "pixfmt" => {
251 if ostr.enc_params.format == NACodecTypeInfo::None {
252 ostr.enc_params.format = NACodecTypeInfo::Video(NAVideoInfo::new(0, 0, false, YUV420_FORMAT));
253 }
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 {
257 vinfo.format = val;
258 } else {
259 println!("invalid pixel format");
260 }
261 } else {
262 println!("video option for audio stream");
263 }
264 },
6dc69f51
KS
265 "srate" => {
266 if ostr.enc_params.format == NACodecTypeInfo::None {
267 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
268 }
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;
273 } else {
274 println!("invalid sampling rate");
275 }
276 } else {
277 println!("audio option for video stream");
278 }
279 },
280 "channels" => {
281 if ostr.enc_params.format == NACodecTypeInfo::None {
282 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
283 }
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;
288 } else {
289 println!("invalid number of channels");
290 }
291 } else {
292 println!("audio option for video stream");
293 }
294 },
295 "block_len" => {
296 if ostr.enc_params.format == NACodecTypeInfo::None {
297 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
298 }
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;
303 } else {
304 println!("invalid block_length");
305 }
306 } else {
307 println!("audio option for video stream");
308 }
309 },
e176bfee
KS
310 "sfmt" => {
311 if ostr.enc_params.format == NACodecTypeInfo::None {
312 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
313 }
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 {
317 ainfo.format = val;
318 } else {
319 println!("invalid audio format");
320 }
321 } else {
322 println!("audio option for video stream");
323 }
324 },
325// todo channel map negotiation
326 /*"chmap" => {
327 if ostr.enc_params.format == NACodecTypeInfo::None {
328 ostr.enc_params.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16_FORMAT, 0));
329 }
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 {
333 ainfo.chmap = val;
334 } else {
335 println!("invalid channel map");
336 }
337 } else {
338 println!("audio option for video stream");
339 }
340 },*/
6dc69f51
KS
341 "bitrate" => {
342 let ret = oval[1].parse::<u32>();
343 if let Ok(val) = ret {
344 ostr.enc_params.bitrate = val;
345 } else {
346 println!("invalid bitrate value");
347 }
348 },
349 "quality" => {
350 let ret = oval[1].parse::<u8>();
351 if let Ok(val) = ret {
352 ostr.enc_params.quality = val;
353 } else {
354 println!("invalid quality value");
355 }
356 },
357 _ => {
358 ostr.enc_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
359 },
360 }
361 } else {
362 println!("unrecognized option '{}'", opt);
363 }
364 }
365 true
366 }
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();
370 if oval.len() == 1 {
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());
376 } else {
377 println!("unknown demuxer format '{}'", oval[1]);
378 }
379 } else {
380 self.demux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
381 }
382 } else {
383 println!("unrecognized option '{}'", opt);
384 }
385 }
386 true
387 }
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();
391 if oval.len() == 1 {
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());
397 } else {
398 println!("unknown muxer format '{}'", oval[1]);
399 }
400 } else {
401 self.mux_opts.push(OptionArgs{ name: oval[0].to_string(), value: Some(oval[1].to_string()) });
402 }
403 } else {
404 println!("unrecognized option '{}'", opt);
405 }
406 }
407 true
408 }
df37d3b1
KS
409 fn parse_scale_options(&mut self, opts: &str) -> bool {
410 for opt in opts.split(',') {
411 let oval: Vec<_> = opt.split('=').collect();
412 if oval.len() == 1 {
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()));
416 } else {
417 println!("unrecognized option '{}'", opt);
418 return false;
419 }
420 }
421 true
422 }
73f889bf 423 fn apply_decoder_options(&self, dec: &mut dyn NADecoder, str_id: u32) {
6dc69f51
KS
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);
429 }
430 }
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);
436 return true;
437 }
438 }
439
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];
a7b5f008 442 if oopts.enc_name.as_str() == "copy" && (cname == "any" || istr.get_info().get_name() == cname) {
86c54d88 443 out_sm.add_stream_ref(istr);
6dc69f51
KS
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());
449 return false;
450 }
451 let mut encoder = (enc_create.unwrap())();
eb563e3d 452 let forced_out = oopts.enc_params.format != NACodecTypeInfo::None;
6dc69f51
KS
453 if oopts.enc_params.format == NACodecTypeInfo::None {
454 oopts.enc_params.format = istr.get_info().get_properties();
455 }
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;
459 }
460 let ret_eparams = encoder.negotiate_format(&oopts.enc_params);
461 if ret_eparams.is_err() {
462 println!("cannot negotiate encoding parameters");
463 return false;
464 }
465 let ret_eparams = ret_eparams.unwrap();
466
467//todo check for params mismatch
468 let cvt = match (&oopts.enc_params.format, &ret_eparams.format) {
469 (NACodecTypeInfo::Video(svinfo), NACodecTypeInfo::Video(dvinfo)) => {
eb563e3d 470 if svinfo == dvinfo && !forced_out {
6dc69f51
KS
471 OutputConvert::None
472 } else {
473 let ofmt = ScaleInfo { fmt: dvinfo.format, width: dvinfo.width, height: dvinfo.height };
df37d3b1 474 let ret = NAScale::new_with_options(ofmt, ofmt, &self.scale_opts);
6dc69f51
KS
475 if ret.is_err() {
476 println!("cannot create scaler");
477 return false;
478 }
479 let scaler = ret.unwrap();
480 let ret = alloc_video_buffer(*dvinfo, 4);
481 if ret.is_err() {
482 println!("cannot create scaler buffer");
483 return false;
484 }
485 let cvt_buf = ret.unwrap();
486 OutputConvert::Video(scaler, cvt_buf)
487 }
488 },
489 (NACodecTypeInfo::Audio(sainfo), NACodecTypeInfo::Audio(dainfo)) => {
490 if sainfo == dainfo {
491 OutputConvert::None
492 } else {
493 let dchmap = match dainfo.channels {
494 1 => NAChannelMap::from_ms_mapping(0x4),
495 2 => NAChannelMap::from_ms_mapping(0x3),
496 _ => {
497println!("can't generate default channel map for {} channels", dainfo.channels);
498 return false;
499 },
500 };
501//todo channelmap
502 OutputConvert::Audio(*dainfo, dchmap)
503 }
504 },
505 _ => OutputConvert::None,
506 };
507 let ret = encoder.init(out_id, ret_eparams);
508 if ret.is_err() {
509 println!("error initialising encoder");
510 return false;
511 }
512 out_sm.add_stream_ref(ret.unwrap());
513
514 let name = format!("output stream {}", out_id);
515 parse_and_apply_options!(encoder, &oopts.enc_opts, name);
516
517 self.encoders.push(OutputMode::Encode(out_id, encoder, cvt));
518 } else {
519println!("encoder {} is not supported by output (expected {})", istr.id, istr.get_info().get_name());
520 return false;
521 }
86c54d88
KS
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));
6dc69f51 525 } else {
6dc69f51
KS
526println!("stream {} ({}) can't be handled", istr.id, istr.get_info().get_name());
527// todo autoselect encoder?
86c54d88 528 return false;
6dc69f51
KS
529 }
530 true
531 }
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);
537 } else {
538 if !self.register_output_stream(cname, istr, out_sm, enc_reg) {
539 return false;
540 }
541 found_stream = true;
542 }
543 }
544 found_stream
545 }
546 fn negotiate_stream_map(&mut self, src_sm: &StreamManager, mux_caps: MuxerCapabilities, out_sm: &mut StreamManager, enc_reg: &RegisteredEncoders) -> bool {
547 match mux_caps {
548 MuxerCapabilities::SingleVideo(cname) => {
549 if self.no_video { return false; }
550 self.map_single(cname, StreamType::Video, src_sm, out_sm, enc_reg)
551 },
552 MuxerCapabilities::SingleAudio(cname) => {
553 if self.no_audio { return false; }
554 self.map_single(cname, StreamType::Audio, src_sm, out_sm, enc_reg)
555 },
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) {
562 return false;
563 }
564 found_vid = true;
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) {
567 return false;
568 }
569 found_aud = true;
570 } else {
571 self.encoders.push(OutputMode::Drop);
572 }
573 }
574 found_vid | found_aud
575 },
576 MuxerCapabilities::OnlyVideo => {
577 if self.no_video { return false; }
578
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) {
583 return false;
584 }
585 found_vid = true;
586 } else {
587 self.encoders.push(OutputMode::Drop);
588 }
589 }
590 found_vid
591 },
592 MuxerCapabilities::OnlyAudio => {
593 if self.no_audio { return false; }
594
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) {
599 return false;
600 }
601 found_aud = true;
602 } else {
603 self.encoders.push(OutputMode::Drop);
604 }
605 }
606 found_aud
607 },
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);
613 continue;
614 }
615 if !self.register_output_stream("any", istr, out_sm, enc_reg) {
616 return false;
617 }
618 }
619 true
620 },
621 }
622 }
623}
624
df37d3b1 625fn encode_frame(dst_id: u32, encoder: &mut Box<dyn NAEncoder>, cvt: &mut OutputConvert, frm: NAFrameRef, scale_opts: &[(String, String)]) -> bool {
d9fe2b71
KS
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();
df37d3b1 634 let ret = NAScale::new_with_options(cur_ifmt, ofmt, scale_opts);
d9fe2b71
KS
635 if ret.is_err() {
636 println!("error re-initialising scaler for {} -> {}", cur_ifmt, ofmt);
637 return false;
638 }
639 *scaler = ret.unwrap();
640 }
641 let ret = scaler.convert(&buf, dbuf);
642 if ret.is_err() {
643 println!("error converting frame for encoding");
644 return false;
645 }
646 dbuf.clone()
647 },
648 OutputConvert::Audio(ref dinfo, ref dchmap) => {
649 let ret = convert_audio_frame(&buf, dinfo, dchmap);
650 if ret.is_err() {
651 println!("error converting audio for stream {}", dst_id);
652 return false;
653 }
654 ret.unwrap()
655 },
656 };
657 let cfrm = NAFrame::new(frm.get_time_information(), frm.frame_type, frm.key, frm.get_info(), cbuf);
658 encoder.encode(&cfrm).unwrap();
659 true
660}
661
6dc69f51
KS
662macro_rules! next_arg {
663 ($args: expr, $arg_idx: expr) => {
664 if $arg_idx + 1 >= $args.len() {
665 println!("codec name is required");
666 }
667 $arg_idx += 1;
668 }
669}
670
86c54d88 671#[allow(clippy::single_match)]
6dc69f51
KS
672fn main() {
673 let args: Vec<_> = env::args().collect();
674
675 if args.len() == 1 {
071d353e
KS
676 println!("usage: nihav-encoder [options] --input inputfile --output outputfile");
677 println!(" use nihav-encoder --help to list all available options");
678 return;
679 }
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");
df37d3b1 689 println!(" --scale-options options - set scaler options");
071d353e
KS
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");
699 println!();
700 println!(" (de)muxer and stream options are passed as comma-separated list e.g. --ostream0 width=320,height=240,flip");
6dc69f51
KS
701 return;
702 }
703
704 let mut dmx_reg = RegisteredDemuxers::new();
705 nihav_register_all_demuxers(&mut dmx_reg);
706 let mut dec_reg = RegisteredDecoders::new();
7b6dcb1e 707 nihav_register_all_decoders(&mut dec_reg);
6dc69f51
KS
708
709 let mut mux_reg = RegisteredMuxers::new();
710 nihav_register_all_muxers(&mut mux_reg);
93521506 711 mux_reg.add_muxer(NULL_MUXER);
6dc69f51
KS
712 let mut enc_reg = RegisteredEncoders::new();
713 nihav_register_all_encoders(&mut enc_reg);
93521506 714 enc_reg.add_encoder(NULL_ENCODER);
6dc69f51
KS
715
716 let mut transcoder = Transcoder::new();
717
718 let mut arg_idx = 1;
5a8a7cdb 719 let mut printed_info = false;
6dc69f51
KS
720 while arg_idx < args.len() {
721 match args[arg_idx].as_str() {
e6cb09af
KS
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);
729 }
730 } else {
731 println!("No registered decoders.");
732 }
5a8a7cdb 733 printed_info = true;
e6cb09af
KS
734 },
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);
742 }
743 } else {
744 println!("No registered encoders.");
745 }
5a8a7cdb 746 printed_info = true;
e6cb09af
KS
747 },
748 "--list-demuxers" => {
749 print!("Registered demuxers:");
750 for dmx in dmx_reg.iter() {
751 print!(" {}", dmx.get_name());
752 }
753 println!();
5a8a7cdb 754 printed_info = true;
e6cb09af
KS
755 },
756 "--list-muxers" => {
757 print!("Registered muxers:");
758 for mux in mux_reg.iter() {
759 print!(" {}", mux.get_name());
760 }
761 println!();
5a8a7cdb 762 printed_info = true;
e6cb09af 763 },
6dc69f51
KS
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);
771 } else {
772 println!("codec {} is not found", cname);
773 }
5a8a7cdb 774 printed_info = true;
6dc69f51
KS
775 },
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);
785 } else {
786 println!("demuxer {} is not found", dname);
787 }
5a8a7cdb 788 printed_info = true;
6dc69f51
KS
789 },
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);
797 } else {
798 println!("codec {} is not found", cname);
799 }
5a8a7cdb 800 printed_info = true;
6dc69f51
KS
801 },
802 "--query-muxer-options" => {
803 next_arg!(args, arg_idx);
804 let name = args[arg_idx].as_str();
805 let mut data = [];
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);
812 } else {
813 println!("muxer {} is not found", name);
814 }
5a8a7cdb 815 printed_info = true;
6dc69f51 816 },
4b5c61e2 817 "--input" | "-i" => {
6dc69f51
KS
818 next_arg!(args, arg_idx);
819 transcoder.input_name = args[arg_idx].clone();
820 },
821 "--input-format" => {
822 next_arg!(args, arg_idx);
823 transcoder.input_fmt = Some(args[arg_idx].clone());
824 },
4b5c61e2 825 "--output" | "-o" => {
6dc69f51
KS
826 next_arg!(args, arg_idx);
827 transcoder.output_name = args[arg_idx].clone();
828 },
829 "--output-format" => {
830 next_arg!(args, arg_idx);
831 transcoder.output_fmt = Some(args[arg_idx].clone());
832 },
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");
837 return;
838 }
839 },
df37d3b1
KS
840 "--scale-options" => {
841 next_arg!(args, arg_idx);
842 if !transcoder.parse_scale_options(&args[arg_idx]) {
843 println!("invalid scale option syntax");
844 return;
845 }
846 },
4b5c61e2 847 "--no-video" | "-vn" => {
6dc69f51
KS
848 transcoder.no_video = true;
849 },
4b5c61e2 850 "--no-audio" | "-an" => {
6dc69f51
KS
851 transcoder.no_audio = true;
852 },
951916e8
KS
853 "--start" => {
854 next_arg!(args, arg_idx);
855 let ret = args[arg_idx].parse::<NATimePoint>();
856 if let Ok(val) = ret {
857 transcoder.start = val;
858 } else {
859 println!("invalid start time");
860 return;
861 }
862 },
863 "--end" => {
864 next_arg!(args, arg_idx);
865 let ret = args[arg_idx].parse::<NATimePoint>();
866 if let Ok(val) = ret {
867 transcoder.end = val;
868 } else {
b0c51548 869 println!("invalid end time");
951916e8
KS
870 return;
871 }
872 },
6dc69f51
KS
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");
877 return;
878 }
879 },
880 _ => {
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");
886 return;
887 }
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");
893 return;
894 }
895 } else if args[arg_idx].starts_with("--") {
896 println!("unknown option");
897 } else {
898 println!("unrecognized argument");
899 }
900 },
901 };
902 arg_idx += 1;
903 }
904
5a8a7cdb
KS
905 if printed_info {
906 return;
907 }
908
86c54d88 909 if transcoder.input_name.is_empty() {
6dc69f51
KS
910 println!("no input name provided");
911 return;
912 }
86c54d88 913 if transcoder.output_name.is_empty() {
6dc69f51
KS
914 println!("no output name provided");
915 return;
916 }
917
918 let res = File::open(transcoder.input_name.as_str());
919 if res.is_err() {
920 println!("error opening input");
921 return;
922 }
923 let mut file = res.unwrap();
924 let mut fr = FileReader::new_read(&mut file);
925 let mut br = ByteReader::new(&mut fr);
926
927 let dmx_name = if let Some(ref str) = transcoder.input_fmt {
928 str.as_str()
86c54d88
KS
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);
931 dmx_name
6dc69f51 932 } else {
86c54d88
KS
933 println!("cannot detect input format");
934 return;
6dc69f51
KS
935 };
936 let ret = dmx_reg.find_demuxer(dmx_name);
937 if ret.is_none() {
938 println!("cannot find demuxer for '{}'", dmx_name);
939 return;
940 }
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());
949println!("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());
955 if ret.is_err() {
956 println!("Error initialising decoder '{}' for stream {}", info.get_name(), str_id);
957 return;
958 }
959 transcoder.apply_decoder_options(dec.as_mut(), str_id);
d9fe2b71
KS
960 let desc = register::get_codec_description(info.get_name());
961 let has_b = if let Some(desc) = desc {
962 desc.has_reorder()
963 } else {
964 println!("No codec description found, using B-frame reorderer.");
965 true
966 };
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)));
6dc69f51
KS
969 } else {
970 println!("No decoder for stream {} ({}) is found", str_id, info.get_name());
971 transcoder.decoders.push(None);
972 }
973 }
951916e8
KS
974 if transcoder.start != NATimePoint::None {
975 let ret = dmx.seek(transcoder.start);
976 if ret.is_err() {
977 println!(" failed to seek to {} error {:?}", transcoder.start, ret.err().unwrap());
978 }
979 }
6dc69f51
KS
980
981 let output_fmt = if let Some(ref str) = transcoder.output_fmt {
982 str
86c54d88
KS
983 } else if let Some(str) = detect::detect_format_by_name(transcoder.output_name.as_str()) {
984 str
6dc69f51 985 } else {
86c54d88
KS
986 println!("Cannot guess muxer for output");
987 return;
6dc69f51
KS
988 };
989 let ret = mux_reg.find_muxer(output_fmt);
990 let ofmt = output_fmt.to_string();
991
992 if ret.is_none() {
993 println!("cannot find muxer '{}'", output_fmt);
994 }
995 let mux_creator = ret.unwrap();
996
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");
1001 return;
1002 }
1003
1004 let ret = File::create(transcoder.output_name.as_str());
1005 if ret.is_err() {
1006 println!("cannot open output file");
1007 return;
1008 }
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);
1014 return;
1015 }
1016 let mut mux = ret.unwrap();
1017 parse_and_apply_options!(mux, &transcoder.mux_opts, "output");
1018
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());
1022 }
1023
951916e8 1024 'main_loop: loop {
6dc69f51
KS
1025 let pktres = dmx.get_frame();
1026 if let Err(DemuxerError::EOF) = pktres { break; }
1027 if pktres.is_err() {
1028 println!("demuxing error");
1029 break;
1030 }
1031 let mut pkt = pktres.unwrap();
f88b8fb4 1032 if transcoder.start != NATimePoint::None && pkt.ts.less_than(transcoder.start) { continue; }
6dc69f51
KS
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());
951916e8 1039 if transcoder.end != NATimePoint::None && !pkt.ts.less_than(transcoder.end) { break 'main_loop; }
6dc69f51
KS
1040 if mux.mux_frame(pkt).is_err() {
1041 println!("error muxing packet");
1042 break;
1043 }
1044 },
1045 OutputMode::Encode(dst_id, ref mut encoder, ref mut cvt) => {
d9fe2b71 1046 if let Some((ref mut dsupp, ref mut decoder, ref mut reorderer)) = transcoder.decoders[src_id] {
6dc69f51 1047 let ret = decoder.decode(dsupp, &pkt);
f88b8fb4
KS
1048 if let (true, Err(DecoderError::MissingReference)) = (transcoder.start != NATimePoint::None, &ret) {
1049 continue;
1050 }
6dc69f51
KS
1051 if ret.is_err() {
1052 println!("error decoding stream {}", src_id);
1053 break;
1054 }
1055 let frm = ret.unwrap();
d9fe2b71
KS
1056 reorderer.add_frame(frm);
1057 while let Some(frm) = reorderer.get_frame() {
df37d3b1 1058 if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) {
d9fe2b71
KS
1059 break;
1060 }
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();
1064 }
6dc69f51
KS
1065 }
1066 } else {
1067 println!("no decoder for stream {}", src_id);
1068 break;
1069 }
1070 },
1071 };
1072 }
d9fe2b71
KS
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() {
df37d3b1 1078 if !encode_frame(dst_id, encoder, cvt, frm, &transcoder.scale_opts) {
d9fe2b71
KS
1079 break;
1080 }
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();
1084 }
1085 }
1086 }
1087 }
1088 }
6dc69f51
KS
1089 'flush_loop: for enc in transcoder.encoders.iter_mut() {
1090 match enc {
1091 OutputMode::Encode(str_id, ref mut encoder, _) => {
1092 let ret = encoder.flush();
1093 if ret.is_err() {
1094 println!("error flushing encoder for stream {}", str_id);
1095 break;
1096 } else {
1097 while let Ok(Some(pkt)) = encoder.get_packet() {
1098 if mux.mux_frame(pkt).is_err() {
1099 println!("error muxing packet");
1100 break 'flush_loop;
1101 }
1102 }
1103 }
1104 },
1105 _ => {},
1106 };
1107 }
1108
1109 let ret = mux.end();
1110 if ret.is_err() {
1111 println!("error at finalising muxing");
1112 }
1113}