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
|
#pragma once
#include "StarJson.hpp"
#include "StarBiMap.hpp"
#include "StarException.hpp"
#include "StarGameTypes.hpp"
#include "StarMaybe.hpp"
#include "StarThread.hpp"
#include "StarDataStreamDevices.hpp"
#include "StarApplicationController.hpp"
#include <queue>
struct OpusDecoder;
typedef std::unique_ptr<OpusDecoder, void(*)(OpusDecoder*)> OpusDecoderPtr;
struct OpusEncoder;
typedef std::unique_ptr<OpusEncoder, void(*)(OpusEncoder*)> OpusEncoderPtr;
namespace Star {
String const VoiceBroadcastPrefix = "Voice\0"s;
STAR_EXCEPTION(VoiceException, StarException);
enum class VoiceInputMode : uint8_t { VoiceActivity, PushToTalk };
extern EnumMap<VoiceInputMode> const VoiceInputModeNames;
enum class VoiceChannelMode: uint8_t { Mono = 1, Stereo = 2 };
extern EnumMap<VoiceChannelMode> const VoiceChannelModeNames;
STAR_CLASS(Voice);
STAR_CLASS(VoiceAudioStream);
STAR_CLASS(ApplicationController);
struct VoiceAudioChunk {
std::unique_ptr<int16_t[]> data;
size_t remaining;
size_t offset = 0;
VoiceAudioChunk(int16_t* ptr, size_t size) {
data.reset(ptr);
remaining = size;
offset = 0;
}
inline size_t takeSamples(std::vector<int16_t>& out, size_t count) {
size_t toRead = min<size_t>(count, remaining);
int16_t* start = data.get() + offset;
out.insert(out.end(), start, start + toRead);
offset += toRead;
remaining -= toRead;
return toRead;
}
//this one's unsafe
inline int16_t takeSample() {
--remaining;
return *(data.get() + offset++);
}
inline bool exhausted() { return remaining == 0; }
};
class Voice {
public:
// Individual speakers are represented by their connection ID.
typedef ConnectionId SpeakerId;
class Speaker {
public:
SpeakerId speakerId = 0;
EntityId entityId = 0;
Vec2F position = Vec2F();
String name = "Unnamed";
OpusDecoderPtr decoderMono;
OpusDecoderPtr decoderStereo;
VoiceAudioStreamPtr audioStream;
Mutex mutex;
int64_t lastReceiveTime = 0;
int64_t lastPlayTime = 0;
float smoothDb = -96.0f;
Array<float, 10> dbHistory = Array<float, 10>::filled(0);
atomic<bool> muted = false;
atomic<bool> playing = 0;
atomic<float> decibelLevel = -96.0f;
atomic<float> volume = 1.0f;
Vec2F channelVolumes = Vec2F::filled(1.f);
unsigned int minimumPlaySamples = 4096;
Speaker(SpeakerId speakerId);
Json toJson() const;
};
typedef std::shared_ptr<Speaker> SpeakerPtr;
// Get pointer to the singleton Voice instance, if it exists. Otherwise,
// returns nullptr.
static Voice* singletonPtr();
// Gets reference to Voice singleton, throws VoiceException if root
// is not initialized.
static Voice& singleton();
Voice(ApplicationControllerPtr appController);
~Voice();
Voice(Voice const&) = delete;
Voice& operator=(Voice const&) = delete;
void init();
void loadJson(Json const& config, bool skipSave = false);
Json saveJson() const;
void save() const;
void scheduleSave();
// Sets the local speaker ID and returns the local speaker. Must be called upon loading into a world.
SpeakerPtr setLocalSpeaker(SpeakerId speakerId);
SpeakerPtr localSpeaker();
SpeakerPtr speaker(SpeakerId speakerId);
HashMap<SpeakerId, SpeakerPtr>& speakers();
List<Voice::SpeakerPtr> sortedSpeakers(bool onlyPlaying);
void clearSpeakers();
// Called when receiving input audio data from SDL, on its own thread.
void readAudioData(uint8_t* stream, int len);
// Called to mix voice audio with the game.
void mix(int16_t* buffer, size_t frames, unsigned channels);
typedef function<float(unsigned, Vec2F, float)> PositionalAttenuationFunction;
void update(float dt, PositionalAttenuationFunction positionalAttenuationFunction = {});
void setDeviceName(Maybe<String> device);
StringList availableDevices();
int send(DataStreamBuffer& out, size_t budget = 0);
bool receive(SpeakerPtr speaker, std::string_view view);
// Must be called every frame with input state, expires after 1s.
void setInput(bool input = true);
inline int encoderChannels() const { return (int)m_channelMode; }
static OpusDecoder* createDecoder(int channels);
static OpusEncoder* createEncoder(int channels);
private:
static Voice* s_singleton;
void resetEncoder();
void resetDevice();
void openDevice();
void closeDevice();
inline bool shouldEnableInput() const { return m_enabled && m_inputEnabled; }
bool playSpeaker(SpeakerPtr const& speaker, int channels);
void thread();
SpeakerId m_speakerId = 0;
SpeakerPtr m_clientSpeaker;
HashMap<SpeakerId, SpeakerPtr> m_speakers;
Mutex m_activeSpeakersMutex;
HashSet<SpeakerPtr> m_activeSpeakers;
OpusEncoderPtr m_encoder;
float m_outputVolume = 1.0f;
float m_inputVolume = 1.0f;
float m_outputAmplitude = 1.0f;
float m_inputAmplitude = 1.0f;
float m_threshold = -50.0f;
int64_t m_lastSentTime = 0;
int64_t m_lastInputTime = 0;
int64_t m_lastThresholdTime = 0;
int64_t m_nextSaveTime = 0;
bool m_enabled = true;
bool m_inputEnabled = false;
bool m_loopback = false;
int m_deviceChannels = 1;
bool m_deviceOpen = false;
Maybe<String> m_deviceName;
VoiceInputMode m_inputMode;
VoiceChannelMode m_channelMode;
unsigned m_bitrate = 0;
ThreadFunction<void> m_thread;
Mutex m_threadMutex;
ConditionVariable m_threadCond;
atomic<bool> m_stopThread;
std::vector<int16_t> m_decodeBuffer;
std::vector<int16_t> m_resampleBuffer;
ApplicationControllerPtr m_applicationController;
struct EncodedChunk {
std::unique_ptr<unsigned char[]> data;
size_t size;
EncodedChunk(unsigned char* _data, size_t len) {
data.reset(_data);
size = len;
}
};
Mutex m_encodeMutex;
std::vector<ByteArray> m_encodedChunks;
size_t m_encodedChunksLength = 0;
Mutex m_captureMutex;
std::queue<VoiceAudioChunk> m_capturedChunks;
size_t m_capturedChunksFrames = 0;
};
}
|