aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 929ab6eddebf72a67680e7853c2a795a3ec463b8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
extern crate nihav_core;
extern crate nihav_codec_support;
extern crate nihav_registry;
extern crate nihav_allstuff;

use std::io::{Write, BufReader};
use std::fs::File;
use std::path::Path;
use nihav_core::frame::*;
use nihav_core::codecs::*;
use nihav_core::demuxers::*;
use nihav_codec_support::imgwrite::*;
use std::env;

mod demux;
use demux::*;
mod wavwriter;
use crate::wavwriter::WavWriter;

#[derive(Clone,Copy,PartialEq)]
enum NumberMode {
    Counter,
    PktPTS,
    FrmPTS,
}

struct FrameOutput {
    prefix:     String,
    streamno:   usize,
    frameno:    u64,
    nmode:      NumberMode,
}

impl FrameOutput {
    fn output_frame(&mut self, pkt: &NAPacket, frm: NAFrameRef) {
        if frm.get_frame_type() != FrameType::Skip {
            let pts = match self.nmode {
                    NumberMode::Counter => { self.frameno },
                    NumberMode::PktPTS  => { pkt.get_pts().unwrap() },
                    NumberMode::FrmPTS  => { if let Some(pt) = frm.get_pts() { pt } else { pkt.get_pts().unwrap() } },
                };
            if write_pnm(&self.prefix, self.streamno, pts, frm).is_err() {
                println!("error writing output picture");
            }
        }
        self.frameno += 1;
    }
}

struct AudioOutput {
    wwr:    WavWriter<'static>,
    wrote_header: bool,
}

impl AudioOutput {
    fn new(name: &str) -> Self { Self { wwr: WavWriter::new(name), wrote_header: false } }
    fn output_frame(&mut self, _pkt: &NAPacket, frm: NAFrameRef) {
        if !self.wrote_header {
            self.wwr.write_header(frm.get_info().as_ref().get_properties().get_audio_info().unwrap()).unwrap();
            self.wrote_header = true;
        }
        self.wwr.write_frame(frm.get_buffer()).unwrap();
    }
}

enum Outputter {
    Video(FrameOutput),
    Audio(AudioOutput),
    None,
}

