1 extern crate nihav_core;
2 extern crate nihav_codec_support;
3 extern crate nihav_registry;
4 extern crate nihav_allstuff;
6 use std::io::{Write, BufReader};
9 use nihav_core::frame::*;
10 use nihav_core::codecs::*;
11 use nihav_core::demuxers::*;
12 use nihav_codec_support::imgwrite::*;
18 use crate::wavwriter::WavWriter;
20 #[derive(Clone,Copy,PartialEq)]
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() } },
42 if write_pnm(&self.prefix, self.streamno, pts, frm).is_err() {
43 println!("error writing output picture");
51 wwr: WavWriter<'static>,
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;
62 self.wwr.write_frame(frm.get_buffer()).unwrap();
73 let args: Vec<_> = env::args().collect();
76 println!("usage: nihav-tool [-noout] [-vn] [-an] input [endtime]");
77 println!(" or invoke nihav-tool --help for more detailed information");
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)");
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();
110 while (cur_arg < args.len()) && args[cur_arg].starts_with('-') {
111 match args[cur_arg].as_str() {
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; },
123 if cur_arg == args.len() {
124 println!("seek time missing");
127 let ret = args[cur_arg].parse::<NATimePoint>();
129 println!("wrong seek time");
132 seek_time = ret.unwrap();
136 if cur_arg == args.len() {
137 println!("name missing");
140 apfx = Some(&args[cur_arg]);
144 if cur_arg == args.len() {
145 println!("name missing");
148 vpfx = Some(args[cur_arg].clone());
152 if cur_arg == args.len() {
153 println!("name missing");
156 force_dmx = Some(&args[cur_arg]);
158 "-print_mov_chunks" => {
159 demux_opts.push(NAOption{name: "print_chunks", value: NAValue::Bool(true) });
161 "-ignerr" => { ignore_errors = true; },
162 "-dumpfrm" => { dump_frames = true; },
163 _ => { println!("unknown option {}", args[cur_arg]); return; },
167 let name = args[cur_arg].as_str();
169 if cur_arg < args.len() {
170 let ret = args[cur_arg].parse::<NATimePoint>();
172 println!("cannot parse end time");
175 lastpts = ret.unwrap();
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);
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());
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!");
200 if seek_time != NATimePoint::None {
201 let ret = demuxer.seek(seek_time);
203 println!(" seek error {:?}", ret.err().unwrap());
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();
213 let s = duration / 1000;
216 println!(" total duration {}:{:02}:{:02}.{}", h, m % 60, s % 60, (duration / 100) % 10);
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;
228 if decfunc.is_none() {
229 println!("no video decoder found!");
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)));
238 writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
244 } else if info.is_audio() {
246 if decfunc.is_none() {
247 println!("no audio decoder found!");
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)));
255 let name = if let Some(apfx) = apfx {
256 format!("{}{:02}.wav", apfx, i)
258 format!("out{:02}.wav", i)
260 writers.push(Outputter::Audio(AudioOutput::new(&name)));
270 writers.push(Outputter::None);
276 let pktres = demuxer.get_frame();
277 if let Err(e) = pktres {
278 if e == DemuxerError::EOF { break; }
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();
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();
290 if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
291 match dec.decode(dsupp, &pkt) {
295 Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
296 Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
301 Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => {
302 println!("ignoring missing ref");
305 println!("error decoding frame {:?}", reason);
311 if pkt.get_pts().is_some() && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; }