summaryrefslogtreecommitdiffstats
path: root/videoplayer/src/audiodec.rs
blob: ad906f0f997f709bf9a4e97ee04629d2366a0f19 (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
use std::time::Duration;
use std::thread::JoinHandle;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError};
use std::str::FromStr;

use sdl2::AudioSubsystem;
use sdl2::audio::{AudioDevice, AudioCallback, AudioSpecDesired};

use nihav_core::formats::*;
use nihav_core::codecs::*;
use nihav_core::soundcvt::*;

use super::{DecoderStuff, DecoderType, DecoderState, DecodingState, PktSendEvent};

static ADEC_STATE: DecoderState = DecoderState::new();
static AUDIO_VOLUME: AtomicUsize = AtomicUsize::new(100);
static CUR_QUEUE_FILL: AtomicUsize = AtomicUsize::new(0);
static SAMPLE_RATE: AtomicUsize = AtomicUsize::new(0);
static CHANNELS: AtomicUsize = AtomicUsize::new(0);

static CURRENT_TIME: AtomicUsize = AtomicUsize::new(0);
static CURRENT_TIME_SET: AtomicBool = AtomicBool::new(false);

const QUEUE_INITIAL_SIZE: usize = 16384;
const QUEUE_REFILL_LIMIT: usize = 262144;

struct AudioQueue {
    queue:  Vec<i16>,
    start:  usize,
    end:    usize,
    srate:  usize,
    chans:  usize,
    spos:   usize,
}

impl AudioQueue {
    fn new(srate: usize, chans: usize) -> Self {
        SAMPLE_RATE.store(srate, Ordering::Relaxed);
        CHANNELS.store(chans, Ordering::Relaxed);
        CUR_QUEUE_FILL.store(0, Ordering::Relaxed);
        Self {
            queue:  Vec::with_capacity(QUEUE_INITIAL_SIZE),
            start:  0,
            end:    0,
            srate, chans,
            spos:   0,
        }
    }
    fn home(&mut self) {
        if self.start == 0 { return; }
        let fill = self.fill();
        if fill > 0 {
            if fill < self.start {
                let (dst, src) = self.queue.split_at_mut(self.start);
                dst[..fill].copy_from_slice(&src[..fill]);
            } else {
                for i in 0..fill {
                    self.queue[i] = self.queue[self.start + i];
                }
            }
        }
        self.start = 0;
        self.end = fill;
    }
    fn set_time(&mut self) {
        let fill = self.fill();
        let samp_time = self.spos.saturating_sub(fill / self.chans);
        CURRENT_TIME.store(samp_time * 1000 / self.srate, Ordering::Relaxed);
        CURRENT_TIME_SET.store(true, Ordering::Relaxed);
        CUR_QUEUE_FILL.store(self.fill(), Ordering::Relaxed);
    }
    fn add(&mut self, src: &[i16], samplepos: usize) {
        if self.end + src.len() > self.queue.len() {
            self.home();
        }
        if self.end + src.len() > self.queue.len() {
            self.queue.resize(self.end + src.len(), 0);
        }
        self.queue[self.end..][..src.len()].copy_from_slice(&src);
        self.end += src.len();
        self.spos = samplepos;
        self.set_time();
    }
    fn add_bytes(&mut self, src: &[u8], samplepos: usize) {
        let srclen = src.len() / 2;
        if self.end + srclen > self.queue.len() {
            self.home();
        }
        if self.end + srclen > self.queue.len() {
            self.queue.resize(self.end + srclen, 0);
        }
        for (dst, src) in self.queue[self.end..][..srclen].iter_mut().zip(src.chunks_exact(2)) {
            *dst = (u16::from(src[0]) + u16::from(src[1]) * 256) as i16;
        }
        self.end += srclen;
        self.spos = samplepos;
        self.set_time();
    }
    fn drain(&mut self, size: usize) {
        let fill = self.fill();
        if size >= fill {
            self.flush();
        } else {
            self.start += size;
        }
        self.set_time();
    }
    fn fill(&self) -> usize { self.end - self.start }
    fn flush(&mut self) {
        self.start  = 0;
        self.end    = 0;
    }
}

pub struct AudioOutput {
    queue:      Arc<Mutex<AudioQueue>>,
}

impl AudioCallback for AudioOutput {
    type Channel = i16;

