| 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, BufReader}; |
| 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 write_pnm(&self.prefix, self.streamno, pts, frm).is_err() { |
| 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 [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(); |
| 178 | println!("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() { |
| 192 | println!(" 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 | let duration = dmx.get_duration(); |
| 201 | if duration != 0 { |
| 202 | let s = duration / 1000; |
| 203 | let m = s / 60; |
| 204 | let h = m / 60; |
| 205 | println!(" total duration {}:{:02}:{:02}.{}", h, m % 60, s % 60, (duration / 100) % 10); |
| 206 | } |
| 207 | for i in 0..dmx.get_num_streams() { |
| 208 | let s = dmx.get_stream(i).unwrap(); |
| 209 | let info = s.get_info(); |
| 210 | let decfunc = dec_reg.find_decoder(info.get_name()); |
| 211 | println!("stream {} - {} {}", i, s, info.get_name()); |
| 212 | let str_id = s.get_id(); |
| 213 | let mut has_out = false; |
| 214 | sids.push(str_id); |
| 215 | if info.is_video() { |
| 216 | if decode_video { |
| 217 | if decfunc.is_none() { |
| 218 | println!("no video decoder found!"); |
| 219 | return; |
| 220 | } |
| 221 | let mut dec = (decfunc.unwrap())(); |
| 222 | let mut dsupp = Box::new(NADecoderSupport::new()); |
| 223 | dec.init(&mut dsupp, info).unwrap(); |
| 224 | dec.set_options(&dec_opts); |
| 225 | decs.push(Some((dsupp, dec))); |
| 226 | if !noout { |
| 227 | writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode})); |
| 228 | has_out = true; |
| 229 | } |
| 230 | } else { |
| 231 | decs.push(None); |
| 232 | } |
| 233 | } else if info.is_audio() { |
| 234 | if decode_audio { |
| 235 | if decfunc.is_none() { |
| 236 | println!("no audio decoder found!"); |
| 237 | return; |
| 238 | } |
| 239 | let mut dec = (decfunc.unwrap())(); |
| 240 | let mut dsupp = Box::new(NADecoderSupport::new()); |
| 241 | dec.init(&mut dsupp, info).unwrap(); |
| 242 | decs.push(Some((dsupp, dec))); |
| 243 | if !noout { |
| 244 | let name = if let Some(apfx) = apfx { |
| 245 | format!("{}{:02}.wav", apfx, i) |
| 246 | } else { |
| 247 | format!("out{:02}.wav", i) |
| 248 | }; |
| 249 | writers.push(Outputter::Audio(AudioOutput::new(&name))); |
| 250 | has_out = true; |
| 251 | } |
| 252 | } else { |
| 253 | decs.push(None); |
| 254 | } |
| 255 | } else { |
| 256 | decs.push(None); |
| 257 | } |
| 258 | if !has_out { |
| 259 | writers.push(Outputter::None); |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | let mut frmnum = 0; |
| 264 | loop { |
| 265 | let pktres = dmx.get_frame(); |
| 266 | if let Err(e) = pktres { |
| 267 | if e == DemuxerError::EOF { break; } |
| 268 | } |
| 269 | let pkt = pktres.unwrap(); |
| 270 | let streamno = pkt.get_stream().get_id(); |
| 271 | let sr = sids.iter().position(|x| *x == streamno); |
| 272 | let idx = sr.unwrap(); |
| 273 | if dump_frames { |
| 274 | let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum)); |
| 275 | let mut ofile = File::create(name).unwrap(); |
| 276 | ofile.write_all(pkt.get_buffer().as_slice()).unwrap(); |
| 277 | frmnum += 1; |
| 278 | } |
| 279 | if let Some((ref mut dsupp, ref mut dec)) = decs[idx] { |
| 280 | match dec.decode(dsupp, &pkt) { |
| 281 | Ok(frm) => { |
| 282 | if !noout { |
| 283 | match writers[idx] { |
| 284 | Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); }, |
| 285 | Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); }, |
| 286 | _ => {}, |
| 287 | }; |
| 288 | } |
| 289 | }, |
| 290 | Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => { |
| 291 | println!("ignoring missing ref"); |
| 292 | }, |
| 293 | Err(reason) => { |
| 294 | println!("error decoding frame {:?}", reason); |
| 295 | if !ignore_errors { |
| 296 | break; |
| 297 | } |
| 298 | }, |
| 299 | }; |
| 300 | if pkt.get_pts() != None && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; } |
| 301 | } |
| 302 | } |
| 303 | //panic!("end"); |
| 304 | } |