openMSX
SoundDevice.cc
Go to the documentation of this file.
1#include "SoundDevice.hh"
2#include "MSXMixer.hh"
3#include "DeviceConfig.hh"
4#include "Mixer.hh"
5#include "XMLElement.hh"
6#include "Filename.hh"
7#include "StringOp.hh"
8#include "MemBuffer.hh"
9#include "MSXException.hh"
10#include "aligned.hh"
11#include "narrow.hh"
12#include "ranges.hh"
13#include "one_of.hh"
14#include "vla.hh"
15#include "xrange.hh"
16#include <array>
17#include <cassert>
18#include <memory>
19
20namespace openmsx {
21
22static MemBuffer<float, SSE_ALIGNMENT> mixBuffer;
23static size_t mixBufferSize = 0;
24
25static void allocateMixBuffer(size_t size)
26{
27 if (mixBufferSize < size) [[unlikely]] {
28 mixBufferSize = size;
29 mixBuffer.resize(mixBufferSize);
30 }
31}
32
33[[nodiscard]] static std::string makeUnique(MSXMixer& mixer, std::string_view name)
34{
35 std::string result(name);
36 if (mixer.findDevice(result)) {
37 unsigned n = 0;
38 do {
39 result = strCat(name, " (", ++n, ')');
40 } while (mixer.findDevice(result));
41 }
42 return result;
43}
44
45void SoundDevice::addFill(float*& buf, float val, unsigned num)
46{
47 // Note: in the past we tried to optimize this by always producing
48 // a multiple of 4 output values. In the general case a SoundDevice is
49 // allowed to do this, but only at the end of the sound buffer. This
50 // method can also be called in the middle of a buffer (so multiple
51 // times per buffer), in such case it does go wrong.
52 assert(num > 0);
53 do {
54 *buf++ += val;
55 } while (--num);
56}
57
58SoundDevice::SoundDevice(MSXMixer& mixer_, std::string_view name_, static_string_view description_,
59 unsigned numChannels_, unsigned inputRate, bool stereo_)
60 : mixer(mixer_)
61 , name(makeUnique(mixer, name_))
62 , description(description_)
63 , numChannels(numChannels_)
64 , stereo(stereo_ ? 2 : 1)
65{
66 assert(numChannels <= MAX_CHANNELS);
67 assert(stereo == one_of(1u, 2u));
68
69 setInputRate(inputRate);
70
71 // initially no channels are muted
72 ranges::fill(channelMuted, false);
73 ranges::fill(channelBalance, 0);
74}
75
77
79{
80 return stereo == 2 || !balanceCenter;
81}
82
84{
85 return 1.0f / 32768.0f;
86}
87
89{
90 const auto& soundConfig = config.getChild("sound");
91 float volume = narrow<float>(soundConfig.getChildDataAsInt("volume", 0)) * (1.0f / 32767.0f);
92 int devBalance = 0;
93 std::string_view mode = soundConfig.getChildData("mode", "mono");
94 if (mode == "mono") {
95 devBalance = 0;
96 } else if (mode == "left") {
97 devBalance = -100;
98 } else if (mode == "right") {
99 devBalance = 100;
100 } else {
101 throw MSXException("balance \"", mode, "\" illegal");
102 }
103
104 for (const auto* b : soundConfig.getChildren("balance")) {
105 auto balance = StringOp::stringTo<int>(b->getData());
106 if (!balance) {
107 throw MSXException("balance ", b->getData(), " illegal");
108 }
109
110 const auto* channel = b->findAttribute("channel");
111 if (!channel) {
112 devBalance = *balance;
113 continue;
114 }
115
116 // TODO Support other balances
117 if (*balance != one_of(0, -100, 100)) {
118 throw MSXException("balance ", *balance, " illegal");
119 }
120 if (*balance != 0) {
121 balanceCenter = false;
122 }
123
124 auto channels = StringOp::parseRange(channel->getValue(), 1, numChannels);
125 channels.foreachSetBit([&](size_t c) {
126 channelBalance[c - 1] = *balance;
127 });
128 }
129
130 mixer.registerSound(*this, volume, devBalance, numChannels);
131}
132
134{
135 mixer.unregisterSound(*this);
136}
137
138void SoundDevice::updateStream(EmuTime::param time)
139{
140 mixer.updateStream(time);
141}
142
143void SoundDevice::setSoftwareVolume(float volume, EmuTime::param time)
144{
145 setSoftwareVolume(volume, volume, time);
146}
147
148void SoundDevice::setSoftwareVolume(float left, float right, EmuTime::param time)
149{
150 updateStream(time);
151 softwareVolumeLeft = left;
152 softwareVolumeRight = right;
153 mixer.updateSoftwareVolume(*this);
154}
155
156void SoundDevice::recordChannel(unsigned channel, const Filename& filename)
157{
158 assert(channel < numChannels);
159 bool wasRecording = writer[channel].has_value();
160 if (!filename.empty()) {
161 writer[channel].emplace(
162 filename, stereo, inputSampleRate);
163 } else {
164 writer[channel].reset();
165 }
166 bool recording = writer[channel].has_value();
167 if (recording != wasRecording) {
168 if (recording) {
169 if (numRecordChannels == 0) {
170 mixer.setSynchronousMode(true);
171 }
172 ++numRecordChannels;
173 assert(numRecordChannels <= numChannels);
174 } else {
175 assert(numRecordChannels > 0);
176 --numRecordChannels;
177 if (numRecordChannels == 0) {
178 mixer.setSynchronousMode(false);
179 }
180 }
181 }
182}
183
184void SoundDevice::muteChannel(unsigned channel, bool muted)
185{
186 assert(channel < numChannels);
187 channelMuted[channel] = muted;
188}
189
190bool SoundDevice::mixChannels(float* dataOut, size_t samples)
191{
192#ifdef __SSE2__
193 assert((uintptr_t(dataOut) & 15) == 0); // must be 16-byte aligned
194#endif
195 if (samples == 0) return true;
196 size_t outputStereo = isStereo() ? 2 : 1;
197
198 std::array<float*, MAX_CHANNELS> bufs_;
199 auto bufs = subspan(bufs_, 0, numChannels);
200
201 unsigned separateChannels = 0;
202 size_t pitch = (samples * stereo + 3) & ~3; // align for SSE access
203 // TODO optimization: All channels with the same balance (according to
204 // channelBalance[]) could use the same buffer when balanceCenter is
205 // false
206 for (auto i : xrange(numChannels)) {
207 if (!channelMuted[i] && !writer[i] && balanceCenter) {
208 // no need to keep this channel separate
209 bufs[i] = dataOut;
210 } else {
211 // muted or recorded channels must go separate
212 // cannot yet fill in bufs[i] here
213 ++separateChannels;
214 }
215 }
216
217 static_assert(sizeof(float) == sizeof(uint32_t));
218 if ((numChannels != 1) || separateChannels) {
219 // The generateChannels() method of SoundDevices with more than
220 // one channel will _add_ the generated channel data in the
221 // provided buffers. Those with only one channel will directly
222 // replace the content of the buffer. For the former we must
223 // start from a buffer containing all zeros.
224 ranges::fill(std::span{dataOut, outputStereo * samples}, 0.0f);
225 }
226
227 if (separateChannels) {
228 allocateMixBuffer(pitch * separateChannels);
229 ranges::fill(std::span{mixBuffer.data(), pitch * separateChannels}, 0.0f);
230 // still need to fill in (some) bufs[i] pointers
231 unsigned count = 0;
232 for (auto i : xrange(numChannels)) {
233 if (channelMuted[i] || writer[i] || !balanceCenter) {
234 bufs[i] = &mixBuffer[pitch * count++];
235 }
236 }
237 assert(count == separateChannels);
238 }
239
240 generateChannels(bufs, narrow<unsigned>(samples));
241
242 if (separateChannels == 0) {
243 return ranges::any_of(xrange(numChannels),
244 [&](auto i) { return bufs[i]; });
245 }
246
247 // record channels
248 for (auto i : xrange(numChannels)) {
249 if (writer[i]) {
250 assert(bufs[i] != dataOut);
251 if (bufs[i]) {
252 auto amp = getAmplificationFactor();
253 if (stereo == 1) {
254 writer[i]->write(
255 std::span{bufs[i], samples},
256 amp.left);
257 } else {
258 writer[i]->write(
259 std::span{reinterpret_cast<const StereoFloat*>(bufs[i]), samples},
260 amp.left, amp.right);
261 }
262 } else {
263 writer[i]->writeSilence(narrow<unsigned>(stereo * samples));
264 }
265 }
266 }
267
268 // remove muted channels (explicitly by user or by device itself)
269 bool anyUnmuted = false;
270 unsigned numMix = 0;
271 VLA(int, mixBalance, numChannels);
272 for (auto i : xrange(numChannels)) {
273 if (bufs[i] && !channelMuted[i]) {
274 anyUnmuted = true;
275 if (bufs[i] != dataOut) {
276 bufs[numMix] = bufs[i];
277 mixBalance[numMix] = channelBalance[i];
278 ++numMix;
279 }
280 }
281 }
282
283 if (numMix == 0) {
284 // all extra channels muted
285 return anyUnmuted;
286 }
287
288 // actually mix channels
289 if (!balanceCenter) {
290 size_t i = 0;
291 do {
292 float left0 = 0.0f;
293 float right0 = 0.0f;
294 float left1 = 0.0f;
295 float right1 = 0.0f;
296 unsigned j = 0;
297 do {
298 if (mixBalance[j] <= 0) {
299 left0 += bufs[j][i + 0];
300 left1 += bufs[j][i + 1];
301 }
302 if (mixBalance[j] >= 0) {
303 right0 += bufs[j][i + 0];
304 right1 += bufs[j][i + 1];
305 }
306 j++;
307 } while (j < numMix);
308 dataOut[i * 2 + 0] = left0;
309 dataOut[i * 2 + 1] = right0;
310 dataOut[i * 2 + 2] = left1;
311 dataOut[i * 2 + 3] = right1;
312 i += 2;
313 } while (i < samples);
314
315 return true;
316 }
317
318 // In the past we had ARM and x86-SSE2 optimized assembly routines for
319 // the stuff below. Currently this code is only rarely used anymore
320 // (only when recording or muting individual sound chip channels), so
321 // it's not worth the extra complexity anymore.
322 size_t num = samples * stereo;
323 size_t i = 0;
324 do {
325 auto out0 = dataOut[i + 0];
326 auto out1 = dataOut[i + 1];
327 auto out2 = dataOut[i + 2];
328 auto out3 = dataOut[i + 3];
329 unsigned j = 0;
330 do {
331 out0 += bufs[j][i + 0];
332 out1 += bufs[j][i + 1];
333 out2 += bufs[j][i + 2];
334 out3 += bufs[j][i + 3];
335 ++j;
336 } while (j < numMix);
337 dataOut[i + 0] = out0;
338 dataOut[i + 1] = out1;
339 dataOut[i + 2] = out2;
340 dataOut[i + 3] = out3;
341 i += 4;
342 } while (i < num);
343
344 return true;
345}
346
348{
349 return mixer.getHostSampleClock();
350}
352{
353 return mixer.getEffectiveSpeed();
354}
355
356} // namespace openmsx
const XMLElement & getChild(std::string_view name) const
Represents a clock with a variable frequency.
This class represents a filename.
Definition Filename.hh:18
bool empty() const
Convenience method to test for empty filename.
Definition Filename.cc:21
void resize(size_t size)
Grow or shrink the memory block.
Definition MemBuffer.hh:111
const T * data() const
Returns pointer to the start of the memory buffer.
Definition MemBuffer.hh:81
double getEffectiveSpeed() const
void recordChannel(unsigned channel, const Filename &filename)
void updateStream(EmuTime::param time)
AmplificationFactors getAmplificationFactor() const
static void addFill(float *&buffer, float value, unsigned num)
Adds a number of samples that all have the same value.
const DynamicClock & getHostSampleClock() const
See MSXMixer::getHostSampleClock().
void setInputRate(unsigned sampleRate)
void setSoftwareVolume(float volume, EmuTime::param time)
Change the 'software volume' of this sound device.
bool mixChannels(float *dataOut, size_t samples)
Calls generateChannels() and combines the output to a single channel.
static constexpr unsigned MAX_CHANNELS
void unregisterSound()
Unregisters this sound device with the Mixer.
SoundDevice(const SoundDevice &)=delete
bool isStereo() const
Is this a stereo device? This is set in the constructor and cannot be changed anymore.
virtual void generateChannels(std::span< float * > buffers, unsigned num)=0
Abstract method to generate the actual sound data.
void registerSound(const DeviceConfig &config)
Registers this sound device with the Mixer.
void muteChannel(unsigned channel, bool muted)
virtual float getAmplificationFactorImpl() const
Get amplification/attenuation factor for this device.
std::string_view getChildData(std::string_view childName) const
Definition XMLElement.cc:62
static_string_view
IterableBitSet< 64 > parseRange(string_view str, unsigned min, unsigned max)
Definition StringOp.cc:177
This file implemented 3 utility functions:
Definition Autofire.cc:9
bool any_of(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:198
constexpr void fill(ForwardRange &&range, const T &value)
Definition ranges.hh:305
size_t size(std::string_view utf8)
constexpr auto subspan(Range &&range, size_t offset, size_t count=std::dynamic_extent)
Definition ranges.hh:471
std::string strCat()
Definition strCat.hh:703
#define VLA(TYPE, NAME, LENGTH)
Definition vla.hh:12
constexpr auto xrange(T e)
Definition xrange.hh:132