]> git.nihav.org Git - nihav-tool.git/blob - src/main.rs
mention that --help is available
[nihav-tool.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::io::{SeekFrom, Write};
7 use std::fs::File;
8 use std::path::Path;
9 use nihav_core::io::byteio::{FileReader, ByteReader};
10 use nihav_core::frame::*;
11 use nihav_core::codecs::*;
12 use nihav_core::demuxers::*;
13 use nihav_codec_support::imgwrite::*;
14 use nihav_registry::detect;
15 use nihav_allstuff::*;
16 use std::env;
17
18 mod wavwriter;
19 use crate::wavwriter::WavWriter;
20
21 #[derive(Clone,Copy,PartialEq)]
22 enum NumberMode {
23 Counter,
24 PktPTS,
25 FrmPTS,
26 }
27
28 struct FrameOutput {
29 prefix: String,
30 streamno: usize,
31 frameno: u64,
32 nmode: NumberMode,
33 }
34
35 impl FrameOutput {
36 fn output_frame(&mut self, pkt: &NAPacket, frm: NAFrameRef) {
37 if frm.get_frame_type() != FrameType::Skip {
38 let pts = match self.nmode {
39 NumberMode::Counter => { self.frameno },
40 NumberMode::PktPTS => { pkt.get_pts().unwrap() },
41 NumberMode::FrmPTS => { if let Some(pt) = frm.get_pts() { pt } else { pkt.get_pts().unwrap() } },
42 };
43 if let Err(_) = write_pnm(&self.prefix, self.streamno, pts, frm) {
44 println!("error writing output picture");
45 }
46 }
47 self.frameno += 1;
48 }
49 }
50
51 struct AudioOutput {
52 wwr: WavWriter<'static>,
53 wrote_header: bool,
54 }
55
56 impl AudioOutput {
57 fn new(name: &str) -> Self { Self { wwr: WavWriter::new(name), wrote_header: false } }
58 fn output_frame(&mut self, _pkt: &NAPacket, frm: NAFrameRef) {
59 if !self.wrote_header {
60 self.wwr.write_header(frm.get_info().as_ref().get_properties().get_audio_info().unwrap()).unwrap();
61 self.wrote_header = true;
62 }
63 self.wwr.write_frame(frm.get_buffer()).unwrap();
64 }
65 }
66
67 enum Outputter {
68 Video(FrameOutput),
69 Audio(AudioOutput),
70 None,
71 }
72
73 fn main() {
74 let args: Vec<_> = env::args().collect();
75
76 if args.len() == 1 {
77 println!("usage: nihav-tool [-noout] [-vn] [-an] input [endtime]");
78 println!(" or invoke nihav-tool --help for more detailed information");
79 return;
80 }
81 if args.len() == 2 && args[1] == "--help" {
82 println!("usage: nihav-tool [options] input [endtime]");
83 println!("available options:");
84 println!(" -noout - decode but do not write output");
85 println!(" -an - do not decode audio streams");
86 println!(" -vn - do not decode video streams");
87 println!(" -nm={{count,pktpts,frmpts}} - use counter/frame PTS/decoded PTS as output image number");
88 println!(" -skip={{key,intra}} - decode only reference frames (I-/P-) or intra frames only");
89 println!(" -seek time - try seeking to the given time before starting decoding");
90 println!(" -apfx/-vpfx prefix - use given prefix when creating output audio/video files instead of default 'out'");
91 println!(" -ignerr - keep decoding even if decoding error is encountered");
92 println!(" -dumpfrm - dump raw frame data for all streams");
93 println!(" endtime - decoding end time, can be given either as time (hh:mm:ss.ms) or as a timestamp (e.g. 42pts)");
94 return;
95 }
96 let mut lastpts = NATimePoint::None;
97 let mut cur_arg: usize = 1;
98 let mut noout = false;
99 let mut decode_video = true;
100 let mut decode_audio = true;
101 let mut nmode = NumberMode::FrmPTS;
102 let mut smode = FrameSkipMode::None;
103 let mut seek_time = NATimePoint::None;
104 let mut vpfx: Option<String> = None;
105 let mut apfx: Option<&str> = None;
106 let mut ignore_errors = false;
107 let mut dump_frames = false;
108
109 while (cur_arg < args.len()) && args[cur_arg].starts_with('-') {
110 match args[cur_arg].as_str() {
111 "--" => { break; },
112 "-noout" => { noout = true; },
113 "-an" => { decode_audio = false; },
114 "-vn" => { decode_video = false; },
115 "-nm=count" => { nmode = NumberMode::Counter; },
116 "-nm=pktpts" => { nmode = NumberMode::PktPTS; },
117 "-nm=frmpts" => { nmode = NumberMode::FrmPTS; },
118 "-skip=key" => { smode = FrameSkipMode::KeyframesOnly; },
119 "-skip=intra" => { smode = FrameSkipMode::IntraOnly; },
120 "-seek" => {
121 cur_arg += 1;
122 if cur_arg == args.len() {
123 println!("seek time missing");
124 return;
125 }
126 let ret = args[cur_arg].parse::<NATimePoint>();
127 if ret.is_err() {
128 println!("wrong seek time");
129 return;
130 }
131 seek_time = ret.unwrap();
132 },
133 "-apfx" => {
134 cur_arg += 1;
135 if cur_arg == args.len() {
136 println!("name missing");
137 return;
138 }
139 apfx = Some(&args[cur_arg]);
140 },
141 "-vpfx" => {
142 cur_arg += 1;
143 if cur_arg == args.len() {
144 println!("name missing");
145 return;
146 }
147 vpfx = Some(args[cur_arg].clone());
148 },
149 "-ignerr" => { ignore_errors = true; },
150 "-dumpfrm" => { dump_frames = true; },
151 _ => { println!("unknown option {}", args[cur_arg]); return; },
152 }
153 cur_arg += 1;
154 }
155 let name = args[cur_arg].as_str();
156 cur_arg += 1;
157 if cur_arg < args.len() {
158 let ret = args[cur_arg].parse::<NATimePoint>();
159 if ret.is_err() {
160 println!("cannot parse end time");
161 return;
162 }
163 lastpts = ret.unwrap();
164 }
165
166 let path = Path::new(name);
167 let mut file = File::open(path).unwrap();
168 let dmx_fact;
169 let mut fr = FileReader::new_read(&mut file);
170 let mut br = ByteReader::new(&mut fr);
171 let res = detect::detect_format(name, &mut br);
172 if res.is_none() {
173 println!("cannot detect format for {}", name);
174 return;
175 }
176 let (dmx_name, _) = res.unwrap();
177 println!("trying demuxer {} on {}", dmx_name, name);
178
179 let mut dmx_reg = RegisteredDemuxers::new();
180 nihav_register_all_demuxers(&mut dmx_reg);
181 let mut dec_reg = RegisteredDecoders::new();
182 nihav_register_all_decoders(&mut dec_reg);
183
184 dmx_fact = dmx_reg.find_demuxer(dmx_name).unwrap();
185 br.seek(SeekFrom::Start(0)).unwrap();
186 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
187
188 if seek_time != NATimePoint::None {
189 let ret = dmx.seek(seek_time);
190 if ret.is_err() {
191 println!(" seek error {:?}", ret.err().unwrap());
192 }
193 }
194
195 let mut decs: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)>> = Vec::new();
196 let mut sids: Vec<u32> = Vec::new();
197 let mut writers: Vec<Outputter> = Vec::new();
198 let dec_opts = [NAOption{name: FRAME_SKIP_OPTION, value: NAValue::String(smode.to_string())}];
199 for i in 0..dmx.get_num_streams() {
200 let s = dmx.get_stream(i).unwrap();
201 let info = s.get_info();
202 let decfunc = dec_reg.find_decoder(info.get_name());
203 println!("stream {} - {} {}", i, s, info.get_name());
204 let str_id = s.get_id();
205 let mut has_out = false;
206 sids.push(str_id);
207 if info.is_video() {
208 if decode_video {
209 if decfunc.is_none() {
210 println!("no video decoder found!");
211 return;
212 }
213 let mut dec = (decfunc.unwrap())();
214 let mut dsupp = Box::new(NADecoderSupport::new());
215 dec.init(&mut dsupp, info).unwrap();
216 dec.set_options(&dec_opts);
217 decs.push(Some((dsupp, dec)));
218 if !noout {
219 writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
220 has_out = true;
221 }
222 } else {
223 decs.push(None);
224 }
225 } else if info.is_audio() {
226 if decode_audio {
227 if decfunc.is_none() {
228 println!("no audio decoder found!");
229 return;
230 }
231 let mut dec = (decfunc.unwrap())();
232 let mut dsupp = Box::new(NADecoderSupport::new());
233 dec.init(&mut dsupp, info).unwrap();
234 decs.push(Some((dsupp, dec)));
235 if !noout {
236 let name = if let Some(apfx) = apfx {
237 format!("{}{:02}.wav", apfx, i)
238 } else {
239 format!("out{:02}.wav", i)
240 };
241 writers.push(Outputter::Audio(AudioOutput::new(&name)));
242 has_out = true;
243 }
244 } else {
245 decs.push(None);
246 }
247 } else {
248 decs.push(None);
249 }
250 if !has_out {
251 writers.push(Outputter::None);
252 }
253 }
254
255 let mut frmnum = 0;
256 loop {
257 let pktres = dmx.get_frame();
258 if let Err(e) = pktres {
259 if e == DemuxerError::EOF { break; }
260 }
261 let pkt = pktres.unwrap();
262 let streamno = pkt.get_stream().get_id();
263 let sr = sids.iter().position(|x| *x == streamno);
264 let idx = sr.unwrap();
265 if dump_frames {
266 let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum));
267 let mut ofile = File::create(name).unwrap();
268 ofile.write(pkt.get_buffer().as_slice()).unwrap();
269 frmnum += 1;
270 }
271 if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
272 match dec.decode(dsupp, &pkt) {
273 Ok(frm) => {
274 if !noout {
275 match writers[idx] {
276 Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
277 Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
278 _ => {},
279 };
280 }
281 },
282 Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => {
283 println!("ignoring missing ref");
284 },
285 Err(reason) => {
286 println!("error decoding frame {:?}", reason);
287 if !ignore_errors {
288 break;
289 }
290 },
291 };
292 if pkt.get_pts() != None && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; }
293 }
294 }
295 //panic!("end");
296 }