]> git.nihav.org Git - nihav-player.git/blob - videoplayer/src/main.rs
98d3447c73244b16a24f38821386fdf437dd81c5
[nihav-player.git] / videoplayer / src / main.rs
1 extern crate sdl2;
2 extern crate nihav_core;
3 extern crate nihav_registry;
4 extern crate nihav_allstuff;
5
6 use std::env;
7 use std::fs::File;
8 use std::io::Write;
9 use std::path::Path;
10 use std::time::{Duration, Instant};
11 use std::thread;
12 use std::sync::atomic::{AtomicU8, Ordering};
13
14 use sdl2::event::{Event, WindowEvent};
15 use sdl2::keyboard::{Keycode, Mod};
16 use sdl2::mouse::{MouseButton, MouseWheelDirection};
17 use sdl2::render::{Canvas, Texture, TextureCreator};
18 use sdl2::pixels::PixelFormatEnum;
19 use sdl2::video::{Window, WindowContext};
20
21 use nihav_registry::detect;
22 use nihav_core::frame::*;
23 use nihav_core::io::byteio::{FileReader, ByteReader};
24 use nihav_core::reorder::*;
25 use nihav_core::codecs::*;
26 use nihav_core::demuxers::*;
27 use nihav_registry::register::*;
28 use nihav_allstuff::*;
29
30 mod audiodec;
31 use audiodec::*;
32 mod videodec;
33 use videodec::*;
34 mod osd;
35 use osd::*;
36
37 #[repr(u8)]
38 #[derive(Clone,Copy,Debug,PartialEq,Default)]
39 enum DecodingState {
40 #[default]
41 Normal,
42 Waiting,
43 Flush,
44 Prefetch,
45 Error,
46 End,
47 }
48
49 impl From<u8> for DecodingState {
50 fn from(val: u8) -> Self {
51 match val {
52 0 => DecodingState::Normal,
53 1 => DecodingState::Waiting,
54 2 => DecodingState::Flush,
55 3 => DecodingState::Prefetch,
56 4 => DecodingState::End,
57 _ => DecodingState::Error,
58 }
59 }
60 }
61
62 struct DecoderState {
63 state: AtomicU8
64 }
65
66 impl DecoderState {
67 const fn new() -> Self {
68 Self {
69 state: AtomicU8::new(DecodingState::Normal as u8)
70 }
71 }
72 fn set_state(&self, state: DecodingState) {
73 self.state.store(state as u8, Ordering::Release);
74 }
75 fn get_state(&self) -> DecodingState {
76 self.state.load(Ordering::Acquire).into()
77 }
78 fn is_flushing(&self) -> bool {
79 matches!(self.get_state(), DecodingState::Flush | DecodingState::Error)
80 }
81 }
82
83 #[cfg(feature="debug")]
84 macro_rules! debug_log {
85 ($log: expr; $blk: block) => {
86 $log.logfile.write($blk.as_bytes()).unwrap();
87 $log.logfile.write(b"\n").unwrap();
88 };
89 }
90 #[cfg(not(feature="debug"))]
91 macro_rules! debug_log {
92 ($log: expr; $blk: block) => {};
93 }
94
95 pub enum PktSendEvent {
96 Packet(NAPacket),
97 GetFrames,
98 Flush,
99 End,
100 ImmediateEnd,
101 HurryUp,
102 }
103
104 pub enum DecoderType {
105 Audio(Box<dyn NADecoder + Send>),
106 Video(Box<dyn NADecoder + Send>, Box<dyn FrameReorderer + Send>),
107 VideoMT(Box<dyn NADecoderMT + Send>, MTFrameReorderer),
108 }
109
110 pub struct DecoderStuff {
111 pub dsupp: Box<NADecoderSupport>,
112 pub dec: DecoderType,
113 }
114
115 fn format_time(ms: u64) -> String {
116 let s = ms / 1000;
117 let ds = (ms % 1000) / 100;
118 let (min, s) = (s / 60, s % 60);
119 let (h, min) = (min / 60, min % 60);
120 if h == 0 {
121 if min == 0 {
122 format!("{}.{}", s, ds)
123 } else {
124 format!("{}:{:02}.{}", min, s, ds)
125 }
126 } else {
127 format!("{}:{:02}:{:02}.{}", h, min, s, ds)
128 }
129 }
130
131 const FRAME_QUEUE_LEN: usize = 25;
132 const MAX_VOLUME: usize = 200;
133
134 pub type FrameRecord = (NABufferType, u64);
135
136 pub struct TimeKeep {
137 ref_time: Instant,
138 ref_ts: u64,
139 }
140
141 impl TimeKeep {
142 fn new() -> Self {
143 Self {
144 ref_time: Instant::now(),
145 ref_ts: 0,
146 }
147 }
148 pub fn get_cur_time(&self) -> u64 {
149 let add = self.ref_time.elapsed().as_millis() as u64;
150 self.ref_ts + add
151 }
152 fn reset_ts(&mut self) {
153 self.ref_ts = 0;
154 }
155 fn reset_all(&mut self, ts: u64) {
156 self.ref_time = Instant::now();
157 self.ref_ts = ts;
158 }
159 fn set_ts(&mut self) {
160 self.ref_ts = self.get_cur_time();
161 }
162 fn set_time(&mut self) {
163 self.ref_time = Instant::now();
164 }
165 }
166
167 pub struct DispFrame<'a> {
168 pub ts: u64,
169 pub is_yuv: bool,
170 pub valid: bool,
171 pub rgb_tex: Texture<'a>,
172 pub yuv_tex: Texture<'a>,
173 }
174
175 pub struct DispQueue<'a> {
176 pub pool: Vec<DispFrame<'a>>,
177 pub first_ts: u64,
178 pub last_ts: u64,
179 pub start: usize,
180 pub end: usize,
181 pub len: usize,
182 pub width: usize,
183 pub height: usize,
184 }
185
186 impl<'a> DispQueue<'a> {
187 fn new(texture_creator: &'a TextureCreator<WindowContext>, width: usize, height: usize, len: usize) -> Self {
188 let mut pool = Vec::with_capacity(len);
189 for _ in 0..len + 1 {
190 let rgb_tex = texture_creator.create_texture_streaming(PixelFormatEnum::RGB24, width as u32, height as u32).expect("failed to create RGB texture");
191 let yuv_tex = texture_creator.create_texture_streaming(PixelFormatEnum::IYUV, ((width + 1) & !1) as u32, ((height + 1) & !1) as u32).expect("failed to create YUV texture");
192 pool.push(DispFrame{ ts: 0, is_yuv: false, valid: false, rgb_tex, yuv_tex });
193 }
194 pool[len].is_yuv = false;
195 pool[len].rgb_tex.with_lock(None, |buffer: &mut [u8], _pitch: usize| {
196 for el in buffer.iter_mut() { *el = 0; }
197 }).expect("RGB texture could not be locked");
198
199 Self { pool, first_ts: 0, last_ts: 0, start: 0, end: 0, len, width, height }
200 }
201
202 fn flush(&mut self) {
203 self.start = 0;
204 self.end = 0;
205 self.first_ts = 0;
206 self.last_ts = 0;
207 for frm in self.pool.iter_mut() {
208 frm.valid = false;
209 }
210 }
211
212 fn get_last_texture(&mut self, osd: &OSD) -> &Texture<'a> {
213 if self.pool[self.len].is_yuv {
214 if osd.is_active() {
215 self.pool[self.len].yuv_tex.with_lock(None, |buffer: &mut [u8], pitch: usize| {
216 osd.draw_yuv(buffer, pitch);
217 }).expect("YUV texture locking failure");
218 }
219 &self.pool[self.len].yuv_tex
220 } else {
221 if osd.is_active() {
222 self.pool[self.len].rgb_tex.with_lock(None, |buffer: &mut [u8], pitch: usize| {
223 osd.draw_rgb(buffer, pitch);
224 }).expect("RGB texture locking failure");
225 }
226 &self.pool[self.len].rgb_tex
227 }
228 }
229 pub fn is_empty(&self) -> bool { self.start == self.end }
230 pub fn is_full(&self) -> bool { self.len == 0 || self.start == (self.end + 1) % self.len }
231 pub fn move_end(&mut self) {
232 self.end += 1;
233 if self.end >= self.len {
234 self.end -= self.len;
235 }
236 }
237 pub fn move_start(&mut self) {
238 self.pool.swap(self.start, self.len);
239 self.start += 1;
240 if self.start >= self.len {
241 self.start -= self.len;
242 }
243 if !self.is_empty() {
244 self.first_ts = self.pool[self.start].ts;
245 }
246 }
247 }
248
249 fn try_display(disp_queue: &mut DispQueue, canvas: &mut Canvas<Window>, osd: &mut OSD, ctime: &TimeKeep) -> Option<u64> {
250 while !disp_queue.is_empty() {
251 let disp_time = disp_queue.first_ts;
252 let ctime = ctime.get_cur_time();
253 if disp_time > ctime + 10 {
254 return Some(disp_time - ctime);
255 } else if disp_time + 10 < ctime {
256 disp_queue.move_start();
257 } else {
258 if osd.is_active() {
259 osd.prepare(ctime);
260 }
261 let frm = &mut disp_queue.pool[disp_queue.start];
262 let texture = if frm.is_yuv {
263 if osd.is_active() {
264 frm.yuv_tex.with_lock(None, |buffer: &mut [u8], pitch: usize| {
265 osd.draw_yuv(buffer, pitch);
266 }).expect("YUV texture locking failure");
267 }
268 &frm.yuv_tex
269 } else {
270 if osd.is_active() {
271 frm.rgb_tex.with_lock(None, |buffer: &mut [u8], pitch: usize| {
272 osd.draw_rgb(buffer, pitch);
273 }).expect("RGB texture locking failure");
274 }
275 &frm.rgb_tex
276 };
277 canvas.clear();
278 canvas.copy(texture, None, None).expect("canvas blit failure");
279 canvas.present();
280
281 disp_queue.move_start();
282 if !disp_queue.is_empty() {
283 return Some((disp_queue.first_ts - ctime).saturating_sub(2));
284 } else {
285 return None;
286 }
287 }
288 }
289 None
290 }
291
292 struct Player {
293 sdl_context: sdl2::Sdl,
294 vsystem: sdl2::VideoSubsystem,
295 asystem: sdl2::AudioSubsystem,
296 xpos: Option<i32>,
297 ypos: Option<i32>,
298
299 acontrol: AudioControl,
300 vcontrol: VideoControl,
301
302 play_video: bool,
303 play_audio: bool,
304 has_video: bool,
305 has_audio: bool,
306 video_str: u32,
307 audio_str: u32,
308
309 vthreads: usize,
310 use_mt: bool,
311
312 paused: bool,
313 mute: bool,
314 volume: usize,
315 end: bool,
316
317 tkeep: TimeKeep,
318
319 debug: bool,
320 osd: OSD,
321
322 #[cfg(feature="debug")]
323 logfile: File,
324 }
325
326 impl Player {
327 fn new() -> Self {
328 let sdl_context = sdl2::init().expect("SDL2 init failure");
329 let vsystem = sdl_context.video().expect("video subsystem init failure");
330 let asystem = sdl_context.audio().expect("audio subsystem init failure");
331 vsystem.disable_screen_saver();
332 let acontrol = AudioControl::new(None, None, false, &asystem);
333 let vcontrol = VideoControl::new(None, 0, 0, 0, 0);
334 Self {
335 sdl_context, asystem, vsystem,
336 xpos: None,
337 ypos: None,
338
339 acontrol, vcontrol,
340
341 play_video: true,
342 play_audio: true,
343 has_video: false,
344 has_audio: false,
345 video_str: 0,
346 audio_str: 0,
347
348 vthreads: 3,
349 use_mt: true,
350
351 paused: false,
352 mute: false,
353 volume: 100,
354 end: false,
355
356 tkeep: TimeKeep::new(),
357
358 debug: false,
359 osd: OSD::new(),
360
361 #[cfg(feature="debug")]
362 logfile: File::create("debug.log").expect("'debug.log' should be available for writing"),
363 }
364 }
365 fn seek(&mut self, off: u64, fwd: bool, dmx: &mut Demuxer, disp_queue: &mut DispQueue) -> Result<(), ()> {
366 let cur_time = self.tkeep.get_cur_time();
367 let seektime = if fwd { cur_time + off * 1000 } else {
368 cur_time.saturating_sub(off * 1000) };
369 debug_log!(self; {format!(" seek to {}", seektime)});
370
371 let ret = dmx.seek(NATimePoint::Milliseconds(seektime));
372 if ret.is_err() {
373 println!(" seek error");
374 return Ok(()); //TODO: not ignore some of seek errors?
375 }
376
377 self.acontrol.flush();
378 self.vcontrol.flush();
379 disp_queue.flush();
380
381 self.tkeep.reset_ts();
382 self.prefill(dmx, disp_queue)?;
383 if !disp_queue.is_empty() {
384 self.tkeep.reset_all(disp_queue.first_ts);
385 } else {
386 let mut iterations = 0;
387 let mut time = self.acontrol.get_time();
388 while time.is_none() {
389 iterations += 1;
390 std::thread::yield_now();
391 if iterations > 1000000 { println!(" still no time set?!"); break; }
392 time = self.acontrol.get_time();
393 }
394 if let Some(time) = time {
395 self.tkeep.reset_all(time);
396 }
397 }
398 if !self.paused {
399 self.acontrol.resume();
400 }
401 Ok(())
402 }
403 fn prefill(&mut self, dmx: &mut Demuxer, disp_queue: &mut DispQueue) -> Result<(), ()> {
404 debug_log!(self; {" prefilling"});
405 while self.vcontrol.get_queue_size() < FRAME_QUEUE_LEN {
406 let mut try_send = self.acontrol.get_queue_size() < FRAME_QUEUE_LEN && (!self.has_video || (!self.vcontrol.is_filled(FRAME_QUEUE_LEN) && !disp_queue.is_full()));
407
408 if !self.vcontrol.try_send_queued() && self.vcontrol.get_queue_size() > FRAME_QUEUE_LEN / 2 {
409 try_send = false;
410 }
411 if !self.acontrol.try_send_queued() && self.acontrol.get_queue_size() > FRAME_QUEUE_LEN / 2 {
412 try_send = false;
413 }
414 if try_send {
415 match dmx.get_frame() {
416 Err(DemuxerError::EOF) => break,
417 Err(_) => break,
418 Ok(pkt) => {
419 let streamno = pkt.get_stream().get_id();
420 if self.has_video && streamno == self.video_str {
421 self.vcontrol.try_send_video(PktSendEvent::Packet(pkt));
422 } else if self.has_audio && streamno == self.audio_str {
423 self.acontrol.try_send_audio(PktSendEvent::Packet(pkt));
424 }
425 }
426 };
427 }
428 self.vcontrol.fill(disp_queue);
429
430 if !try_send {
431 break;
432 }
433 }
434 if self.has_video {
435 while self.vcontrol.get_queue_size() > 0 && !disp_queue.is_full() {
436 self.vcontrol.try_send_queued();
437 self.vcontrol.fill(disp_queue);
438 std::thread::sleep(Duration::from_millis(10));
439 }
440 self.vcontrol.wait_for_frames()?;
441 self.vcontrol.fill(disp_queue);
442 }
443 debug_log!(self; {format!(" prefilling done, frames {}-{} audio {}", disp_queue.start, disp_queue.end, self.acontrol.get_fill())});
444 Ok(())
445 }
446 fn toggle_pause(&mut self) {
447 self.paused = !self.paused;
448 if self.paused {
449 self.vsystem.enable_screen_saver();
450 self.tkeep.set_ts();
451 } else {
452 self.vsystem.disable_screen_saver();
453 self.tkeep.set_time();
454 }
455 if self.paused {
456 self.acontrol.pause();
457 } else {
458 self.acontrol.resume();
459 }
460 }
461 fn handle_events(&mut self, event_pump: &mut sdl2::EventPump, canvas: &mut Canvas<Window>, dmx: &mut Demuxer, disp_queue: &mut DispQueue) -> Result<bool, ()> {
462 for event in event_pump.poll_iter() {
463 if let Event::Quit {..} = event {
464 self.end = true;
465 println!();
466 return Ok(true);
467 }
468 if let Event::Window {win_event: WindowEvent::Exposed, ..} = event {
469 canvas.clear();
470 canvas.copy(disp_queue.get_last_texture(&self.osd), None, None).expect("blitting failure");
471 canvas.present();
472 }
473 if let Event::MouseButtonDown {mouse_btn, ..} = event {
474 match mouse_btn {
475 MouseButton::Right => self.toggle_pause(),
476 MouseButton::Middle => self.osd.toggle(),
477 _ => {},
478 };
479 }
480 if let Event::MouseWheel {direction: MouseWheelDirection::Normal, x: 0, y, ..} = event {
481 self.seek(10, y > 0, dmx, disp_queue)?;
482 }
483 if let Event::KeyDown {keycode: Some(keycode), keymod, ..} = event {
484 match keycode {
485 Keycode::Escape => {
486 self.end = true;
487 println!();
488 return Ok(true);
489 },
490 Keycode::Q if keymod.contains(Mod::RSHIFTMOD) || keymod.contains(Mod::LSHIFTMOD) => {
491 self.end = true;
492 println!();
493 return Ok(true);
494 },
495 Keycode::Return => return Ok(true),
496 Keycode::Right => { self.seek(10, true, dmx, disp_queue)?; },
497 Keycode::Left => { self.seek(10, false, dmx, disp_queue)?; },
498 Keycode::Up => { self.seek(60, true, dmx, disp_queue)?; },
499 Keycode::Down => { self.seek(60, false, dmx, disp_queue)?; },
500 Keycode::PageUp => { self.seek(600, true, dmx, disp_queue)?; },
501 Keycode::PageDown => { self.seek(600, false, dmx, disp_queue)?; },
502 Keycode::Space => { self.toggle_pause(); },
503 Keycode::Plus | Keycode::KpPlus => {
504 self.volume = (self.volume + 10).min(MAX_VOLUME);
505 if !self.mute {
506 self.acontrol.set_volume(self.volume);
507 }
508 },
509 Keycode::Minus | Keycode::KpMinus => {
510 self.volume = self.volume.saturating_sub(10);
511 if !self.mute {
512 self.acontrol.set_volume(self.volume);
513 }
514 },
515 Keycode::D => {
516 self.debug = !self.debug;
517 },
518 Keycode::M => {
519 self.mute = !self.mute;
520 if self.mute {
521 self.acontrol.set_volume(0);
522 } else {
523 self.acontrol.set_volume(self.volume);
524 }
525 },
526 Keycode::H => {
527 self.vcontrol.try_send_video(PktSendEvent::HurryUp);
528 },
529 Keycode::O => {
530 self.osd.toggle();
531 },
532 _ => {},
533 };
534 if !self.paused {
535 print!("{:60}\r", ' ');
536 std::io::stdout().flush().unwrap();
537 }
538 }
539 }
540 Ok(false)
541 }
542 fn play(&mut self, name: &str, start_time: NATimePoint) {
543 debug_log!(self; {format!("Playing {}", name)});
544
545 // prepare data source
546 let path = Path::new(name);
547 let mut file = if let Ok(handle) = File::open(path) {
548 handle
549 } else {
550 println!("failed to open {}", name);
551 return;
552 };
553 let mut fr = FileReader::new_read(&mut file);
554 let mut br = ByteReader::new(&mut fr);
555 let res = detect::detect_format(name, &mut br);
556 if res.is_none() {
557 println!("cannot detect format for {}", name);
558 return;
559 }
560 let (dmx_name, _score) = res.unwrap();
561 debug_log!(self; {format!(" found demuxer {} with score {:?}", dmx_name, _score)});
562 println!("trying demuxer {} on {}", dmx_name, name);
563
564 let mut dmx_reg = RegisteredDemuxers::new();
565 nihav_register_all_demuxers(&mut dmx_reg);
566 let mut dec_reg = RegisteredDecoders::new();
567 nihav_register_all_decoders(&mut dec_reg);
568 let mut mtdec_reg = RegisteredMTDecoders::new();
569 if self.use_mt {
570 nihav_register_all_mt_decoders(&mut mtdec_reg);
571 }
572
573 let ret = dmx_reg.find_demuxer(dmx_name);
574 if ret.is_none() {
575 println!("error finding {} demuxer", dmx_name);
576 return;
577 }
578 let dmx_fact = ret.unwrap();
579 br.seek(SeekFrom::Start(0)).expect("should be able to seek to the start");
580 let ret = create_demuxer(dmx_fact, &mut br);
581 if ret.is_err() {
582 println!("error creating demuxer");
583 return;
584 }
585 let mut dmx = ret.unwrap();
586 if start_time != NATimePoint::None {
587 debug_log!(self; {format!(" start seek to {}", start_time)});
588 if dmx.seek(start_time).is_err() {
589 println!("initial seek failed");
590 }
591 }
592
593 let mut width = 640;
594 let mut height = 480;
595 let mut tb_num = 0;
596 let mut tb_den = 0;
597 let mut ainfo: Option<NAAudioInfo> = None;
598 let mut sbr_hack = false;
599
600 let mut video_dec: Option<DecoderStuff> = None;
601 let mut audio_dec: Option<DecoderStuff> = None;
602
603 let duration = dmx.get_duration();
604 if duration != 0 {
605 println!(" total duration {}", format_time(duration));
606 }
607 self.has_video = false;
608 self.has_audio = false;
609 self.osd.reset();
610 self.osd.set_duration(duration);
611 for i in 0..dmx.get_num_streams() {
612 let s = dmx.get_stream(i).unwrap();
613 let info = s.get_info();
614 let decfunc = dec_reg.find_decoder(info.get_name());
615 let decfunc_mt = mtdec_reg.find_decoder(info.get_name());
616 println!("stream {} - {} {}", i, s, info.get_name());
617 debug_log!(self; {format!(" stream {} - {} {}", i, s, info.get_name())});
618 let str_id = s.get_id();
619 if info.is_video() {
620 if video_dec.is_none() && self.play_video {
621 if let Some(decfunc) = decfunc_mt {
622 let mut dec = (decfunc)();
623 let mut dsupp = Box::new(NADecoderSupport::new());
624 let props = info.get_properties().get_video_info().unwrap();
625 if props.get_width() != 0 {
626 width = props.get_width();
627 height = props.get_height();
628 }
629 if dec.init(&mut dsupp, info.clone(), self.vthreads).is_ok() {
630 video_dec = Some(DecoderStuff{ dsupp, dec: DecoderType::VideoMT(dec, MTFrameReorderer::new()) });
631 self.video_str = str_id;
632 let (tbn, tbd) = s.get_timebase();
633 tb_num = tbn;
634 tb_den = tbd;
635 self.has_video = true;
636 continue;
637 } else {
638 println!("failed to create multi-threaded decoder, falling back");
639 }
640 }
641 if let Some(decfunc) = decfunc {
642 let mut dec = (decfunc)();
643 let mut dsupp = Box::new(NADecoderSupport::new());
644 let props = info.get_properties().get_video_info().unwrap();
645 if props.get_width() != 0 {
646 width = props.get_width();
647 height = props.get_height();
648 }
649 let desc = get_codec_description(info.get_name());
650 let (reorder_depth, reord) = if desc.is_none() || (desc.unwrap().caps & CODEC_CAP_COMPLEX_REORDER) == 0 {
651 let reord: Box<dyn FrameReorderer + Send> = Box::new(IPBReorderer::new());
652 (3, reord)
653 } else {
654 let reord: Box<dyn FrameReorderer + Send> = Box::new(ComplexReorderer::new());
655 (16, reord)
656 };
657 dsupp.pool_u8 = NAVideoBufferPool::new(reorder_depth);
658 dsupp.pool_u16 = NAVideoBufferPool::new(reorder_depth);
659 dsupp.pool_u32 = NAVideoBufferPool::new(reorder_depth);
660 if dec.init(&mut dsupp, info).is_err() {
661 println!("failed to initialise video decoder");
662 return;
663 }
664 video_dec = Some(DecoderStuff{ dsupp, dec: DecoderType::Video(dec, reord) });
665 self.video_str = str_id;
666 let (tbn, tbd) = s.get_timebase();
667 tb_num = tbn;
668 tb_den = tbd;
669 self.has_video = true;
670 } else {
671 println!("no video decoder for {} found!", info.get_name());
672 }
673 }
674 } else if info.is_audio() {
675 if audio_dec.is_none() && self.play_audio {
676 if let Some(decfunc) = decfunc {
677 let mut dec = (decfunc)();
678 let mut dsupp = Box::new(NADecoderSupport::new());
679 ainfo = info.get_properties().get_audio_info();
680 if let (true, Some(ref ai)) = (info.get_name() == "aac", ainfo) {
681 if ai.sample_rate < 32000 {
682 sbr_hack = true;
683 }
684 }
685 if dec.init(&mut dsupp, info).is_err() {
686 println!("failed to initialise audio decoder");
687 return;
688 }
689 audio_dec = Some(DecoderStuff{ dsupp, dec: DecoderType::Audio(dec) });
690 self.audio_str = str_id;
691 self.has_audio = true;
692 } else {
693 println!("no audio decoder for {} found!", info.get_name());
694 }
695 }
696 } else {
697 println!("decoder {} not found", info.get_name());
698 }
699 }
700 if !self.has_video && !self.has_audio {
701 println!("No playable streams found.");
702 return;
703 }
704
705 while (width <= 384) && (height <= 288) {
706 width <<= 1;
707 height <<= 1;
708 }
709
710 // prepare playback structure
711 let mut new_vcontrol = VideoControl::new(video_dec, width, height, tb_num, tb_den);
712 std::mem::swap(&mut self.vcontrol, &mut new_vcontrol);
713
714 let mut new_acontrol = AudioControl::new(audio_dec, ainfo, sbr_hack, &self.asystem);
715 std::mem::swap(&mut self.acontrol, &mut new_acontrol);
716
717 if self.mute {
718 self.acontrol.set_volume(0);
719 } else {
720 self.acontrol.set_volume(self.volume);
721 }
722
723 let fname = path.file_name();
724 let wname = if let Some(fname) = fname {
725 "NihAV player - ".to_owned() + fname.to_str().expect("should be able to set window title")
726 } else {
727 "NihAV player".to_owned()
728 };
729 let mut builder = self.vsystem.window(&wname, width as u32, height as u32);
730 let window = if let (Some(xpos), Some(ypos)) = (self.xpos, self.ypos) {
731 builder.position(xpos, ypos).build().expect("should be able to set window position")
732 } else {
733 builder.position_centered().build().expect("should be able to centre window")
734 };
735 let mut canvas = window.into_canvas().build().expect("should be able to build canvas");
736 let texture_creator = canvas.texture_creator();
737 let mut disp_q = DispQueue::new(&texture_creator, width, height, if self.has_video { FRAME_QUEUE_LEN } else { 0 });
738 if !self.has_video {
739 canvas.clear();
740 canvas.copy(disp_q.get_last_texture(&self.osd), None, None).expect("blit failure");
741 canvas.present();
742 }
743
744 self.has_audio = self.acontrol.has_audio();
745 if !self.has_video && !self.has_audio {
746 println!("No playable streams.");
747 return;
748 }
749
750 // play
751 if self.prefill(&mut dmx, &mut disp_q).is_err() {
752 std::mem::swap(&mut self.vcontrol, &mut new_vcontrol);
753 new_vcontrol.finish();
754 std::mem::swap(&mut self.acontrol, &mut new_acontrol);
755 new_acontrol.finish();
756 return;
757 }
758 self.tkeep.reset_all(if !disp_q.is_empty() { disp_q.first_ts } else { 0 });
759 if !self.paused {
760 self.acontrol.resume();
761 }
762 let mut event_pump = self.sdl_context.event_pump().expect("should be able to create event pump");
763 let mut last_disp = Instant::now();
764 let mut has_data = true;
765 'main: loop {
766 let ret = self.handle_events(&mut event_pump, &mut canvas, &mut dmx, &mut disp_q);
767 if matches!(ret, Ok(true) | Err(_)) {
768 println!();
769 break 'main;
770 }
771 if !self.paused {
772 let mut try_send = self.acontrol.get_queue_size() < FRAME_QUEUE_LEN && self.vcontrol.get_queue_size() < FRAME_QUEUE_LEN;
773 if !self.vcontrol.try_send_queued() && self.vcontrol.is_filled(FRAME_QUEUE_LEN) {
774 try_send = false;
775 }
776 if !self.acontrol.try_send_queued() {
777 try_send = false;
778 }
779 while has_data && try_send {
780 match dmx.get_frame() {
781 Err(DemuxerError::EOF) => {
782 self.vcontrol.try_send_video(PktSendEvent::End);
783 self.acontrol.try_send_audio(PktSendEvent::End);
784 has_data = false;
785 },
786 Err(err) => {
787 println!("demuxer error {:?}", err);
788 if err == DemuxerError::IOError {
789 self.vcontrol.try_send_video(PktSendEvent::End);
790 self.acontrol.try_send_audio(PktSendEvent::End);
791 has_data = false;
792 }
793 },
794 Ok(pkt) => {
795 let streamno = pkt.get_stream().get_id();
796 if self.has_video && streamno == self.video_str {
797 debug_log!(self; {" sending video packet"});
798 self.vcontrol.try_send_video(PktSendEvent::Packet(pkt));
799 if self.vcontrol.is_filled(FRAME_QUEUE_LEN) {
800 try_send = false;
801 }
802 } else if self.has_audio && streamno == self.audio_str {
803 debug_log!(self; {" sending audio packet"});
804 self.acontrol.try_send_audio(PktSendEvent::Packet(pkt));
805 if self.acontrol.get_queue_size() >= FRAME_QUEUE_LEN {
806 try_send = false;
807 }
808 }
809 }
810 };
811 }
812 self.vcontrol.fill(&mut disp_q);
813 let mut sleep_time = 25;
814 debug_log!(self; {format!(" time {}", self.tkeep.get_cur_time())});
815 if self.has_video {
816 debug_log!(self; {format!(" disp queue {}-{}, {}-{} vqueue fill {}", disp_q.first_ts, disp_q.last_ts, disp_q.start, disp_q.end, self.vcontrol.get_queue_size())});
817 let ret = try_display(&mut disp_q, &mut canvas, &mut self.osd, &self.tkeep);
818 if let Some(next_time) = ret {
819 sleep_time = sleep_time.min(next_time);
820 }
821 }
822 if self.has_audio {
823 let time_left = self.acontrol.get_time_left();
824 debug_log!(self; {format!(" audio left {}", time_left)});
825 sleep_time = sleep_time.min(time_left);
826 }
827 debug_log!(self; {format!(" sleep {}ms", sleep_time)});
828 if last_disp.elapsed().as_millis() >= 10 {
829 let c_time = self.tkeep.get_cur_time();
830
831 if !self.debug {
832 print!(" {} {}% \r", format_time(c_time), self.acontrol.get_volume());
833 } else {
834 print!(" {} {} {}% {:3} {:6}\r", format_time(c_time), if self.vcontrol.is_yuv() { 'Y' } else { 'R' }, self.acontrol.get_volume(), (disp_q.end + disp_q.len - disp_q.start) % disp_q.len, self.acontrol.get_fill());
835 }
836 std::io::stdout().flush().unwrap();
837 last_disp = Instant::now();
838 }
839 let mut end = true;
840 if self.has_video && !self.vcontrol.is_video_end() {
841 end = false;
842 }
843 if self.has_audio && !self.acontrol.is_audio_end() {
844 end = false;
845 }
846 if end {
847 break;
848 }
849 thread::sleep(Duration::from_millis(sleep_time));
850 } else {
851 thread::sleep(Duration::from_millis(20));
852 }
853 }
854 let (xpos, ypos) = canvas.into_window().position();
855 self.xpos = Some(xpos);
856 self.ypos = Some(ypos);
857 println!();
858 std::mem::swap(&mut self.vcontrol, &mut new_vcontrol);
859 new_vcontrol.finish();
860 std::mem::swap(&mut self.acontrol, &mut new_acontrol);
861 new_acontrol.finish();
862 }
863 }
864
865 fn main() {
866 let args: Vec<String> = env::args().collect();
867
868 if args.len() == 1 {
869 println!("usage: nihav-player file1 file2 ...");
870 return;
871 }
872
873 let mut player = Player::new();
874
875 let mut aiter = args.iter().skip(1);
876 let mut seek_time = NATimePoint::None;
877 while let Some(arg) = aiter.next() {
878 match arg.as_str() {
879 "-an" => { player.play_audio = false; },
880 "-ae" => { player.play_audio = true; },
881 "-vn" => { player.play_video = false; },
882 "-ve" => { player.play_video = true; },
883 "-seek" | "-start" => {
884 if let Some(arg) = aiter.next() {
885 if let Ok(time) = arg.parse::<NATimePoint>() {
886 seek_time = time;
887 } else {
888 println!("wrong seek time");
889 seek_time = NATimePoint::None;
890 }
891 }
892 },
893 "-vol" => {
894 if let Some(arg) = aiter.next() {
895 if let Ok(vol) = arg.parse::<usize>() {
896 player.volume = vol.min(MAX_VOLUME);
897 } else {
898 println!("wrong volume");
899 }
900 }
901 },
902 "-debug" => {
903 player.debug = true;
904 },
905 "-nodebug" => {
906 player.debug = false;
907 },
908 "-mt" => {
909 player.use_mt = true;
910 },
911 "-nomt" => {
912 player.use_mt = false;
913 },
914 "-threads" => {
915 if let Some(arg) = aiter.next() {
916 if let Ok(val) = arg.parse::<usize>() {
917 player.vthreads = val.max(1);
918 } else {
919 println!("wrong number of threads");
920 }
921 }
922 },
923 _ => {
924 player.play(arg, seek_time);
925 if player.end { break; }
926 seek_time = NATimePoint::None;
927 },
928 };
929 }
930 }