summaryrefslogtreecommitdiffstats
path: root/sndplay/src/main.rs
blob: c368651a6815e68e3e87e8370d9972eabdc4c3c1 (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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
extern crate libc;
extern crate sdl2_sys;
extern crate nihav_core;
extern crate nihav_registry;

use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::sync::mpsc;
use std::time::Duration;
use std::thread;
use sdl2_sys::{SDL_AudioSpec, Uint32};
use nihav_core::io::byteio::{FileReader, ByteReader};
use nihav_core::frame::*;
use nihav_core::codecs::*;
use nihav_core::demuxers::*;
use nihav_core::soundcvt::*;

mod allreg;
mod command;
use command::*;
mod demux;
use demux::*;

struct Player {
    ended:      bool,
    full_reg:   allreg::FullRegister,
    paused:     bool,
    mute:       bool,
    volume:     u8,
    debug:      bool,
    buf:        Vec<i16>,
}

struct AudioDevice {
    device_id:  sdl2_sys::SDL_AudioDeviceID
}

impl AudioDevice {
    fn open(arate: u32, channels: u8) -> Option<(Self, SDL_AudioSpec)> {
        let desired_spec = SDL_AudioSpec {
            freq:       arate as i32,
            format:     sdl2_sys::AUDIO_S16 as u16,
            channels,
            silence:    0,
            samples:    0,
            padding:    0,
            size:       0,
            callback:   None,
            userdata:   std::ptr::null_mut(),
        };
        let mut dspec = desired_spec;
        let device_id = unsafe { sdl2_sys::SDL_OpenAudioDevice(std::ptr::null(), 0, &desired_spec, &mut dspec, 0) };
        if device_id != 0 {
            Some((AudioDevice { device_id }, dspec))
        } else {
            None
        }
    }
    fn pause(&self) {
        unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 1); }
    }
    fn resume(&self) {
        unsafe { sdl2_sys::SDL_PauseAudioDevice(self.device_id, 0); }
    }
    fn clear(&self) {
        unsafe { sdl2_sys::SDL_ClearQueuedAudio(self.device_id); }
    }
    fn queue(&self, buf: &[i16]) {
        unsafe {
            let len = buf.len() * 2;
            let buf_ptr = buf.as_ptr();
            sdl2_sys::SDL_QueueAudio(self.device_id, buf_ptr as *const core::ffi::c_void, len as Uint32);
        }
    }
    fn queue_bytes(&self, buf: &[u8]) {
        unsafe {
            let len = buf.len();
            let buf_ptr = buf.as_ptr();
            sdl2_sys::SDL_QueueAudio(self.device_id, buf_ptr as *const core::ffi::c_void, len as Uint32);
        }
    }
    fn size(&self) -> u32 {
        unsafe { sdl2_sys::SDL_GetQueuedAudioSize(self.device_id) }
    }
}

impl Drop for AudioDevice {
    fn drop(&mut self) {
        unsafe { sdl2_sys::SDL_CloseAudioDevice(self.device_id); }
    }
}

struct Decoder<'a> {
    demuxer:    DemuxerObject<'a>,
    decoder:    Box<dyn NADecoder>,
    dsupp:      Box<NADecoderSupport>,
    buf:        &'a mut Vec<i16>,
    stream_no:  usize,
    dst_info:   NAAudioInfo,
    dst_chmap:  NAChannelMap,
    samplepos:  u64,
    arate:      u32,
    volume:     u8,
    mute:       bool,
}

fn output_vol_i16(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[i16], mute: bool, volume: u8) {
    if !mute {
        tmp.clear();
        tmp.reserve(src.len());
        let vol = i32::from(volume);
        for &sample in src.iter() {
            let nsamp = vol * i32::from(sample) / 100;
            tmp.push(nsamp.min(32767).max(-32768) as i16);
        }
    } else {
        tmp.clear();
        tmp.resize(src.len(), 0);
    }
    device.queue(&tmp);
}

fn output_vol_u8(device: &AudioDevice, tmp: &mut Vec<i16>, src: &[u8], mute: bool, volume: u8) {
    if !mute {
        tmp.clear();
        tmp.reserve(src.len());
        let vol = i32::from(volume);
        for sample in src.chunks_exact(2) {
            let sample = (u16::from(sample[0]) + u16::from(sample[1]) * 256) as i16;
            let nsamp = vol * i32::from(sample) / 100;
            tmp.push(nsamp.min(32767).max(-32768) as i16);
        }
    } else {
        tmp.clear();
        tmp.resize(src.len() / 2, 0);
    }
    device.queue(&tmp);
}