    fn callback(&mut self, out: &mut [Self::Channel]) {
        let mut queue = self.queue.lock().expect("audio queue should be accessible");
        let dstlen = out.len();
        let copylen = queue.fill().min(dstlen);
        let volume = AUDIO_VOLUME.load(Ordering::Relaxed) as i32;
        if volume == 100 {
            out[..copylen].copy_from_slice(&queue.queue[queue.start..][..copylen]);
        } else {
            for (dst, &src) in out[..copylen].iter_mut().zip(queue.queue[queue.start..].iter()) {
                *dst = (i32::from(src) * volume / 100).max(-32768).min(32767) as i16;
            }
        }
        queue.drain(copylen);
        for el in out[copylen..].iter_mut() { *el = 0; }
    }
}

fn dummy_audio_thread(aprecv: Receiver<PktSendEvent>) -> JoinHandle<()> {
    std::thread::Builder::new().name("acontrol-dummy".to_string()).spawn(move ||{
                    loop {
                        match aprecv.recv() {
                            Ok(PktSendEvent::End) => break,
                            Ok(PktSendEvent::ImmediateEnd) => break,
                            Err(_) => {
                                break;
                            },
                            _ => {},
                        };
                    }
                }).unwrap()
}

type AudioPlaybackType = Option<AudioDevice<AudioOutput>>;

fn start_audio_decoding(asystem: &AudioSubsystem, ainfo: NAAudioInfo, sbr_hack: bool, mut audio_dec: DecoderStuff, aprecv: Receiver<PktSendEvent>) -> (AudioPlaybackType, JoinHandle<()>) {
    let ch = ainfo.channels.max(2);
    let sample_rate = if !sbr_hack { ainfo.sample_rate } else { ainfo.sample_rate * 2 };
    let desired_spec = AudioSpecDesired {
        freq:       Some(sample_rate as i32),
        channels:   Some(ch),
        samples:    None
    };
    let dst_info = NAAudioInfo {
            sample_rate:    sample_rate,
            channels:       ch,
            format:         SND_S16_FORMAT,
            block_len:      0,
        };
    let queue = Arc::new(Mutex::new(AudioQueue::new(sample_rate as usize, ch as usize)));
    let qclone = queue.clone();
    let ret = asystem.open_playback(None, &desired_spec, |_spec| {
            AudioOutput {
                queue:      qclone,
            }
        });
    if ret.is_err() {
        return (None, dummy_audio_thread(aprecv))
    }
    let adevice = ret.unwrap();
    (Some(adevice), std::thread::Builder::new().name("acontrol".to_string()).spawn(move ||{
            let adec = if let DecoderType::Audio(ref mut dec) = audio_dec.dec { dec } else { panic!("not an audio decoder!"); };
            let mut samplepos = 0usize;
            let dst_chmap = if dst_info.channels == 2 {
                    NAChannelMap::from_str("L,R").expect("should be able to create stereo channel map")
                } else {
                    NAChannelMap::from_str("C").expect("should be able to create single-channel map")
                };
            ADEC_STATE.set_state(DecodingState::Normal);
            loop {
                match aprecv.recv() {
                    Ok(PktSendEvent::Packet(pkt)) => {
                        loop {
                            if CUR_QUEUE_FILL.load(Ordering::Relaxed)
 < QUEUE_REFILL_LIMIT || ADEC_STATE.is_flushing() {
                                break;
                            }
                            std::thread::sleep(Duration::from_millis(100));
                        }
                        if !ADEC_STATE.is_flushing() {
                            if let Ok(frm) = adec.decode(&mut audio_dec.dsupp, &pkt) {
                                let buf = frm.get_buffer();
                                if let Some(pts) = frm.get_pts() {
                                    samplepos = NATimeInfo::ts_to_time(pts, u64::from(dst_info.sample_rate), frm.ts.tb_num, frm.ts.tb_den) as usize;
                                    if sbr_hack {
                                        samplepos >>= 2;
                                    }
                                }
                                samplepos += buf.get_audio_length();
                                if let Ok(out_buf) = convert_audio_frame(&buf, &dst_info, &dst_chmap) {
                                    match out_buf {
                                        NABufferType::AudioI16(abuf) => {
                                            let mut qdata = queue.lock().expect("audio queue should be accessible");
                                            qdata.add(abuf.get_data(), samplepos);
                                            drop(qdata);
                                        },
                                        NABufferType::AudioPacked(abuf) => {
                                            let mut qdata = queue.lock().expect("audio queue should be accessible");
                                            qdata.add_bytes(abuf.get_data(), samplepos);
                                            drop(qdata);
                                        },
                                        _ => {},
                                    };
                                }
                            }
                        }
                    },
                    Ok(PktSendEvent::GetFrames) => {},
                    Ok(PktSendEvent::Flush) => {
                        adec.flush();
                        let mut qdata = queue.lock().expect("audio queue should be accessible");
                        qdata.flush();
                        ADEC_STATE.set_state(DecodingState::Waiting);
                    },
                    Ok(PktSendEvent::End) => break,
                    Ok(PktSendEvent::ImmediateEnd) => {
                        let mut qdata = queue.lock().expect("audio queue should be accessible");
                        qdata.flush();
                        break;
                    },
                    Ok(PktSendEvent::HurryUp) => {},
                    Err(_) => {
                        break;
                    },
                };
            }
            loop {
                let qdata = queue.lock().expect("audio queue should be accessible");
                if qdata.fill() == 0 || ADEC_STATE.is_flushing() {
                    break;
                }
            }
            ADEC_STATE.set_state(DecodingState::End);
        }).unwrap())
}

