]> git.nihav.org Git - nihav-player.git/blob - sndplay/src/main.rs
c8e75a420731439355bad5c45ef1e7f432485aa7
[nihav-player.git] / sndplay / src / main.rs
1 extern crate libc;
2 extern crate sdl2_sys;
3 extern crate nihav_core;
4 extern crate nihav_registry;
5
6 use std::fs::File;
7 use std::io::prelude::*;
8 use std::io::BufReader;
9 use std::sync::mpsc;
10 use std::time::Duration;
11 use std::thread;
12 use sdl2_sys::{SDL_AudioSpec, Uint32};
13 use nihav_core::io::byteio::{FileReader, ByteReader};
14 use nihav_core::frame::*;
15 use nihav_core::codecs::*;
16 use nihav_core::demuxers::*;
17 use nihav_core::soundcvt::*;
18
19 mod allreg;
20 mod command;
21 use command::*;
22 mod demux;
23 use demux::*;
24
25 struct Player {
26 ended: bool,
27 full_reg: allreg::FullRegister,
28 paused: bool,
29 mute: bool,
30 volume: u8,
31 debug: bool,
32 buf: Vec<i16>,
33 }
34
35 struct AudioDevice {
36 device_id: sdl2_sys::SDL_AudioDeviceID
37 }
38
39 impl AudioDevice {
40 fn open(arate: u32, channels: u8) -> Option<(Self, SDL_AudioSpec)> {
41 let desired_spec = SDL_AudioSpec {
42 freq: arate as i32,
43 format: sdl2_sys::AUDIO_S16 as u16,
44 channels,
45 silence: 0,
46 samples: 0,
47 padding: 0,
48 size: 0,
49 callback: None,
50 userdata: std::ptr::null_mut(),
51 };
52 let mut dspec = desired_spec;
53 let device_id = unsafe { sdl2_sys::SDL_OpenAudioDevice(std::ptr::null(), 0, &desired_spec, &mut dspec, 0) };
54 if device_id != 0 {
55 Some((AudioDevice { device_id }, dspec))
56 } else {
57 None
58 }
59 }
60 fn pause(&self) {
61 unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 1); }
62 }
63 fn resume(&self) {
64 unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 0); }
65 }
66 fn clear(&self) {
67 unsafe { sdl2_sys::SDL_ClearQueuedAudio(self.device_id); }
68 }
69 fn queue(&self, buf: &[i16]) {
70 unsafe {
71 let len = buf.len() * 2;
72 let buf_ptr = buf.as_ptr();
73 sdl2_sys::SDL_QueueAudio(self.device_id, buf_ptr as *const core::ffi::c_void, len as Uint32);
74 }
75 }
76 fn queue_bytes(&self, buf: &[u8]) {
77 unsafe {
78 let len = buf.len();
79 let buf_ptr = buf.as_ptr();
80 sdl2_sys::SDL_QueueAudio(self.device_id, buf_ptr as *const core::ffi::c_void, len as Uint32);
81 }
82 }
83 fn size(&self) -> u32 {
84 unsafe { sdl2_sys::SDL_GetQueuedAudioSize(self.device_id) }
85 }
86 }
87
88 impl Drop for AudioDevice {
89 fn drop(&mut self) {
90 unsafe { sdl2_sys::SDL_CloseAudioDevice(self.device_id); }
91 }
92 }
93
94 struct Decoder<'a> {
95 demuxer: DemuxerObject<'a>,
96 decoder: Box<dyn NADecoder>,
97 dsupp: Box<NADecoderSupport>,
98 buf: &'a mut Vec<i16>,
99 stream_no: usize,
100 dst_info: NAAudioInfo,
101 dst_chmap: NAChannelMap,
102 samplepos: u64,
103 arate: u32,
104 volume: u8,
105 mute: bool,
106 }
107
108 fn output_vol_i16(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[i16], mute: bool, volume: u8) {
109 if !mute {
110 tmp.clear();
111 tmp.reserve(src.len());
112 let vol = i32::from(volume);
113 for &sample in src.iter() {
114 let nsamp = vol * i32::from(sample) / 100;
115 tmp.push(nsamp.min(32767).max(-32768) as i16);
116 }
117 } else {
118 tmp.clear();
119 tmp.resize(src.len(), 0);
120 }
121 device.queue(&tmp);
122 }
123
124 fn output_vol_u8(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[u8], mute: bool, volume: u8) {
125 if !mute {
126 tmp.clear();
127 tmp.reserve(src.len());
128 let vol = i32::from(volume);
129 for sample in src.chunks_exact(2) {
130 let sample = (u16::from(sample[0]) + u16::from(sample[1]) * 256) as i16;
131 let nsamp = vol * i32::from(sample) / 100;
132 tmp.push(nsamp.min(32767).max(-32768) as i16);
133 }
134 } else {
135 tmp.clear();
136 tmp.resize(src.len() / 2, 0);
137 }
138 device.queue(&tmp);
139 }
140
141 impl<'a> Decoder<'a> {
142 fn refill(&mut self, device: &AudioDevice) -> bool {
143 loop {
144 match self.demuxer.get_frame() {
145 Ok(pkt) => {
146 if pkt.get_stream().get_num() == self.stream_no {
147 match self.decoder.decode(&mut self.dsupp, &pkt) {
148 Ok(frm) => {
149 let buf = frm.get_buffer();
150 if let NABufferType::None = buf {
151 return false;
152 }
153 if let Some(pts) = frm.ts.get_pts() {
154 self.samplepos = NATimeInfo::ts_to_time(pts, u64::from(self.arate), frm.ts.tb_num, frm.ts.tb_den);
155 }
156 let out_buf = convert_audio_frame(&buf, &self.dst_info, &self.dst_chmap).unwrap();
157 match out_buf {
158 NABufferType::AudioI16(abuf) => {
159 if !self.mute && self.volume == 100 {
160 device.queue(&abuf.get_data());
161 } else {
162 output_vol_i16(device, self.buf, &abuf.get_data(), self.mute, self.volume);
163 }
164 self.samplepos += abuf.get_length() as u64;
165 },
166 NABufferType::AudioPacked(abuf) => {
167 if !self.mute && self.volume == 100 {
168 device.queue_bytes(&abuf.get_data());
169 } else {
170 output_vol_u8(device, self.buf, &abuf.get_data(), self.mute, self.volume);
171 }
172 self.samplepos += abuf.get_length() as u64;
173 },
174 _ => println!("unknown buffer type"),
175 };
176 return false;
177 },
178 Err(err) => {
179 println!(" error decoding {:?}", err);
180 return true;
181 },
182 };
183 }
184 },
185 Err(DemuxerError::EOF) => return true,
186 Err(err) => {
187 println!("demuxing error {:?}", err);
188 return true;
189 },
190 };
191 }
192 }
193 fn seek(&mut self, time: u64) -> bool {
194 let ret = self.demuxer.seek(NATimePoint::Milliseconds(time));
195 if ret.is_err() { println!(" seek error\n"); }
196 ret.is_ok()
197 }
198 }
199
200 fn format_time(ms: u64) -> String {
201 let s = ms / 1000;
202 let ds = (ms % 1000) / 100;
203 let (min, s) = (s / 60, s % 60);
204 let (h, min) = (min / 60, min % 60);
205 if h == 0 {
206 if min == 0 {
207 format!("{}.{}", s, ds)
208 } else {
209 format!("{}:{:02}.{}", min, s, ds)
210 }
211 } else {
212 format!("{}:{:02}:{:02}.{}", h, min, s, ds)
213 }
214 }
215
216 impl Player {
217 fn new() -> Self {
218 let full_reg = allreg::FullRegister::new();
219
220 unsafe {
221 if sdl2_sys::SDL_Init(sdl2_sys::SDL_INIT_AUDIO) != 0 {
222 panic!("cannot init SDL");
223 }
224 }
225
226 Self {
227 ended: false,
228 paused: false,
229 full_reg,
230 volume: 100,
231 mute: false,
232 debug: false,
233 buf: Vec::new(),
234 }
235 }
236 fn play_file(&mut self, name: &str, cmd_receiver: &mpsc::Receiver<Command>, start_time: NATimePoint) {
237 let ret = File::open(name);
238 if ret.is_err() {
239 println!("error opening {}", name);
240 return;
241 }
242 let file = ret.unwrap();
243 let file = BufReader::new(file);
244
245 let mut fr = FileReader::new_read(file);
246 let mut br = ByteReader::new(&mut fr);
247 if br.peek_byte().is_err() {
248 println!("Cannot read {}", name);
249 return;
250 }
251 let (is_raw, start, end) = detect_tags(&mut br);
252
253 let mut nfr: Box<dyn ByteIO>;
254 if start != 0 || end.is_some() {
255 //println!(" limiting range to {:X}-{:X}", start, end.unwrap_or(0));
256 let file = fr.finish();
257 nfr = Box::new(BoundedFileReader::new_read(file, start, end).unwrap());
258 } else {
259 nfr = Box::new(fr);
260 }
261 let mut br = ByteReader::new(nfr.as_mut());
262 let dmx = DemuxerObject::create(&mut br, &self.full_reg, name, is_raw);
263 if dmx.is_none() {
264 println!("No demuxer found!");
265 return;
266 }
267
268 let mut ainfo = None;
269 let mut dec: Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)> = None;
270 let mut stream_no = 0;
271 let mut duration = dmx.get_duration();
272 for i in 0..dmx.get_num_streams() {
273 let s = dmx.get_stream(i).unwrap();
274 let info = s.get_info();
275 if info.is_audio() {
276 let decfunc = self.full_reg.dec_reg.find_decoder(info.get_name());
277 if decfunc.is_none() {
278 println!("no decoder for {}", info.get_name());
279 continue;
280 }
281 let mut decoder = (decfunc.unwrap())();
282 let mut dsupp = Box::new(NADecoderSupport::new());
283 if decoder.init(&mut dsupp, info.clone()).is_err() {
284 println!("cannot init decoder for stream {}", i);
285 continue;
286 }
287 dec = Some((dsupp, decoder));
288 ainfo = Some(info);
289 stream_no = i;
290 if s.duration > 0 {
291 duration = NATimeInfo::ts_to_time(s.duration, 1000, s.tb_num, s.tb_den);
292 }
293 break;
294 }
295 }
296 if dec.is_none() {
297 println!("no audio decoder found");
298 return;
299 }
300 let (dsupp, decoder) = dec.unwrap();
301
302 let ainfo = ainfo.unwrap().get_properties().get_audio_info().unwrap();
303 let arate = if ainfo.sample_rate > 0 { ainfo.sample_rate } else { 44100 };
304 let ch = ainfo.channels;
305
306 println!("Playing {} [{}Hz {}ch]", name, arate, ch);
307 let ret = AudioDevice::open(arate, ch.min(2));
308 if ret.is_none() {
309 println!("cannot open output");
310 return;
311 }
312 let (device, dspec) = ret.unwrap();
313 let block_limit = dmx.get_stream(stream_no).unwrap().tb_num * arate / dmx.get_stream(stream_no).unwrap().tb_den * u32::from(dspec.channels);
314
315 let dst_info = NAAudioInfo { sample_rate: dspec.freq as u32, channels: dspec.channels, format: SND_S16_FORMAT, block_len: 1 };
316 let dst_chmap = if dst_info.channels == 2 {
317 NAChannelMap::from_str("L,R").unwrap()
318 } else {
319 NAChannelMap::from_str("C").unwrap()
320 };
321 let mut decoder = Decoder {
322 demuxer: dmx,
323 decoder, dsupp,
324 stream_no,
325 dst_info, dst_chmap,
326 samplepos: 0,
327 arate,
328 volume: self.volume,
329 mute: self.mute,
330 buf: &mut self.buf,
331 };
332 let mut refill_limit = arate * u32::from(dspec.channels);
333 let underfill_limit = (arate * u32::from(dspec.channels) / 4).max(block_limit);
334
335 if start_time != NATimePoint::None {
336 let _ret = decoder.demuxer.seek(start_time);
337 }
338
339 let mut eof = decoder.refill(&device);
340 while !eof && device.size() < refill_limit {
341 eof = decoder.refill(&device);
342 }
343
344 let duration_str = if duration != 0 { format_time(duration) } else { "???".to_owned() };
345 if !self.paused {
346 device.resume();
347 }
348 let mut no_display = false;
349 'main: loop {
350 let cur_time = decoder.samplepos.saturating_sub(u64::from(device.size() / 2 / u32::from(dst_info.channels)));
351 let full_ms = cur_time * 1000 / u64::from(arate);
352 let timestr = format_time(full_ms);
353 let disp_vol = if self.mute { 0 } else { self.volume };
354 if !no_display {
355 if !self.debug {
356 print!("> {} / {} {}% \r", timestr, duration_str, disp_vol);
357 } else {
358 print!("> {} / {} |{}| {}% \r", timestr, duration_str, device.size(), disp_vol);
359 }
360 }
361 std::io::stdout().flush().unwrap();
362 if device.size() < underfill_limit && !self.paused && refill_limit < (1 << 20) {
363 if full_ms > 5000 {
364 println!("underrun!");
365 }
366 refill_limit += refill_limit >> 1;
367 }
368 if device.size() < refill_limit / 2 {
369 while !eof && device.size() < refill_limit {
370 eof = decoder.refill(&device);
371 }
372 }
373 if eof && device.size() == 0 {
374 break 'main;
375 }
376 while let Ok(cmd) = cmd_receiver.try_recv() {
377 let cur_time = decoder.samplepos.saturating_sub(u64::from(device.size() / 2 / u32::from(dst_info.channels)));
378 match cmd {
379 Command::Forward(val) => {
380 device.pause();
381 device.clear();
382 let seekoff = match val {
383 1 => 10,
384 2 => 60,
385 _ => 10 * 60,
386 };
387 let seek_time = cur_time * 1000 / u64::from(arate) + seekoff * 1000;
388 let _ret = decoder.seek(seek_time);
389 while !eof && device.size() < refill_limit {
390 eof = decoder.refill(&device);
391 }
392 if eof {
393 break 'main;
394 }
395 if !self.paused {
396 device.resume();
397 }
398 },
399 Command::Back(val) => {
400 device.pause();
401 device.clear();
402 let seekoff = match val {
403 1 => 10,
404 2 => 60,
405 _ => 10 * 60,
406 };
407 let seek_time = (cur_time * 1000 / u64::from(arate)).saturating_sub(seekoff * 1000);
408 let _ret = decoder.seek(seek_time);
409 while !eof && device.size() < refill_limit {
410 eof = decoder.refill(&device);
411 }
412 if eof {
413 break 'main;
414 }
415 if !self.paused {
416 device.resume();
417 }
418 },
419 Command::Seek(seek_time) => {
420 device.pause();
421 device.clear();
422 let _ret = decoder.seek(seek_time);
423 while !eof && device.size() < refill_limit {
424 eof = decoder.refill(&device);
425 }
426 if eof {
427 break 'main;
428 }
429 if !self.paused {
430 device.resume();
431 }
432 },
433 Command::Quit => {
434 device.pause();
435 self.ended = true;
436 break 'main;
437 },
438 Command::Next => {
439 device.pause();
440 break 'main;
441 },
442 Command::Repeat => {
443 device.pause();
444 device.clear();
445 let _ret = decoder.seek(0);
446 while !eof && device.size() < refill_limit {
447 eof = decoder.refill(&device);
448 }
449 if eof {
450 break 'main;
451 }
452 if !self.paused {
453 device.resume();
454 }
455 },
456 Command::Pause => {
457 self.paused = !self.paused;
458 if self.paused {
459 device.pause();
460 } else {
461 device.resume();
462 }
463 },
464 Command::VolumeUp => {
465 self.volume = (self.volume + 10).min(200);
466 decoder.volume = self.volume;
467 },
468 Command::VolumeDown => {
469 self.volume = self.volume.saturating_sub(10);
470 decoder.volume = self.volume;
471 },
472 Command::Mute => {
473 self.mute = !self.mute;
474 decoder.mute = self.mute;
475 },
476 Command::Debug => {
477 self.debug = !self.debug;
478 },
479 Command::PauseDisplay => {
480 no_display = true;
481 if !self.paused {
482 device.pause();
483 }
484 },
485 Command::ResumeDisplay => {
486 no_display = false;
487 if !self.paused {
488 device.resume();
489 }
490 },
491 };
492 if !no_display {
493 print!("\r{:60}\r", ' ');
494 }
495 }
496 thread::sleep(Duration::from_millis(200));
497 }
498
499 println!();
500 }
501 }
502
503 fn main() {
504 let args: Vec<String> = std::env::args().collect();
505
506 let cmd_state = CmdLineState::new();
507
508 let (cmd_reader_thread, cmd_receiver) = start_reader();
509 let mut player = Player::new();
510
511 if args.len() == 1 {
512 println!("usage: nihav-sndplay file1 file2 ...");
513 return;
514 }
515
516 if args[1] == "--help" {
517 println!("usage: nihav-sndplay file1 file2 ...");
518 println!("commands:");
519 println!(" escape / q - quit");
520 println!(" space - pause / resume playback");
521 println!(" enter / end - play next file");
522 println!(" home - play current track from the beginning");
523 println!(" left / right - seek 10 seconds forward / back");
524 println!(" up / down - seek 1 minute forward / back");
525 println!(" pgup / pgdn - seek 10 minutes forward / back");
526 println!(" + / - - increase / decrease volume");
527 println!(" m - mute output");
528 return;
529 }
530
531 let mut aiter = args[1..].iter();
532 let mut start_time = NATimePoint::None;
533 while let Some(arg) = aiter.next() {
534 match arg.as_str() {
535 "-start" => {
536 if let Some(arg) = aiter.next() {
537 if let Ok(val) = arg.parse() {
538 start_time = val;
539 } else {
540 println!("invalid time");
541 }
542 } else {
543 println!("argument is required");
544 }
545 },
546 _ => {
547 player.play_file(arg, &cmd_receiver, start_time);
548 if player.ended {
549 break;
550 }
551 start_time = NATimePoint::None;
552 },
553 };
554 }
555 cmd_state.restore();
556
557 drop(cmd_reader_thread);
558 unsafe { sdl2_sys::SDL_Quit(); }
559 }