impl<'a> Decoder<'a> {
    fn refill(&mut self, device: &AudioDevice) -> bool {
        loop {
            match self.demuxer.get_frame() {
                Ok(pkt) => {
                    if pkt.get_stream().get_num() == self.stream_no {
                        match self.decoder.decode(&mut self.dsupp, &pkt) {
                            Ok(frm) => {
                                let buf = frm.get_buffer();
                                if let NABufferType::None = buf {
                                    return false;
                                }
                                if let Some(pts) = frm.ts.get_pts() {
                                    self.samplepos = NATimeInfo::ts_to_time(pts, u64::from(self.arate), frm.ts.tb_num, frm.ts.tb_den);
                                }
                                if buf.get_audio_length() == 0 {
                                    return false;
                                }
                                let out_buf = convert_audio_frame(&buf, &self.dst_info, &self.dst_chmap).unwrap();
                                match out_buf {
                                    NABufferType::AudioI16(abuf) => {
                                        if !self.mute && self.volume == 100 {
                                            device.queue(&abuf.get_data());
                                        } else {
                                            output_vol_i16(device, self.buf, &abuf.get_data(), self.mute, self.volume);
                                        }
                                        self.samplepos += abuf.get_length() as u64;
                                    },
                                    NABufferType::AudioPacked(abuf) => {
                                        if !self.mute && self.volume == 100 {
                                            device.queue_bytes(&abuf.get_data());
                                        } else {
                                            output_vol_u8(device, self.buf, &abuf.get_data(), self.mute, self.volume);
                                        }
                                        self.samplepos += abuf.get_length() as u64;
                                    },
                                    _ => println!("unknown buffer type"),
                                };
                                return false;
                            },
                            Err(err) => {
                                println!(" error decoding {:?}", err);
                                return true;
                            },
                        };
                    }
                },
                Err(DemuxerError::EOF) => return true,
                Err(err) => {
                    println!("demuxing error {:?}", err);
                    return true;
                },
            };
        }
    }
    fn seek(&mut self, time: u64) -> bool {
        let ret = self.demuxer.seek(NATimePoint::Milliseconds(time));
if ret.is_err() { println!(" seek error\n"); }
        self.decoder.flush();
        ret.is_ok()
    }
}

fn format_time(ms: u64) -> String {
    let s = ms / 1000;
    let ds = (ms % 1000) / 100;
    let (min, s) = (s / 60, s % 60);
    let (h, min) = (min / 60, min % 60);
    if h == 0 {
        if min == 0 {
            format!("{}.{}", s, ds)
        } else {
            format!("{}:{:02}.{}", min, s, ds)
        }
    } else {
        format!("{}:{:02}:{:02}.{}", h, min, s, ds)
    }
}

