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
|
//! All things audio.
//!
//! Audio is handled mostly as signals from [dasp_signal]. Input/output is handled by [cpal].
pub mod input;
pub mod output;
pub mod sound_effects;
pub mod transformers;
use crate::error::AudioError;
use crate::network::VoiceStreamType;
use crate::state::StatePhase;
use futures_util::stream::Stream;
use futures_util::StreamExt;
use mumble_protocol::voice::{VoicePacket, VoicePacketPayload};
use mumble_protocol::Serverbound;
use mumlib::config::SoundEffect;
use std::collections::{hash_map::Entry, HashMap};
use std::fmt::Debug;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio::sync::watch;
use self::input::{AudioInputDevice, DefaultAudioInputDevice};
use self::output::{AudioOutputDevice, ClientStream, DefaultAudioOutputDevice};
use self::sound_effects::{NotificationEvent, SoundEffects, SoundEffectId};
/// The sample rate used internally.
const SAMPLE_RATE: u32 = 48000;
/// Input audio state. Input audio is picket up from an [AudioInputDevice] (e.g.
/// a microphone) and sent over the network.
pub struct AudioInput {
device: DefaultAudioInputDevice,
/// Outgoing voice packets that should be sent over the network.
channel_receiver:
Arc<tokio::sync::Mutex<Box<dyn Stream<Item = VoicePacket<Serverbound>> + Unpin>>>,
}
impl AudioInput {
pub fn new(
input_volume: f32,
phase_watcher: watch::Receiver<StatePhase>,
) -> Result<Self, AudioError> {
let mut default = DefaultAudioInputDevice::new(input_volume, phase_watcher, 4)?;
let opus_stream = default
.sample_receiver()
.unwrap()
.enumerate()
.map(|(i, e)| VoicePacket::Audio {
_dst: std::marker::PhantomData,
target: 0, // normal speech
session_id: (), // unused for server-bound packets
seq_num: i as u64,
payload: VoicePacketPayload::Opus(e.into(), false),
position_info: None,
});
default.play()?;
let res = Self {
device: default,
channel_receiver: Arc::new(tokio::sync::Mutex::new(Box::new(opus_stream))),
};
Ok(res)
}
pub fn receiver(
&self,
) -> Arc<tokio::sync::Mutex<Box<dyn Stream<Item = VoicePacket<Serverbound>> + Unpin>>> {
Arc::clone(&self.channel_receiver)
}
pub fn set_volume(&self, input_volume: f32) {
self.device.set_volume(input_volume);
}
}
impl Debug for AudioInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AudioInput")
.field("device", &self.device)
.field("channel_receiver", &"receiver")
.finish()
}
}
#[derive(Debug)]
/// Audio output state. The audio is received from each client over the network,
/// decoded, merged and finally played to an [AudioOutputDevice] (e.g. speaker,
/// headphones, ...).
pub struct AudioOutput {
device: DefaultAudioOutputDevice,
/// The volume and mute-status of a user ID.
user_volumes: Arc<Mutex<HashMap<u32, (f32, bool)>>>,
/// The client stream per user ID. A separate stream is kept for UDP and TCP.
///
/// Shared with [DefaultAudioOutputDevice].
client_streams: Arc<Mutex<ClientStream>>,
/// Opened sound effects.
sound_effects: SoundEffects,
/// Which file should be played on specific events.
sound_effect_events: HashMap<NotificationEvent, SoundEffectId>,
}
impl AudioOutput {
pub fn new(output_volume: f32) -> Result<Self, AudioError> {
let user_volumes = Arc::new(std::sync::Mutex::new(HashMap::new()));
let default = DefaultAudioOutputDevice::new(output_volume, Arc::clone(&user_volumes))?;
default.play()?;
let client_streams = default.client_streams();
let mut res = Self {
device: default,
user_volumes,
client_streams,
sound_effects: SoundEffects::new(2),
sound_effect_events: HashMap::new(),
};
res.load_sound_effects(&[]);
Ok(res)
}
pub fn load_sound_effects(&mut self, sound_effects: &[SoundEffect]) {
todo!()
}
/// Decodes a voice packet.
pub fn decode_packet_payload(
&self,
stream_type: VoiceStreamType,
session_id: u32,
payload: VoicePacketPayload,
) {
self.client_streams
.lock()
.unwrap()
.decode_packet((stream_type, session_id), payload);
}
/// Sets the volume of the output device.
pub fn set_volume(&self, output_volume: f32) {
self.device.set_volume(output_volume);
}
/// Sets the incoming volume of a user.
pub fn set_user_volume(&self, id: u32, volume: f32) {
match self.user_volumes.lock().unwrap().entry(id) {
Entry::Occupied(mut entry) => {
entry.get_mut().0 = volume;
}
Entry::Vacant(entry) => {
entry.insert((volume, false));
}
}
}
/// Mutes another user.
pub fn set_mute(&self, id: u32, mute: bool) {
match self.user_volumes.lock().unwrap().entry(id) {
Entry::Occupied(mut entry) => {
entry.get_mut().1 = mute;
}
Entry::Vacant(entry) => {
entry.insert((1.0, mute));
}
}
}
/// Queues a sound effect.
pub fn play_effect(&self, effect: NotificationEvent) {
let id = self
.sound_effect_events
.get(&effect)
.cloned()
.unwrap_or_else(SoundEffects::default_sound_effect);
let samples = &self.sound_effects[id];
self.client_streams.lock().unwrap().add_sound_effect(samples);
}
}
|