OpenTTD Source 20261112-master-gbcbec5e63f
mixer.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include <mutex>
12#include <atomic>
13#include "core/math_func.hpp"
14#include "framerate_type.h"
15#include "mixer.h"
16
17#include "safeguards.h"
18
21 std::shared_ptr<std::vector<std::byte>> memory;
22
24 uint32_t pos;
25 uint32_t frac_pos;
26 uint32_t frac_speed;
27 uint32_t samples_left;
28
34
35 bool is16bit;
36};
37
38using MixerChannelMask = uint8_t;
39
40static std::atomic<MixerChannelMask> _active_channels;
41static std::atomic<MixerChannelMask> _stop_channels;
42static MixerChannel _channels[8];
43static uint32_t _play_rate = 11025;
44static uint32_t _max_size = UINT_MAX;
45static MxStreamCallback _music_stream = nullptr;
46static std::mutex _music_stream_mutex;
47static std::atomic<uint8_t> _effect_vol;
48
55static const int MAX_VOLUME = 32767;
56
64template <typename T>
65static int RateConversion(T *b, int frac_pos)
66{
67 return ((b[0] * ((1 << 16) - frac_pos)) + (b[1] * frac_pos)) >> 16;
68}
69
70template <typename T>
71static void mix_int16(MixerChannel *sc, int16_t *buffer, uint samples, uint8_t effect_vol)
72{
73 /* Shift required to get sample value into range for the data type. */
74 const uint SHIFT = sizeof(T) * CHAR_BIT;
75
76 if (samples > sc->samples_left) samples = sc->samples_left;
77 sc->samples_left -= samples;
78 assert(samples > 0);
79
80 const T *b = reinterpret_cast<const T *>(sc->memory->data()) + sc->pos;
81 uint32_t frac_pos = sc->frac_pos;
82 uint32_t frac_speed = sc->frac_speed;
83 int volume_left = sc->volume_left * effect_vol / 255;
84 int volume_right = sc->volume_right * effect_vol / 255;
85
86 if (frac_speed == 0x10000) {
87 /* Special case when frac_speed is 0x10000 */
88 do {
89 buffer[0] = Clamp(buffer[0] + (*b * volume_left >> SHIFT), -MAX_VOLUME, MAX_VOLUME);
90 buffer[1] = Clamp(buffer[1] + (*b * volume_right >> SHIFT), -MAX_VOLUME, MAX_VOLUME);
91 b++;
92 buffer += 2;
93 } while (--samples > 0);
94 } else {
95 do {
96 int data = RateConversion(b, frac_pos);
97 buffer[0] = Clamp(buffer[0] + (data * volume_left >> SHIFT), -MAX_VOLUME, MAX_VOLUME);
98 buffer[1] = Clamp(buffer[1] + (data * volume_right >> SHIFT), -MAX_VOLUME, MAX_VOLUME);
99 buffer += 2;
100 frac_pos += frac_speed;
101 b += frac_pos >> 16;
102 frac_pos &= 0xffff;
103 } while (--samples > 0);
104 }
105
106 sc->frac_pos = frac_pos;
107 sc->pos = b - reinterpret_cast<const T *>(sc->memory->data());
108}
109
110static void MxCloseChannel(uint8_t channel_index)
111{
112 _active_channels.fetch_and(~(1U << channel_index), std::memory_order_release);
113}
114
121{
122 _stop_channels.fetch_or(~0, std::memory_order_release);
123}
124
125void MxMixSamples(void *buffer, uint samples)
126{
128 static uint last_samples = 0;
129 if (samples != last_samples) {
130 framerate.SetExpectedRate((double)_play_rate / samples);
131 last_samples = samples;
132 }
133
134 /* Clear the buffer */
135 std::fill_n(static_cast<int16_t *>(buffer), 2 * samples, 0);
136
137 {
138 std::lock_guard<std::mutex> lock{ _music_stream_mutex };
139 /* Fetch music if a sampled stream is available */
140 if (_music_stream) _music_stream((int16_t*)buffer, samples);
141 }
142
143 /* Check if any channels should be stopped. */
144 MixerChannelMask stop = _stop_channels.load(std::memory_order_acquire);
145 for (uint8_t idx : SetBitIterator(stop)) {
146 MxCloseChannel(idx);
147 }
148
149 /* Apply simple x^3 scaling to master effect volume. This increases the
150 * perceived difference in loudness to better match expectations. effect_vol
151 * is expected to be in the range 0-127 hence the division by 127 * 127 to
152 * get back into range. */
153 uint8_t effect_vol_setting = _effect_vol.load(std::memory_order_relaxed);
154 uint8_t effect_vol = (effect_vol_setting *
155 effect_vol_setting *
156 effect_vol_setting) / (127 * 127);
157
158 /* Mix each channel */
159 MixerChannelMask active = _active_channels.load(std::memory_order_acquire);
160 for (uint8_t idx : SetBitIterator(active)) {
161 MixerChannel *mc = &_channels[idx];
162 if (mc->is16bit) {
163 mix_int16<int16_t>(mc, (int16_t*)buffer, samples, effect_vol);
164 } else {
165 mix_int16<int8_t>(mc, (int16_t*)buffer, samples, effect_vol);
166 }
167 if (mc->samples_left == 0) MxCloseChannel(idx);
168 }
169}
170
171MixerChannel *MxAllocateChannel()
172{
173 MixerChannelMask currently_active = _active_channels.load(std::memory_order_acquire);
174 MixerChannelMask available = ~currently_active;
175 if (available == 0) return nullptr;
176
177 uint8_t channel_index = FindFirstBit(available);
178
179 MixerChannel *mc = &_channels[channel_index];
180 mc->memory = nullptr;
181 return mc;
182}
183
184void MxSetChannelRawSrc(MixerChannel *mc, const std::shared_ptr<std::vector<std::byte>> &mem, uint rate, bool is16bit)
185{
186 mc->memory = mem;
187 mc->frac_pos = 0;
188 mc->pos = 0;
189
190 mc->frac_speed = (rate << 16U) / _play_rate;
191
192 size_t size = mc->memory->size();
193 if (is16bit) size /= 2;
194 /* Less 1 to allow for padding sample for the resampler. */
195 size -= 1;
196
197 /* adjust the magnitude to prevent overflow */
198 while (size >= _max_size) {
199 size >>= 1;
200 rate = (rate >> 1) + 1;
201 }
202
203 /* Scale number of samples by play rate. */
204 mc->samples_left = (uint)size * _play_rate / rate;
205 mc->is16bit = is16bit;
206}
207
214void MxSetChannelVolume(MixerChannel *mc, uint volume, float pan)
215{
216 /* Use sinusoidal pan to maintain overall sound power level regardless
217 * of position. */
218 mc->volume_left = (uint)(sin((1.0 - pan) * M_PI / 2.0) * volume);
219 mc->volume_right = (uint)(sin(pan * M_PI / 2.0) * volume);
220}
221
222
223void MxActivateChannel(MixerChannel *mc)
224{
225 uint8_t channel_index = mc - _channels;
226 _stop_channels.fetch_and(~(1U << channel_index), std::memory_order_release);
227 _active_channels.fetch_or((1U << channel_index), std::memory_order_release);
228}
229
235uint32_t MxSetMusicSource(MxStreamCallback music_callback)
236{
237 std::lock_guard<std::mutex> lock{ _music_stream_mutex };
238 _music_stream = music_callback;
239 return _play_rate;
240}
241
242
243bool MxInitialize(uint rate)
244{
245 std::lock_guard<std::mutex> lock{ _music_stream_mutex };
246 _play_rate = rate;
247 _max_size = UINT_MAX / _play_rate;
248 _music_stream = nullptr; /* rate may have changed, any music source is now invalid */
249 return true;
250}
251
256uint32_t MxGetRate()
257{
258 return _play_rate;
259}
260
261void SetEffectVolume(uint8_t volume)
262{
263 _effect_vol.store(volume, std::memory_order_relaxed);
264}
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
RAII class for measuring simple elements of performance.
#define T
Climate temperate.
Definition engines.h:91
Types for recording game performance data.
@ Sound
Speed of mixing audio samples.
Integer math functions.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
void MxCloseAllChannels()
Close all mixer channels.
Definition mixer.cpp:120
static int RateConversion(T *b, int frac_pos)
Perform the rate conversion between the input and output.
Definition mixer.cpp:65
uint32_t MxGetRate()
Get the current mixer sampling rate.
Definition mixer.cpp:256
uint8_t MixerChannelMask
Type representing a bitmask of mixer channels.
Definition mixer.cpp:38
uint32_t MxSetMusicSource(MxStreamCallback music_callback)
Set source of PCM music.
Definition mixer.cpp:235
void MxSetChannelVolume(MixerChannel *mc, uint volume, float pan)
Set volume and pan parameters for a sound.
Definition mixer.cpp:214
static const int MAX_VOLUME
The theoretical maximum volume for a single sound sample.
Definition mixer.cpp:55
Functions to mix sound samples.
void(* MxStreamCallback)(int16_t *buffer, size_t samples)
Type of callback functions for supplying PCM music.
Definition mixer.h:21
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
int volume_left
Definition mixer.cpp:31
int volume_right
Definition mixer.cpp:32
uint32_t pos
Current position in memory.
Definition mixer.cpp:24
std::shared_ptr< std::vector< std::byte > > memory
Pointer to allocated buffer memory.
Definition mixer.cpp:21
Iterable ensemble of each set bit in a value.
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35