impl Player {
    fn new() -> Self {
        let full_reg = allreg::FullRegister::new();

        unsafe {
            if sdl2_sys::SDL_Init(sdl2_sys::SDL_INIT_AUDIO) != 0 {
                panic!("cannot init SDL");
            }
        }

        Self {
            ended:  false,
            paused: false,
            full_reg,
            volume: 100,
            mute:   false,
            debug:  false,
            buf:    Vec::new(),
        }
    }
    fn play_file(&mut self, name: &str, cmd_receiver: &mpsc::Receiver<Command>, start_time: NATimePoint) {
        let ret = File::open(name);
        if ret.is_err() {
            println!("error opening {}", name);
            return;
        }
        let file = ret.unwrap();
        let file = BufReader::new(file);

        let mut fr = FileReader::new_read(file);
        let mut br = ByteReader::new(&mut fr);
        if br.peek_byte().is_err() {
            println!("Cannot read {}", name);
            return;
        }
        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 dmx = DemuxerObject::create(&mut br, &self.full_reg, name, is_raw);
        if dmx.is_none() {
            println!("No demuxer found!");
            return;
        }

        let mut ainfo = None;
        let mut dec: Option<(Box<NADecoderSupport>, Box<dyn NADecoder>)> = None;
        let mut stream_no = 0;
        let mut duration = dmx.get_duration();
        for i in 0..dmx.get_num_streams() {
            let s = dmx.get_stream(i).unwrap();
            let info = s.get_info();
            if info.is_audio() {
                let decfunc = self.full_reg.dec_reg.find_decoder(info.get_name());
                if decfunc.is_none() {
                    println!("no decoder for {}", info.get_name());
                    continue;
                }
                let mut decoder = (decfunc.unwrap())();
                let mut dsupp = Box::new(NADecoderSupport::new());
                if decoder.init(&mut dsupp, info.clone()).is_err() {
                    println!("cannot init decoder for stream {}", i);
                    continue;
                }
                dec = Some((dsupp, decoder));
                ainfo = Some(info);
                stream_no = i;
                if s.duration > 0 {
                    duration = NATimeInfo::ts_to_time(s.duration, 1000, s.tb_num, s.tb_den);
                }
                break;
            }
        }
        if dec.is_none() {
            println!("no audio decoder found");
            return;
        }
        let (dsupp, decoder) = dec.unwrap();

        let ainfo = ainfo.unwrap().get_properties().get_audio_info().unwrap();
        let arate = if ainfo.sample_rate > 0 { ainfo.sample_rate } else { 44100 };
        let ch    = ainfo.channels;

        println!("Playing {} [{}Hz {}ch]", name, arate, ch);
        let ret = AudioDevice::open(arate, ch.min(2));
        if ret.is_none() {
            println!("cannot open output");
            return;
        }
        let (device, dspec) = ret.unwrap();
        let block_limit = dmx.get_stream(stream_no).unwrap().tb_num * arate / dmx.get_stream(stream_no).unwrap().tb_den * u32::from(dspec.channels);

        let dst_info = NAAudioInfo { sample_rate: dspec.freq as u32, channels: dspec.channels, format: SND_S16_FORMAT, block_len: 1 };
        let dst_chmap = if dst_info.channels == 2 {
                NAChannelMap::from_str("L,R").unwrap()
            } else {
                NAChannelMap::from_str("C").unwrap()
            };
        let mut decoder = Decoder {
                demuxer:    dmx,
                decoder, dsupp,
                stream_no,
                dst_info, dst_chmap,
                samplepos: 0,
                arate,
                volume: self.volume,
                mute:   self.mute,
                buf:    &mut self.buf,
            };
        let mut refill_limit = arate * u32::from(dspec.channels);
        let underfill_limit = (arate * u32::from(dspec.channels) / 4).max(block_limit);

        if start_time != NATimePoint::None {
            let _ret = decoder.demuxer.seek(start_time);
        }

        let mut eof = decoder.refill(&device);
        while !eof && device.size() < refill_limit {
            eof = decoder.refill(&device);
        }

        let duration_str = if duration != 0 { format_time(duration) } else { "???".to_owned() };
        if !self.paused {
            device.resume();
        }
        let mut no_display = false;
        'main: loop {
            let cur_time = decoder.samplepos.saturating_sub(u64::from(device.size() / 2 / u32::from(dst_info.channels)));
            let full_ms = cur_time * 1000 / u64::from(arate);
            let timestr = format_time(full_ms);
            let disp_vol = if self.mute { 0 } else { self.volume };
            if !no_display {
                if !self.debug {
                    print!("> {} / {}   {}%       \r", timestr, duration_str, disp_vol);
                } else {
                    print!("> {} / {}   |{}| {}%       \r", timestr, duration_str, device.size(), disp_vol);
                }
            }
            std::io::stdout().flush().unwrap();
            if device.size() < underfill_limit && !self.paused && (refill_limit < (1 << 20)) & !eof {
                if full_ms > 5000 {
                    println!("underrun!");
                }
                refill_limit += refill_limit >> 1;
            }
            if device.size() < refill_limit / 2 {
                while !eof && device.size() < refill_limit {
                    eof = decoder.refill(&device);
                }
            }
            if eof && device.size() == 0 {
                break 'main;
            }
            while let Ok(cmd) = cmd_receiver.try_recv() {
                let cur_time = decoder.samplepos.saturating_sub(u64::from(device.size() / 2 / u32::from(dst_info.channels)));
                match cmd {
                    Command::Forward(val) => {
                        device.pause();
                        device.clear();
                        let seekoff = match val {
                                1 => 10,
                                2 => 60,
                                _ => 10 * 60,
                            };
                        let seek_time = cur_time * 1000 / u64::from(arate) + seekoff * 1000;
                        let _ret = decoder.seek(seek_time);
                        while !eof && device.size() < refill_limit {
                            eof = decoder.refill(&device);
                        }
                        if eof {
                            break 'main;
                        }
                        if !self.paused {
                            device.resume();
                        }
                    },
                    Command::Back(val) => {
                        device.pause();
                        device.clear();
                        let seekoff = match val {
                                1 => 10,
                                2 => 60,
                                _ => 10 * 60,
                            };
                        let seek_time = (cur_time * 1000 / u64::from(arate)).saturating_sub(seekoff * 1000);
                        let _ret = decoder.seek(seek_time);
                        while !eof && device.size() < refill_limit {
                            eof = decoder.refill(&device);
                        }
                        if eof {
                            break 'main;
                        }
                        if !self.paused {
                            device.resume();
                        }
                    },
                    Command::Seek(seek_time) => {
                        device.pause();
                        device.clear();
                        let _ret = decoder.seek(seek_time);
                        while !eof && device.size() < refill_limit {
                            eof = decoder.refill(&device);
                        }
                        if eof {
                            break 'main;
                        }
                        if !self.paused {
                            device.resume();
                        }
                    },
                    Command::Quit => {
                        device.pause();
                        self.ended = true;
                        break 'main;
                    },
                    Command::Next => {
                        device.pause();
                        break 'main;
                    },
                    Command::Repeat => {
                        device.pause();
                        device.clear();
                        let _ret = decoder.seek(0);
                        while !eof && device.size() < refill_limit {
                            eof = decoder.refill(&device);
                        }
                        if eof {
                            break 'main;
                        }
                        if !self.paused {
                            device.resume();
                        }
                    },
                    Command::Pause => {
                        self.paused = !self.paused;
                        if self.paused {
                            device.pause();
                        } else {
                            device.resume();
                        }
                    },
                    Command::VolumeUp => {
                        self.volume = (self.volume + 10).min(200);
                        decoder.volume = self.volume;
                    },
                    Command::VolumeDown => {
                        self.volume = self.volume.saturating_sub(10);
                        decoder.volume = self.volume;
                    },
                    Command::Mute => {
                        self.mute = !self.mute;
                        decoder.mute = self.mute;
                    },
                    Command::Debug => {
                        self.debug = !self.debug;
                    },
                    Command::PauseDisplay  => {
                        no_display = true;
                        if !self.paused {
                            device.pause();
                        }
                    },
                    Command::ResumeDisplay => {
                        no_display = false;
                        if !self.paused {
                            device.resume();
                        }
                    },
                };
                if !no_display {
                    print!("\r{:60}\r", ' ');
                }
            }
            thread::sleep(Duration::from_millis(200));
        }

