miniaudio_backend.cpp 12 KB

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