]> git.nihav.org Git - nihav-tool.git/blob - src/main.rs
improve ID3 tag handling
[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
108 while (cur_arg < args.len()) && args[cur_arg].starts_with('-') {
109 match args[cur_arg].as_str() {
110 "--" => { break; },
111 "-noout" => { noout = true; },
112 "-an" => { decode_audio = false; },
113 "-vn" => { decode_video = false; },
114 "-nm=count" => { nmode = NumberMode::Counter; },
115 "-nm=pktpts" => { nmode = NumberMode::PktPTS; },
116 "-nm=frmpts" => { nmode = NumberMode::FrmPTS; },
117 "-skip=key" => { smode = FrameSkipMode::KeyframesOnly; },
118 "-skip=intra" => { smode = FrameSkipMode::IntraOnly; },
119 "-seek" => {
120 cur_arg += 1;
121 if cur_arg == args.len() {
122 println!("seek time missing");
123 return;
124 }
125 let ret = args[cur_arg].parse::<NATimePoint>();
126 if ret.is_err() {
127 println!("wrong seek time");
128 return;
129 }
130 seek_time = ret.unwrap();
131 },
132 "-apfx" => {
133 cur_arg += 1;
134 if cur_arg == args.len() {
135 println!("name missing");
136 return;
137 }
138 apfx = Some(&args[cur_arg]);
139 },
140 "-vpfx" => {
141 cur_arg += 1;
142 if cur_arg == args.len() {
143 println!("name missing");
144 return;
145 }
146 vpfx = Some(args[cur_arg].clone());
147 },
148 "-ignerr" => { ignore_errors = true; },
149 "-dumpfrm" => { dump_frames = true; },
150 _ => { println!("unknown option {}", args[cur_arg]); return; },
151 }
152 cur_arg += 1;
153 }
154 let name = args[cur_arg].as_str();
155 cur_arg += 1;
156 if cur_arg < args.len() {
157 let ret = args[cur_arg].parse::<NATimePoint>();
158 if ret.is_err() {
159 println!("cannot parse end time");
160 return;
161 }
162 lastpts = ret.unwrap();
163 }
164
165 let path = Path::new(name);
166 let file = File::open(path).unwrap();
167 let file = BufReader::new(file);
168 let mut fr = FileReader::new_read(file);
169 let mut br = ByteReader::new(&mut fr);
170 let (is_raw, start, end) = detect_tags(&mut br);
171
172 let mut nfr: Box<dyn ByteIO>;
173 if start != 0 || end.is_some() {
174 println!(" limiting range to {:X}-{:X}", start, end.unwrap_or(0));
175 let file = fr.finish();
176 nfr = Box::new(BoundedFileReader::new_read(file, start, end).unwrap());
177 } else {
178 nfr = Box::new(fr);
179 }
180 let mut br = ByteReader::new(nfr.as_mut());
181 let full_reg = FullRegister::new();
182 let mut demuxer = DemuxerObject::create(&mut br, &full_reg, name, is_raw);
183 if demuxer.is_none() {
184 println!("No demuxer found!");
185 return;
186 }
187 if seek_time != NATimePoint::None {
188 let ret = demuxer.seek(seek_time);
189 if ret.is_err() {
190 println!(" seek error {:?}", ret.err().unwrap());
191 }
192 }
193
194 let mut decs: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)>> = Vec::new();
195 let mut sids: Vec<u32> = Vec::new();
196 let mut writers: Vec<Outputter> = Vec::new();
197 let dec_opts = [NAOption{name: FRAME_SKIP_OPTION, value: NAValue::String(smode.to_string())}];
198 let duration = demuxer.get_duration();
199 if duration != 0 {
200 let s = duration / 1000;
201 let m = s / 60;
202 let h = m / 60;
203 println!(" total duration {}:{:02}:{:02}.{}", h, m % 60, s % 60, (duration / 100) % 10);
204 }
205 for i in 0..demuxer.get_num_streams() {
206 let s = demuxer.get_stream(i).unwrap();
207 let info = s.get_info();
208 let decfunc = full_reg.dec_reg.find_decoder(info.get_name());
209 println!("stream {} - {} {}", i, s, info.get_name());
210 let str_id = s.get_id();
211 let mut has_out = false;
212 sids.push(str_id);
213 if info.is_video() {
214 if decode_video {
215 if decfunc.is_none() {
216 println!("no video decoder found!");
217 return;
218 }
219 let mut dec = (decfunc.unwrap())();
220 let mut dsupp = Box::new(NADecoderSupport::new());
221 dec.init(&mut dsupp, info).unwrap();
222 dec.set_options(&dec_opts);
223 decs.push(Some((dsupp, dec)));
224 if !noout {
225 writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
226 has_out = true;
227 }
228 } else {
229 decs.push(None);
230 }
231 } else if info.is_audio() {
232 if decode_audio {
233 if decfunc.is_none() {
234 println!("no audio decoder found!");
235 return;
236 }
237 let mut dec = (decfunc.unwrap())();
238 let mut dsupp = Box::new(NADecoderSupport::new());
239 dec.init(&mut dsupp, info).unwrap();
240 decs.push(Some((dsupp, dec)));
241 if !noout {
242 let name = if let Some(apfx) = apfx {
243 format!("{}{:02}.wav", apfx, i)
244 } else {
245 format!("out{:02}.wav", i)
246 };
247 writers.push(Outputter::Audio(AudioOutput::new(&name)));
248 has_out = true;
249 }
250 } else {
251 decs.push(None);
252 }
253 } else {
254 decs.push(None);
255 }
256 if !has_out {
257 writers.push(Outputter::None);
258 }
259 }
260
261 let mut frmnum = 0;
262 loop {
263 let pktres = demuxer.get_frame();
264 if let Err(e) = pktres {
265 if e == DemuxerError::EOF { break; }
266 }
267 let pkt = pktres.unwrap();
268 let streamno = pkt.get_stream().get_id();
269 let sr = sids.iter().position(|x| *x == streamno);
270 let idx = sr.unwrap();
271 if dump_frames {
272 let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum));
273 let mut ofile = File::create(name).unwrap();
274 ofile.write_all(pkt.get_buffer().as_slice()).unwrap();
275 frmnum += 1;
276 }
277 if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
278 match dec.decode(dsupp, &pkt) {
279 Ok(frm) => {
280 if !noout {
281 match writers[idx] {
282 Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
283 Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
284 _ => {},
285 };
286 }
287 },
288 Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => {
289 println!("ignoring missing ref");
290 },
291 Err(reason) => {
292 println!("error decoding frame {:?}", reason);
293 if !ignore_errors {
294 break;
295 }
296 },
297 };
298 if pkt.get_pts() != None && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; }
299 }
300 }
301 //panic!("end");
302 }