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