        println!();
    }
}

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

    let cmd_state = CmdLineState::new();

    let (cmd_reader_thread, cmd_receiver) = start_reader();
    let mut player = Player::new();

    if args.len() == 1 {
        println!("usage: nihav-sndplay file1 file2 ...");
        return;
    }

    if args[1] == "--help" {
        println!("usage: nihav-sndplay file1 file2 ...");
        println!("commands:");
        println!("  escape / q      - quit");
        println!("  space           - pause / resume playback");
        println!("  enter / end     - play next file");
        println!("  home            - play current track from the beginning");
        println!("  left / right    - seek 10 seconds forward / back");
        println!("  up / down       - seek 1 minute forward / back");
        println!("  pgup / pgdn     - seek 10 minutes forward / back");
        println!("  + / -           - increase / decrease volume");
        println!("  m               - mute output");
        return;
    }

    let mut aiter = args[1..].iter();
    let mut start_time = NATimePoint::None;
    while let Some(arg) = aiter.next() {
        match arg.as_str() {
            "-start" => {
                if let Some(arg) = aiter.next() {
                    if let Ok(val) = arg.parse() {
                        start_time = val;
                    } else {
                        println!("invalid time");
                    }
                } else {
                    println!("argument is required");
                }
            },
            _ => {
                player.play_file(arg, &cmd_receiver, start_time);
                if player.ended {
                    break;
                }
                start_time = NATimePoint::None;
            },
        };
    }
    cmd_state.restore();

    drop(cmd_reader_thread);
    unsafe { sdl2_sys::SDL_Quit(); }
}