]> git.nihav.org Git - nihav-tool.git/blame_incremental - src/main.rs
flush wavwriter data on close
[nihav-tool.git] / src / main.rs
... / ...
CommitLineData
1extern crate nihav_core;
2extern crate nihav_codec_support;
3extern crate nihav_registry;
4extern crate nihav_allstuff;
5
6use std::io::{SeekFrom, Write, BufReader};
7use std::fs::File;
8use std::path::Path;
9use nihav_core::io::byteio::{FileReader, ByteReader};
10use nihav_core::frame::*;
11use nihav_core::codecs::*;
12use nihav_core::demuxers::*;
13use nihav_codec_support::imgwrite::*;
14use nihav_registry::detect;
15use nihav_allstuff::*;
16use std::env;
17
18mod wavwriter;
19use crate::wavwriter::WavWriter;
20
21#[derive(Clone,Copy,PartialEq)]
22enum NumberMode {
23 Counter,
24 PktPTS,
25 FrmPTS,
26}
27
28struct FrameOutput {
29 prefix: String,
30 streamno: usize,
31 frameno: u64,
32 nmode: NumberMode,
33}
34
35impl 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
51struct AudioOutput {
52 wwr: WavWriter<'static>,
53 wrote_header: bool,
54}
55
56impl 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
67enum Outputter {
68 Video(FrameOutput),
69 Audio(AudioOutput),
70 None,
71}
72
73fn 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 file = File::open(path).unwrap();
168 let mut file = BufReader::new(file);
169 let dmx_fact;
170 let mut fr = FileReader::new_read(&mut file);
171 let mut br = ByteReader::new(&mut fr);
172 let res = detect::detect_format(name, &mut br);
173 if res.is_none() {
174 println!("cannot detect format for {}", name);
175 return;
176 }
177 let (dmx_name, _) = res.unwrap();
178println!("trying demuxer {} on {}", dmx_name, name);
179
180 let mut dmx_reg = RegisteredDemuxers::new();
181 nihav_register_all_demuxers(&mut dmx_reg);
182 let mut dec_reg = RegisteredDecoders::new();
183 nihav_register_all_decoders(&mut dec_reg);
184
185 dmx_fact = dmx_reg.find_demuxer(dmx_name).unwrap();
186 br.seek(SeekFrom::Start(0)).unwrap();
187 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
188
189 if seek_time != NATimePoint::None {
190 let ret = dmx.seek(seek_time);
191 if ret.is_err() {
192println!(" seek error {:?}", ret.err().unwrap());
193 }
194 }
195
196 let mut decs: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)>> = Vec::new();
197 let mut sids: Vec<u32> = Vec::new();
198 let mut writers: Vec<Outputter> = Vec::new();
199 let dec_opts = [NAOption{name: FRAME_SKIP_OPTION, value: NAValue::String(smode.to_string())}];
200 for i in 0..dmx.get_num_streams() {
201 let s = dmx.get_stream(i).unwrap();
202 let info = s.get_info();
203 let decfunc = dec_reg.find_decoder(info.get_name());
204println!("stream {} - {} {}", i, s, info.get_name());
205 let str_id = s.get_id();
206 let mut has_out = false;
207 sids.push(str_id);
208 if info.is_video() {
209 if decode_video {
210 if decfunc.is_none() {
211 println!("no video decoder found!");
212 return;
213 }
214 let mut dec = (decfunc.unwrap())();
215 let mut dsupp = Box::new(NADecoderSupport::new());
216 dec.init(&mut dsupp, info).unwrap();
217 dec.set_options(&dec_opts);
218 decs.push(Some((dsupp, dec)));
219 if !noout {
220 writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
221 has_out = true;
222 }
223 } else {
224 decs.push(None);
225 }
226 } else if info.is_audio() {
227 if decode_audio {
228 if decfunc.is_none() {
229 println!("no audio 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 decs.push(Some((dsupp, dec)));
236 if !noout {
237 let name = if let Some(apfx) = apfx {
238 format!("{}{:02}.wav", apfx, i)
239 } else {
240 format!("out{:02}.wav", i)
241 };
242 writers.push(Outputter::Audio(AudioOutput::new(&name)));
243 has_out = true;
244 }
245 } else {
246 decs.push(None);
247 }
248 } else {
249 decs.push(None);
250 }
251 if !has_out {
252 writers.push(Outputter::None);
253 }
254 }
255
256 let mut frmnum = 0;
257 loop {
258 let pktres = dmx.get_frame();
259 if let Err(e) = pktres {
260 if e == DemuxerError::EOF { break; }
261 }
262 let pkt = pktres.unwrap();
263 let streamno = pkt.get_stream().get_id();
264 let sr = sids.iter().position(|x| *x == streamno);
265 let idx = sr.unwrap();
266 if dump_frames {
267 let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum));
268 let mut ofile = File::create(name).unwrap();
269 ofile.write(pkt.get_buffer().as_slice()).unwrap();
270 frmnum += 1;
271 }
272 if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
273 match dec.decode(dsupp, &pkt) {
274 Ok(frm) => {
275 if !noout {
276 match writers[idx] {
277 Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
278 Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
279 _ => {},
280 };
281 }
282 },
283 Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => {
284 println!("ignoring missing ref");
285 },
286 Err(reason) => {
287 println!("error decoding frame {:?}", reason);
288 if !ignore_errors {
289 break;
290 }
291 },
292 };
293 if pkt.get_pts() != None && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; }
294 }
295 }
296//panic!("end");
297}