fn main() {
    let args: Vec<_> = env::args().collect();

    if args.len() == 1 {
        println!("usage: nihav-tool [-noout] [-vn] [-an] input [endtime]");
        println!(" or invoke nihav-tool --help for more detailed information");
        return;
    }
    if args.len() == 2 && args[1] == "--help" {
        println!("usage: nihav-tool [options] input [endtime]");
        println!("available options:");
        println!(" -noout     - decode but do not write output");
        println!(" -an        - do not decode audio streams");
        println!(" -vn        - do not decode video streams");
        println!(" -nm={{count,pktpts,frmpts}} - use counter/frame PTS/decoded PTS as output image number");
        println!(" -skip={{key,intra}} - decode only reference frames (I-/P-) or intra frames only");
        println!(" -seek time - try seeking to the given time before starting decoding");
        println!(" -apfx/-vpfx prefix - use given prefix when creating output audio/video files instead of default 'out'");
        println!(" -ignerr    - keep decoding even if decoding error is encountered");
        println!(" -dumpfrm   - dump raw frame data for all streams");
        println!(" endtime    - decoding end time, can be given either as time (hh:mm:ss.ms) or as a timestamp (e.g. 42pts)");
        return;
    }
    let mut lastpts = NATimePoint::None;
    let mut cur_arg: usize = 1;
    let mut noout = false;
    let mut decode_video = true;
    let mut decode_audio = true;
    let mut nmode = NumberMode::FrmPTS;
    let mut smode = FrameSkipMode::None;
    let mut seek_time = NATimePoint::None;
    let mut vpfx: Option<String> = None;
    let mut apfx: Option<&str> = None;
    let mut ignore_errors = false;
    let mut dump_frames = false;
    let mut force_dmx: Option<&str> = None;

    while (cur_arg < args.len()) && args[cur_arg].starts_with('-') {
        match args[cur_arg].as_str() {
            "--"        => { break; },
            "-noout"    => { noout = true; },
            "-an"       => { decode_audio = false; },
            "-vn"       => { decode_video = false; },
            "-nm=count"  => { nmode = NumberMode::Counter; },
            "-nm=pktpts" => { nmode = NumberMode::PktPTS; },
            "-nm=frmpts" => { nmode = NumberMode::FrmPTS; },
            "-skip=key"   => { smode = FrameSkipMode::KeyframesOnly; },
            "-skip=intra" => { smode = FrameSkipMode::IntraOnly; },
            "-seek"     => {
                cur_arg += 1;
                if cur_arg == args.len() {
                    println!("seek time missing");
                    return;
                }
                let ret = args[cur_arg].parse::<NATimePoint>();
                if ret.is_err() {
                    println!("wrong seek time");
                    return;
                }
                seek_time = ret.unwrap();
            },
            "-apfx"     => {
                cur_arg += 1;
                if cur_arg == args.len() {
                    println!("name missing");
                    return;
                }
                apfx = Some(&args[cur_arg]);
            },
            "-vpfx"     => {
                cur_arg += 1;
                if cur_arg == args.len() {
                    println!("name missing");
                    return;
                }
                vpfx = Some(args[cur_arg].clone());
            },
            "-demuxer"     => {
                cur_arg += 1;
                if cur_arg == args.len() {
                    println!("name missing");
                    return;
                }
                force_dmx = Some(&args[cur_arg]);
            },
            "-ignerr"   => { ignore_errors = true; },
            "-dumpfrm"  => { dump_frames = true; },
            _           => { println!("unknown option {}", args[cur_arg]); return; },
        }
        cur_arg += 1;
    }
    let name = args[cur_arg].as_str();
    cur_arg += 1;
    if cur_arg < args.len() {
        let ret = args[cur_arg].parse::<NATimePoint>();
        if ret.is_err() {
            println!("cannot parse end time");
            return;
        }
        lastpts = ret.unwrap();
    }

    let path = Path::new(name);
    let file = File::open(path).unwrap();
    let file = BufReader::new(file);
    let mut fr = FileReader::new_read(file);
    let mut br = ByteReader::new(&mut fr);
    let (is_raw, start, end) = detect_tags(&mut br);

    let mut nfr: Box<dyn ByteIO>;
    if start != 0 || end.is_some() {
        println!(" limiting range to {:X}-{:X}", start, end.unwrap_or(0));
        let file = fr.finish();
        nfr = Box::new(BoundedFileReader::new_read(file, start, end).unwrap());
    } else {
        nfr = Box::new(fr);
    }
    let mut br = ByteReader::new(nfr.as_mut());
    let full_reg = FullRegister::new();
    let mut demuxer = DemuxerObject::create(&mut br, &full_reg, name, force_dmx, is_raw);
    if demuxer.is_none() {
        println!("No demuxer found!");
        return;
    }
    if seek_time != NATimePoint::None {
        let ret = demuxer.seek(seek_time);
        if ret.is_err() {
println!(" seek error {:?}", ret.err().unwrap());
        }
    }

    let mut decs: Vec<Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)>> = Vec::new();
    let mut sids: Vec<u32> = Vec::new();
    let mut writers: Vec<Outputter> = Vec::new();
    let dec_opts = [NAOption{name: FRAME_SKIP_OPTION, value: NAValue::String(smode.to_string())}];
    let duration = demuxer.get_duration();
    if duration != 0 {
        let s = duration / 1000;
        let m = s / 60;
        let h = m / 60;
        println!(" total duration {}:{:02}:{:02}.{}", h, m % 60, s % 60, (duration / 100) % 10);
    }
    for i in 0..demuxer.get_num_streams() {
        let s = demuxer.get_stream(i).unwrap();
        let info = s.get_info();
        let decfunc = full_reg.dec_reg.find_decoder(info.get_name());
println!("stream {} - {} {}", i, s, info.get_name());
        let str_id = s.get_id();
        let mut has_out = false;
        sids.push(str_id);
        if info.is_video() {
            if decode_video {
                if decfunc.is_none() {
                    println!("no video decoder found!");
                    return;
                }
                let mut dec = (decfunc.unwrap())();
                let mut dsupp = Box::new(NADecoderSupport::new());
                dec.init(&mut dsupp, info).unwrap();
                dec.set_options(&dec_opts);
                decs.push(Some((dsupp, dec)));
                if !noout {
                    writers.push(Outputter::Video(FrameOutput{prefix: if let Some(ref str) = vpfx { str.clone() } else { "out".to_string() }, streamno: i, frameno: 1, nmode}));
                    has_out = true;
                }
            } else {
                decs.push(None);
            }
        } else if info.is_audio() {
            if decode_audio {
                if decfunc.is_none() {
                    println!("no audio decoder found!");
                    return;
                }
                let mut dec = (decfunc.unwrap())();
                let mut dsupp = Box::new(NADecoderSupport::new());
                dec.init(&mut dsupp, info).unwrap();
                decs.push(Some((dsupp, dec)));
                if !noout {
                    let name = if let Some(apfx) = apfx {
                            format!("{}{:02}.wav", apfx, i)
                        } else {
                            format!("out{:02}.wav", i)
                        };
                    writers.push(Outputter::Audio(AudioOutput::new(&name)));
                    has_out = true;
                }
            } else {
                decs.push(None);
            }
        } else {
            decs.push(None);
        }
        if !has_out {
            writers.push(Outputter::None);
        }
    }

    let mut frmnum = 0;
    loop {
        let pktres = demuxer.get_frame();
        if let Err(e) = pktres {
            if e == DemuxerError::EOF { break; }
        }
        let pkt = pktres.unwrap();
        let streamno = pkt.get_stream().get_id();
        let sr = sids.iter().position(|x| *x == streamno);
        let idx = sr.unwrap();
        if dump_frames {
            let name = format!("out{:02}_{:08}.frm", streamno, pkt.get_pts().unwrap_or(frmnum));
            let mut ofile = File::create(name).unwrap();
            ofile.write_all(pkt.get_buffer().as_slice()).unwrap();
            frmnum += 1;
        }
        if let Some((ref mut dsupp, ref mut dec)) = decs[idx] {
            match dec.decode(dsupp, &pkt) {
                Ok(frm) => {
                    if !noout {
                        match writers[idx] {
                            Outputter::Video(ref mut wr) => { wr.output_frame(&pkt, frm); },
                            Outputter::Audio(ref mut wr) => { wr.output_frame(&pkt, frm); },
                            _ => {},
                        };
                    }
                },
                Err(DecoderError::MissingReference) if seek_time != NATimePoint::None => {
                    println!("ignoring missing ref");
                },
                Err(reason) => {
                    println!("error decoding frame {:?}", reason);
                    if !ignore_errors {
                        break;
                    }
                },
            };
            if pkt.get_pts() != None && lastpts != NATimePoint::None && !pkt.ts.less_than(lastpts) { break; }
        }
    }
//panic!("end");
}