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