MiniaudioBackend.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #include "MiniaudioBackend.h"
  2. #include <QDebug>
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstddef>
  6. #include <cstring>
  7. #include <qglobal.h>
  8. #include <qhashfunctions.h>
  9. #include <qmutex.h>
  10. #include <qobject.h>
  11. #include <utility>
  12. #define MINIAUDIO_IMPLEMENTATION
  13. #define MA_NO_ENCODING
  14. #define MA_ENABLE_ONLY_SPECIFIC_BACKENDS
  15. #define MA_ENABLE_PULSEAUDIO
  16. #define MA_ENABLE_ALSA
  17. #define MA_ENABLE_WASAPI
  18. #define MA_ENABLE_COREAUDIO
  19. #define MA_ENABLE_MP3
  20. #define MA_ENABLE_FLAC
  21. #define MA_ENABLE_VORBIS
  22. #include <miniaudio.h>
  23. struct DeviceWrapper {
  24. MiniaudioBackend *self;
  25. };
  26. static void audioCallback(ma_device *device, void *output_buffer, const void *,
  27. ma_uint32 frame_count) {
  28. auto *wrapper = reinterpret_cast<DeviceWrapper *>(device->pUserData);
  29. if ((wrapper == nullptr) || (wrapper->self == nullptr)) {
  30. std::memset(output_buffer, 0,
  31. static_cast<unsigned long>(
  32. frame_count * MiniaudioBackend::DEFAULT_OUTPUT_CHANNELS) *
  33. sizeof(float));
  34. return;
  35. }
  36. wrapper->self->on_audio(reinterpret_cast<float *>(output_buffer),
  37. frame_count);
  38. }
  39. MiniaudioBackend::MiniaudioBackend(QObject *parent) : QObject(parent) {}
  40. MiniaudioBackend::~MiniaudioBackend() { shutdown(); }
  41. auto MiniaudioBackend::initialize(int device_rate, int,
  42. int music_channels) -> bool {
  43. m_sample_rate = std::max(MIN_SAMPLE_RATE, device_rate);
  44. m_output_channels = DEFAULT_OUTPUT_CHANNELS;
  45. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  46. config.playback.format = ma_format_f32;
  47. config.playback.channels = m_output_channels;
  48. config.sampleRate = m_sample_rate;
  49. config.dataCallback = audioCallback;
  50. auto *wrapper = new DeviceWrapper{this};
  51. config.pUserData = wrapper;
  52. m_device = new ma_device();
  53. if (ma_device_init(nullptr, &config, m_device) != MA_SUCCESS) {
  54. qWarning() << "MiniaudioBackend: Failed to initialize audio device";
  55. qWarning() << " Requested sample rate:" << m_sample_rate;
  56. qWarning() << " Requested channels:" << m_output_channels;
  57. qWarning() << " This may indicate no audio device is available";
  58. delete m_device;
  59. m_device = nullptr;
  60. delete wrapper;
  61. return false;
  62. }
  63. m_channels.resize(std::max(1, music_channels));
  64. for (auto &channel : m_channels) {
  65. channel = Channel{};
  66. }
  67. m_sound_effects.resize(DEFAULT_SOUND_EFFECT_SLOTS);
  68. for (auto &sfx : m_sound_effects) {
  69. sfx = SoundEffect{};
  70. }
  71. if (ma_device_start(m_device) != MA_SUCCESS) {
  72. qWarning() << "MiniaudioBackend: Failed to start audio device";
  73. ma_device_uninit(m_device);
  74. delete m_device;
  75. m_device = nullptr;
  76. delete wrapper;
  77. return false;
  78. }
  79. qInfo() << "MiniaudioBackend: Initialized successfully";
  80. qInfo() << " Sample rate:" << m_sample_rate;
  81. qInfo() << " Channels:" << m_output_channels;
  82. qInfo() << " Music channels:" << music_channels;
  83. return true;
  84. }
  85. void MiniaudioBackend::shutdown() {
  86. QMutexLocker const locker(&m_mutex);
  87. stop_device();
  88. m_tracks.clear();
  89. m_channels.clear();
  90. }
  91. void MiniaudioBackend::stop_device() {
  92. if (m_device == nullptr) {
  93. return;
  94. }
  95. auto *wrapper = reinterpret_cast<DeviceWrapper *>(m_device->pUserData);
  96. ma_device_stop(m_device);
  97. ma_device_uninit(m_device);
  98. delete m_device;
  99. m_device = nullptr;
  100. delete wrapper;
  101. }
  102. auto MiniaudioBackend::predecode(const QString &id,
  103. const QString &path) -> bool {
  104. ma_decoder_config const decoder_config =
  105. ma_decoder_config_init(ma_format_f32, m_output_channels, m_sample_rate);
  106. ma_decoder decoder;
  107. if (ma_decoder_init_file(path.toUtf8().constData(), &decoder_config,
  108. &decoder) != MA_SUCCESS) {
  109. qWarning() << "miniaudio: cannot open" << path;
  110. return false;
  111. }
  112. QVector<float> pcm;
  113. float buffer[DECODE_BUFFER_FRAMES * DEFAULT_OUTPUT_CHANNELS];
  114. for (;;) {
  115. ma_uint64 frames_read = 0;
  116. ma_result const result = ma_decoder_read_pcm_frames(
  117. &decoder, buffer, DECODE_BUFFER_FRAMES, &frames_read);
  118. if (frames_read > 0) {
  119. const size_t samples = size_t(frames_read) * DEFAULT_OUTPUT_CHANNELS;
  120. const size_t old_size = pcm.size();
  121. pcm.resize(old_size + samples);
  122. std::memcpy(pcm.data() + old_size, buffer, samples * sizeof(float));
  123. }
  124. if (result == MA_AT_END) {
  125. break;
  126. }
  127. if (result != MA_SUCCESS) {
  128. ma_decoder_uninit(&decoder);
  129. return false;
  130. }
  131. }
  132. ma_decoder_uninit(&decoder);
  133. QMutexLocker const locker(&m_mutex);
  134. DecodedTrack track;
  135. track.frames = pcm.size() / DEFAULT_OUTPUT_CHANNELS;
  136. track.pcm = std::move(pcm);
  137. m_tracks[id] = std::move(track);
  138. return true;
  139. }
  140. void MiniaudioBackend::play(int channel, const QString &id, float volume,
  141. bool loop, int fade_ms) {
  142. static constexpr int MIN_FADE_MS = 1;
  143. static constexpr int MS_PER_SECOND = 1000;
  144. QMutexLocker locker(&m_mutex);
  145. if (channel < 0 || channel >= m_channels.size()) {
  146. return;
  147. }
  148. auto it = m_tracks.find(id);
  149. if (it == m_tracks.end()) {
  150. locker.unlock();
  151. predecode(id, id);
  152. locker.relock();
  153. it = m_tracks.find(id);
  154. if (it == m_tracks.end()) {
  155. qWarning() << "MiniaudioBackend: unknown track" << id;
  156. return;
  157. }
  158. }
  159. auto &ch = m_channels[channel];
  160. ch.track = &it.value();
  161. ch.frame_pos = 0;
  162. ch.looping = loop;
  163. ch.paused = false;
  164. ch.active = true;
  165. ch.target_volume = std::clamp(volume, MIN_VOLUME, MAX_VOLUME);
  166. ch.current_volume = MIN_VOLUME;
  167. const unsigned fade_samples =
  168. std::max(unsigned(MIN_FADE_MS),
  169. unsigned((fade_ms * m_sample_rate) / MS_PER_SECOND));
  170. ch.fade_samples = fade_samples;
  171. ch.volume_step = (ch.target_volume - ch.current_volume) / float(fade_samples);
  172. }
  173. void MiniaudioBackend::stop(int channel, int fade_ms) {
  174. static constexpr int MIN_FADE_MS = 1;
  175. static constexpr int MS_PER_SECOND = 1000;
  176. QMutexLocker const locker(&m_mutex);
  177. if (channel < 0 || channel >= m_channels.size()) {
  178. return;
  179. }
  180. auto &ch = m_channels[channel];
  181. if (!ch.active) {
  182. return;
  183. }
  184. const unsigned fade_samples =
  185. std::max(unsigned(MIN_FADE_MS),
  186. unsigned((fade_ms * m_sample_rate) / MS_PER_SECOND));
  187. ch.target_volume = MIN_VOLUME;
  188. ch.fade_samples = fade_samples;
  189. ch.volume_step = (ch.target_volume - ch.current_volume) / float(fade_samples);
  190. ch.looping = false;
  191. }
  192. void MiniaudioBackend::pause(int channel) {
  193. QMutexLocker const locker(&m_mutex);
  194. if (channel >= 0 && channel < m_channels.size()) {
  195. m_channels[channel].paused = true;
  196. }
  197. }
  198. void MiniaudioBackend::resume(int channel) {
  199. QMutexLocker const locker(&m_mutex);
  200. if (channel >= 0 && channel < m_channels.size()) {
  201. m_channels[channel].paused = false;
  202. }
  203. }
  204. void MiniaudioBackend::set_volume(int channel, float volume, int fade_ms) {
  205. static constexpr int MIN_FADE_MS = 1;
  206. static constexpr int MS_PER_SECOND = 1000;
  207. QMutexLocker const locker(&m_mutex);
  208. if (channel < 0 || channel >= m_channels.size()) {
  209. return;
  210. }
  211. auto &ch = m_channels[channel];
  212. if (!ch.active) {
  213. return;
  214. }
  215. ch.target_volume = std::clamp(volume, MIN_VOLUME, MAX_VOLUME);
  216. const unsigned fade_samples =
  217. std::max(unsigned(MIN_FADE_MS),
  218. unsigned((fade_ms * m_sample_rate) / MS_PER_SECOND));
  219. ch.fade_samples = fade_samples;
  220. ch.volume_step = (ch.target_volume - ch.current_volume) / float(fade_samples);
  221. }
  222. void MiniaudioBackend::stop_all(int fade_ms) {
  223. static constexpr int MIN_FADE_MS = 1;
  224. static constexpr int MS_PER_SECOND = 1000;
  225. QMutexLocker const locker(&m_mutex);
  226. const unsigned fade_samples =
  227. std::max(unsigned(MIN_FADE_MS),
  228. unsigned((fade_ms * m_sample_rate) / MS_PER_SECOND));
  229. for (auto &ch : m_channels) {
  230. if (!ch.active) {
  231. continue;
  232. }
  233. ch.target_volume = MIN_VOLUME;
  234. ch.fade_samples = fade_samples;
  235. ch.volume_step =
  236. (ch.target_volume - ch.current_volume) / float(fade_samples);
  237. ch.looping = false;
  238. }
  239. }
  240. void MiniaudioBackend::set_master_volume(float volume, int) {
  241. QMutexLocker const locker(&m_mutex);
  242. m_master_volume = std::clamp(volume, MIN_VOLUME, MAX_VOLUME);
  243. }
  244. auto MiniaudioBackend::any_channel_playing() const -> bool {
  245. QMutexLocker const locker(&m_mutex);
  246. for (const auto &ch : m_channels) {
  247. if (ch.active && !ch.paused) {
  248. return true;
  249. }
  250. }
  251. return false;
  252. }
  253. auto MiniaudioBackend::channel_playing(int channel) const -> bool {
  254. QMutexLocker const locker(&m_mutex);
  255. if (channel < 0 || channel >= m_channels.size()) {
  256. return false;
  257. }
  258. const auto &ch = m_channels[channel];
  259. return ch.active && !ch.paused;
  260. }
  261. void MiniaudioBackend::play_sound(const QString &id, float volume, bool loop) {
  262. QMutexLocker const locker(&m_mutex);
  263. auto it = m_tracks.find(id);
  264. if (it == m_tracks.end()) {
  265. qWarning() << "MiniaudioBackend: Sound not preloaded:" << id;
  266. return;
  267. }
  268. int const slot = find_free_sound_slot();
  269. if (slot < 0) {
  270. qWarning() << "MiniaudioBackend: No free sound slots available";
  271. return;
  272. }
  273. auto &sfx = m_sound_effects[slot];
  274. sfx.track = &it.value();
  275. sfx.frame_pos = 0;
  276. sfx.volume = std::clamp(volume, MIN_VOLUME, MAX_VOLUME);
  277. sfx.looping = loop;
  278. sfx.active = true;
  279. }
  280. auto MiniaudioBackend::find_free_sound_slot() const -> int {
  281. for (int i = 0; i < m_sound_effects.size(); ++i) {
  282. if (!m_sound_effects[i].active) {
  283. return i;
  284. }
  285. }
  286. return -1;
  287. }
  288. void MiniaudioBackend::on_audio(float *output, unsigned frames) {
  289. static constexpr int STEREO_CHANNELS = 2;
  290. const unsigned samples = frames * STEREO_CHANNELS;
  291. std::memset(output, 0, samples * sizeof(float));
  292. QMutexLocker const locker(&m_mutex);
  293. for (auto &ch : m_channels) {
  294. if (!ch.active || ch.paused || ch.track == nullptr) {
  295. continue;
  296. }
  297. const auto *pcm = ch.track->pcm.constData();
  298. unsigned frames_left = frames;
  299. unsigned pos = ch.frame_pos;
  300. float *dst = output;
  301. while (frames_left > 0) {
  302. if (pos >= ch.track->frames) {
  303. if (ch.looping) {
  304. pos = 0;
  305. } else {
  306. break;
  307. }
  308. }
  309. const unsigned can_copy = std::min(frames_left, ch.track->frames - pos);
  310. const float *src = pcm + static_cast<size_t>(pos * STEREO_CHANNELS);
  311. for (unsigned i = 0; i < can_copy; ++i) {
  312. const float vol = ch.current_volume * m_master_volume;
  313. dst[0] += src[0] * vol;
  314. dst[1] += src[1] * vol;
  315. dst += STEREO_CHANNELS;
  316. src += STEREO_CHANNELS;
  317. if (ch.fade_samples > 0) {
  318. ch.current_volume += ch.volume_step;
  319. --ch.fade_samples;
  320. if (ch.fade_samples == 0) {
  321. ch.current_volume = ch.target_volume;
  322. }
  323. }
  324. }
  325. pos += can_copy;
  326. frames_left -= can_copy;
  327. }
  328. ch.frame_pos = pos;
  329. if (!ch.looping && ch.frame_pos >= ch.track->frames) {
  330. ch.active = false;
  331. ch.current_volume = ch.target_volume = MIN_VOLUME;
  332. ch.fade_samples = 0;
  333. }
  334. if (ch.fade_samples == 0 && ch.current_volume == MIN_VOLUME &&
  335. ch.target_volume == MIN_VOLUME && !ch.looping) {
  336. ch.active = false;
  337. }
  338. }
  339. for (auto &sfx : m_sound_effects) {
  340. if (!sfx.active || sfx.track == nullptr) {
  341. continue;
  342. }
  343. const auto *pcm = sfx.track->pcm.constData();
  344. unsigned frames_left = frames;
  345. unsigned pos = sfx.frame_pos;
  346. float *dst = output;
  347. while (frames_left > 0) {
  348. if (pos >= sfx.track->frames) {
  349. if (sfx.looping) {
  350. pos = 0;
  351. } else {
  352. sfx.active = false;
  353. break;
  354. }
  355. }
  356. const unsigned can_copy = std::min(frames_left, sfx.track->frames - pos);
  357. const float *src = pcm + static_cast<size_t>(pos * STEREO_CHANNELS);
  358. for (unsigned i = 0; i < can_copy; ++i) {
  359. const float vol = sfx.volume * m_master_volume;
  360. dst[0] += src[0] * vol;
  361. dst[1] += src[1] * vol;
  362. dst += STEREO_CHANNELS;
  363. src += STEREO_CHANNELS;
  364. }
  365. pos += can_copy;
  366. frames_left -= can_copy;
  367. }
  368. sfx.frame_pos = pos;
  369. }
  370. for (unsigned i = 0; i < samples; ++i) {
  371. if (output[i] > MAX_VOLUME) {
  372. output[i] = MAX_VOLUME;
  373. } else if (output[i] < -MAX_VOLUME) {
  374. output[i] = -MAX_VOLUME;
  375. }
  376. }
  377. }