]> git.nihav.org Git - nihav-tool.git/blob - src/main.rs
1be4e2a0a7e36a42ebb004e69251cc84006bd64a
[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 [lastpts]");
78 return;
79 }
80 let mut lastpts: Option<u64> = None;
81 let mut cur_arg: usize = 1;
82 let mut noout = false;
83 let mut decode_video = true;
84 let mut decode_audio = true;
85 let mut nmode = NumberMode::FrmPTS;
86 let mut smode = FrameSkipMode::None;
87 let mut seek_time = 0u64;
88 let mut vpfx: Option<String> = None;
89 let mut apfx: Option<&str> = None;
90 let mut ignore_errors = false;
91 let mut dump_frames = false;
92
93 while (cur_arg < args.len()) && args[cur_arg].starts_with('-') {
94 match args[cur_arg].as_str() {
95 "--" => { break; },
96 "-noout" => { noout = true; },
97 "-an" => { decode_audio = false; },
98 "-vn" => { decode_video = false; },
99 "-nm=count" => { nmode = NumberMode::Counter; },
100 "-nm=pktpts" => { nmode = NumberMode::PktPTS; },
101 "-nm=frmpts" => { nmode = NumberMode::FrmPTS; },
102 "-skip=key" => { smode = FrameSkipMode::KeyframesOnly; },
103 "-skip=intra" => { smode = FrameSkipMode::IntraOnly; },
104 "-seek" => {
105 cur_arg += 1;
106 if cur_arg == args.len() {
107 println!("seek time missing");
108 return;
109 }
110 let ret = args[cur_arg].parse::<u64>();
111 if ret.is_err() {
112 println!("wrong seek time");
113 return;
114 }
115 seek_time = ret.unwrap();
116 },
117 "-apfx" => {
118 cur_arg += 1;
119 if cur_arg == args.len() {
120 println!("name missing");
121 return;
122 }
123 apfx = Some(&args[cur_arg]);
124 },
125 "-vpfx" => {
126 cur_arg += 1;
127 if cur_arg == args.len() {
128 println!("name missing");
129 return;
130 }
131 vpfx = Some(args[cur_arg].clone());
132 },
133 "-ignerr" => { ignore_errors = true; },
134 "-dumpfrm" => { dump_frames = true; },
135 _ => { println!("unknown option {}", args[cur_arg]); return; },
136 }
137 cur_arg += 1;
138 }
139 let name = args[cur_arg].as_str();
140 cur_arg += 1;
141 if cur_arg < args.len() {
142 lastpts = Some(u64::from_str_radix(args[cur_arg].as_str(), 10).unwrap());
143 }
144
145 let path = Path::new(name);
146 let mut file = File::open(path).unwrap();
147 let dmx_fact;
148 let mut fr = FileReader::new_read(&mut file);
149 let mut br = ByteReader::new(&mut fr);
150 let res = detect::detect_format(name, &mut br);
151 if res.is_none() {
152 println!("cannot detect format for {}", name);
153 return;
154 }
155 let (dmx_name, _) = res.unwrap();
156 println!("trying demuxer {} on {}", dmx_name, name);
157
158 let mut dmx_reg = RegisteredDemuxers::new();
159 nihav_register_all_demuxers(&mut dmx_reg);
160 let mut dec_reg = RegisteredDecoders::new();
161 nihav_register_all_codecs(&mut dec_reg);
162
163 dmx_fact = dmx_reg.find_demuxer(dmx_name).unwrap();
164 br.seek(SeekFrom::Start(0)).unwrap();
165 let mut dmx = create_demuxer(dmx_fact, &mut br).unwrap();
166
167 if seek_time > 0 {
168 let ret = dmx.seek(seek_time);
169 if ret.is_err() {
170 println!(" seek error {:?}", ret.err().unwrap());
171 }
172 }
173
174 let mut decs: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)>> = Vec::new();
175 let mut sids: Vec<u32> = Vec::new();
176 let mut writers: Vec<Outputter> = Vec::new();
177 let dec_opts = [NAOption{name: FRAME_SKIP_OPTION, value: NAValue::String(smode.to_string())}];
178 for i in 0..dmx.get_num_streams() {
179 let s = dmx.get_stream(i).unwrap();
180 let info = s.get_info();
181 let decfunc = dec_reg.find_decoder(info.get_name());
182 println!("stream {} - {} {}", i, s, info.get_name());
183 let str_id = s.get_id();
184 let mut has_out = false;
185 sids.push(str_id);
186 if info.is_video() {
187 if decode_video {
188 if decfunc.is_none() {
189 println!("no video decoder found!");
190 return;
191 }
192 let mut dec = (decfunc.unwrap())();
193 let mut dsupp = Box::new(NADecoderSupport::new());
194 dec.init(&mut dsupp, info).unwrap();
195 dec.set_options(&dec_opts);
196 decs.push(Some((dsupp, dec)));
197 if !noout {
198 writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
199 has_out = true;
200 }
201 } else {
202 decs.push(None);
203 }
204 } else if info.is_audio() {
205 if decode_audio {
206 if decfunc.is_none() {
207 println!("no audio decoder found!");
208 return;
209 }
210 let mut dec = (decfunc.unwrap())();
211 let mut dsupp = Box::new(NADecoderSupport::new());
212 dec.init(&mut dsupp, info).unwrap();
213 decs.push(Some((dsupp, dec)));
214 if !noout {
215 let name = if let Some(apfx) = apfx {
216 format!("{}{:02}.wav", apfx, i)
217 } else {
218 format!("out{:02}.wav", i)
219 };
220 writers.push(Outputter::Audio(AudioOutput::new(&name)));
221 has_out = true;
222 }
223 } else {
224 decs.push(None);
225 }
226 } else {
227 decs.push(None);
228 panic!("decoder {} not found", info.get_name());
229 }
230 if !has_out {
231 writers.push(Outputter::None);
232 }
233 }
234
235 let mut frmnum = 0;
236 loop {
237 let pktres = dmx.get_frame();
238 if let Err(e) = pktres {
239 if e == DemuxerError::EOF { break; }
240 }
241 let pkt = pktres.unwrap();
242 let streamno = pkt.get_stream().get_id();
243 let sr = sids.iter().position(|x| *x == streamno);
244 let idx = sr.unwrap();
245 if dump_frames {
246 let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum));
247 let mut ofile = File::create(name).unwrap();
248 ofile.write(pkt.get_buffer().as_slice()).unwrap();
249 frmnum += 1;
250 }
251 if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
252 match dec.decode(dsupp, &pkt) {
253 Ok(frm) => {
254 if !noout {
255 match writers[idx] {
256 Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
257 Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
258 _ => {},
259 };
260 }
261 },
262 Err(DecoderError::MissingReference) if seek_time > 0 => {
263 println!("ignoring missing ref");
264 },
265 Err(reason) => {
266 println!("error decoding frame {:?}", reason);
267 if !ignore_errors {
268 break;
269 }
270 },
271 };
272 if pkt.get_pts() != None && lastpts.is_some() && pkt.get_pts() >= lastpts { break; }
273 }
274 }
275 //panic!("end");
276 }