pub struct AudioControl {
    aqueue:         Vec<PktSendEvent>,
    apsend:         SyncSender<PktSendEvent>,
    adevice:        AudioPlaybackType,
    athread:        JoinHandle<()>,
}

impl AudioControl {
    pub fn new(audio_dec: Option<DecoderStuff>, ainfo: Option<NAAudioInfo>, sbr_hack: bool, asystem: &AudioSubsystem) -> Self {
        let (apsend, aprecv) = std::sync::mpsc::sync_channel::<PktSendEvent>(20);
        let (adevice, athread) = if let Some(audio_dec) = audio_dec {
                start_audio_decoding(asystem, ainfo.expect("audio info should be present"), sbr_hack, audio_dec, aprecv)
            } else {
                (None, dummy_audio_thread(aprecv))
            };
        ADEC_STATE.set_state(DecodingState::Normal);

        Self {
            aqueue:     Vec::new(),
            apsend,
            adevice,
            athread,
        }
    }
    pub fn has_audio(&self) -> bool { self.adevice.is_some() }
    pub fn pause(&mut self) {
        if let Some(ref device) = self.adevice {
            device.pause();
        }
    }
    pub fn resume(&mut self) {
        if let Some(ref device) = self.adevice {
            device.resume();
        }
    }
    pub fn set_volume(&mut self, volume: usize) {
        AUDIO_VOLUME.store(volume, Ordering::Relaxed);
    }
    pub fn get_volume(&self) -> usize {
        AUDIO_VOLUME.load(Ordering::Relaxed)
    }
    pub fn is_audio_end(&self) -> bool {
        matches!(ADEC_STATE.get_state(), DecodingState::End | DecodingState::Error)
    }
    pub fn get_fill(&self) -> usize { CUR_QUEUE_FILL.load(Ordering::Relaxed) }
    pub fn get_time(&self) -> Option<u64> {
        if CURRENT_TIME_SET.load(Ordering::Relaxed) {
            Some(CURRENT_TIME.load(Ordering::Relaxed) as u64)
        } else {
            None
        }
    }
    pub fn get_time_left(&self) -> u64 {
        let srate = SAMPLE_RATE.load(Ordering::Relaxed);
        let chans = CHANNELS.load(Ordering::Relaxed);
        if srate != 0 && chans != 0{
            let fill = self.get_fill();
            (fill * 1000 / srate / chans) as u64
        } else {
            0
        }
    }

    pub fn get_queue_size(&self) -> usize { self.aqueue.len() }
    pub fn try_send_audio(&mut self, evt: PktSendEvent) -> bool {
        if self.aqueue.len() > 0 {
            self.aqueue.push(evt);
            false
        } else {
            self.try_send_event(evt)
        }
    }
    fn try_send_event(&mut self, evt: PktSendEvent) -> bool {
        if let Err(TrySendError::Full(evt)) = self.apsend.try_send(evt) {
            self.aqueue.insert(0, evt);
            false
        } else {
            true
        }
    }
    pub fn try_send_queued(&mut self) -> bool {
        while !self.aqueue.is_empty() {
            let pkt = self.aqueue.remove(0);
            if !self.try_send_event(pkt) {
                 return false;
            }
        }
        true
    }

    pub fn flush(&mut self) {
        self.pause();
        self.aqueue.clear();
        ADEC_STATE.set_state(DecodingState::Flush);
        CURRENT_TIME_SET.store(false, Ordering::Release);
        let _ = self.apsend.send(PktSendEvent::Flush);
    }
    pub fn finish(self) {
        ADEC_STATE.set_state(DecodingState::Flush);
        let _ = self.apsend.send(PktSendEvent::ImmediateEnd);
        self.athread.join().unwrap();
    }
}