3 extern crate nihav_core;
4 extern crate nihav_registry;
7 use std::io::prelude::*;
8 use std::io::BufReader;
10 use std::time::Duration;
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::*;
27 full_reg: allreg::FullRegister,
36 device_id: sdl2_sys::SDL_AudioDeviceID
40 fn open(arate: u32, channels: u8) -> Option<(Self, SDL_AudioSpec)> {
41 let desired_spec = SDL_AudioSpec {
43 format: sdl2_sys::AUDIO_S16 as u16,
50 userdata: std::ptr::null_mut(),
52 let mut dspec = desired_spec;
53 let device_id = unsafe { sdl2_sys::SDL_OpenAudioDevice(std::ptr::null(), 0, &desired_spec, &mut dspec, 0) };
55 Some((AudioDevice { device_id }, dspec))
61 unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 1); }
64 unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 0); }
67 unsafe { sdl2_sys::SDL_ClearQueuedAudio(self.device_id); }
69 fn queue(&self, buf: &[i16]) {
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);
76 fn queue_bytes(&self, buf: &[u8]) {
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);
83 fn size(&self) -> u32 {
84 unsafe { sdl2_sys::SDL_GetQueuedAudioSize(self.device_id) }
88 impl Drop for AudioDevice {
90 unsafe { sdl2_sys::SDL_CloseAudioDevice(self.device_id); }
95 demuxer: DemuxerObject<'a>,
96 decoder: Box<dyn NADecoder>,
97 dsupp: Box<NADecoderSupport>,
98 buf: &'a mut Vec<i16>,
100 dst_info: NAAudioInfo,
101 dst_chmap: NAChannelMap,
108 fn output_vol_i16(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[i16], mute: bool, volume: u8) {
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);
119 tmp.resize(src.len(), 0);
124 fn output_vol_u8(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[u8], mute: bool, volume: u8) {
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);
136 tmp.resize(src.len() / 2, 0);
141 impl<'a> Decoder<'a> {
142 fn refill(&mut self, device: &AudioDevice) -> bool {
144 match self.demuxer.get_frame() {
146 if pkt.get_stream().get_num() == self.stream_no {
147 match self.decoder.decode(&mut self.dsupp, &pkt) {
149 let buf = frm.get_buffer();
150 if let NABufferType::None = buf {
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);
156 let out_buf = convert_audio_frame(&buf, &self.dst_info, &self.dst_chmap).unwrap();
158 NABufferType::AudioI16(abuf) => {
159 if !self.mute && self.volume == 100 {
160 device.queue(&abuf.get_data());
162 output_vol_i16(device, self.buf, &abuf.get_data(), self.mute, self.volume);
164 self.samplepos += abuf.get_length() as u64;
166 NABufferType::AudioPacked(abuf) => {
167 if !self.mute && self.volume == 100 {
168 device.queue_bytes(&abuf.get_data());
170 output_vol_u8(device, self.buf, &abuf.get_data(), self.mute, self.volume);
172 self.samplepos += abuf.get_length() as u64;
174 _ => println!("unknown buffer type"),
179 println!(" error decoding {:?}", err);
185 Err(DemuxerError::EOF) => return true,
187 println!("demuxing error {:?}", err);
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"); }
200 fn format_time(ms: u64) -> String {
202 let ds = (ms % 1000) / 100;
203 let (min, s) = (s / 60, s % 60);
204 let (h, min) = (min / 60, min % 60);
207 format!("{}.{}", s, ds)
209 format!("{}:{:02}.{}", min, s, ds)
212 format!("{}:{:02}:{:02}.{}", h, min, s, ds)
218 let full_reg = allreg::FullRegister::new();
221 if sdl2_sys::SDL_Init(sdl2_sys::SDL_INIT_AUDIO) != 0 {
222 panic!("cannot init SDL");
236 fn play_file(&mut self, name: &str, cmd_receiver: &mpsc::Receiver<Command>, start_time: NATimePoint) {
237 let ret = File::open(name);
239 println!("error opening {}", name);
242 let file = ret.unwrap();
243 let file = BufReader::new(file);
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);
251 let (is_raw, start, end) = detect_tags(&mut br);
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());
261 let mut br = ByteReader::new(nfr.as_mut());
262 let dmx = DemuxerObject::create(&mut br, &self.full_reg, name, is_raw);
264 println!("No demuxer found!");
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();
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());
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);
287 dec = Some((dsupp, decoder));
291 duration = NATimeInfo::ts_to_time(s.duration, 1000, s.tb_num, s.tb_den);
297 println!("no audio decoder found");
300 let (dsupp, decoder) = dec.unwrap();
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;
306 println!("Playing {} [{}Hz {}ch]", name, arate, ch);
307 let ret = AudioDevice::open(arate, ch.min(2));
309 println!("cannot open output");
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);
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()
319 NAChannelMap::from_str("C").unwrap()
321 let mut decoder = Decoder {
332 let mut refill_limit = arate * u32::from(dspec.channels);
333 let underfill_limit = (arate * u32::from(dspec.channels) / 4).max(block_limit);
335 if start_time != NATimePoint::None {
336 let _ret = decoder.demuxer.seek(start_time);
339 let mut eof = decoder.refill(&device);
340 while !eof && device.size() < refill_limit {
341 eof = decoder.refill(&device);
344 let duration_str = if duration != 0 { format_time(duration) } else { "???".to_owned() };
348 let mut no_display = false;
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 };
356 print!("> {} / {} {}% \r", timestr, duration_str, disp_vol);
358 print!("> {} / {} |{}| {}% \r", timestr, duration_str, device.size(), disp_vol);
361 std::io::stdout().flush().unwrap();
362 if device.size() < underfill_limit && !self.paused && refill_limit < (1 << 20) {
364 println!("underrun!");
366 refill_limit += refill_limit >> 1;
368 if device.size() < refill_limit / 2 {
369 while !eof && device.size() < refill_limit {
370 eof = decoder.refill(&device);
373 if eof && device.size() == 0 {
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)));
379 Command::Forward(val) => {
382 let seekoff = match val {
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);
399 Command::Back(val) => {
402 let seekoff = match val {
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);
419 Command::Seek(seek_time) => {
422 let _ret = decoder.seek(seek_time);
423 while !eof && device.size() < refill_limit {
424 eof = decoder.refill(&device);
445 let _ret = decoder.seek(0);
446 while !eof && device.size() < refill_limit {
447 eof = decoder.refill(&device);
457 self.paused = !self.paused;
464 Command::VolumeUp => {
465 self.volume = (self.volume + 10).min(200);
466 decoder.volume = self.volume;
468 Command::VolumeDown => {
469 self.volume = self.volume.saturating_sub(10);
470 decoder.volume = self.volume;
473 self.mute = !self.mute;
474 decoder.mute = self.mute;
477 self.debug = !self.debug;
479 Command::PauseDisplay => {
485 Command::ResumeDisplay => {
493 print!("\r{:60}\r", ' ');
496 thread::sleep(Duration::from_millis(200));
504 let args: Vec<String> = std::env::args().collect();
506 let cmd_state = CmdLineState::new();
508 let (cmd_reader_thread, cmd_receiver) = start_reader();
509 let mut player = Player::new();
512 println!("usage: nihav-sndplay file1 file2 ...");
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");
531 let mut aiter = args[1..].iter();
532 let mut start_time = NATimePoint::None;
533 while let Some(arg) = aiter.next() {
536 if let Some(arg) = aiter.next() {
537 if let Ok(val) = arg.parse() {
540 println!("invalid time");
543 println!("argument is required");
547 player.play_file(arg, &cmd_receiver, start_time);
551 start_time = NATimePoint::None;
557 drop(cmd_reader_thread);
558 unsafe { sdl2_sys::SDL_Quit(); }