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