Mixer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // Copyright 2008 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "AudioCommon/Mixer.h"
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstring>
  7. #include "AudioCommon/Enums.h"
  8. #include "Common/ChunkFile.h"
  9. #include "Common/CommonTypes.h"
  10. #include "Common/Logging/Log.h"
  11. #include "Common/Swap.h"
  12. #include "Core/Config/MainSettings.h"
  13. #include "Core/ConfigManager.h"
  14. #include "VideoCommon/PerformanceMetrics.h"
  15. static u32 DPL2QualityToFrameBlockSize(AudioCommon::DPL2Quality quality)
  16. {
  17. switch (quality)
  18. {
  19. case AudioCommon::DPL2Quality::Lowest:
  20. return 512;
  21. case AudioCommon::DPL2Quality::Low:
  22. return 1024;
  23. case AudioCommon::DPL2Quality::Highest:
  24. return 4096;
  25. default:
  26. return 2048;
  27. }
  28. }
  29. Mixer::Mixer(unsigned int BackendSampleRate)
  30. : m_sampleRate(BackendSampleRate), m_stretcher(BackendSampleRate),
  31. m_surround_decoder(BackendSampleRate,
  32. DPL2QualityToFrameBlockSize(Config::Get(Config::MAIN_DPL2_QUALITY)))
  33. {
  34. m_config_changed_callback_id = Config::AddConfigChangedCallback([this] { RefreshConfig(); });
  35. RefreshConfig();
  36. INFO_LOG_FMT(AUDIO_INTERFACE, "Mixer is initialized");
  37. }
  38. Mixer::~Mixer()
  39. {
  40. Config::RemoveConfigChangedCallback(m_config_changed_callback_id);
  41. }
  42. void Mixer::DoState(PointerWrap& p)
  43. {
  44. m_dma_mixer.DoState(p);
  45. m_streaming_mixer.DoState(p);
  46. m_wiimote_speaker_mixer.DoState(p);
  47. m_skylander_portal_mixer.DoState(p);
  48. for (auto& mixer : m_gba_mixers)
  49. mixer.DoState(p);
  50. }
  51. // Executed from sound stream thread
  52. unsigned int Mixer::MixerFifo::Mix(short* samples, unsigned int numSamples,
  53. bool consider_framelimit, float emulationspeed,
  54. int timing_variance)
  55. {
  56. unsigned int currentSample = 0;
  57. // Cache access in non-volatile variable
  58. // This is the only function changing the read value, so it's safe to
  59. // cache it locally although it's written here.
  60. // The writing pointer will be modified outside, but it will only increase,
  61. // so we will just ignore new written data while interpolating.
  62. // Without this cache, the compiler wouldn't be allowed to optimize the
  63. // interpolation loop.
  64. u32 indexR = m_indexR.load();
  65. u32 indexW = m_indexW.load();
  66. // render numleft sample pairs to samples[]
  67. // advance indexR with sample position
  68. // remember fractional offset
  69. float aid_sample_rate =
  70. FIXED_SAMPLE_RATE_DIVIDEND / static_cast<float>(m_input_sample_rate_divisor);
  71. if (consider_framelimit && emulationspeed > 0.0f)
  72. {
  73. float numLeft = static_cast<float>(((indexW - indexR) & INDEX_MASK) / 2);
  74. u32 low_watermark = (FIXED_SAMPLE_RATE_DIVIDEND * timing_variance) /
  75. (static_cast<u64>(m_input_sample_rate_divisor) * 1000);
  76. low_watermark = std::min(low_watermark, MAX_SAMPLES / 2);
  77. m_numLeftI = (numLeft + m_numLeftI * (CONTROL_AVG - 1)) / CONTROL_AVG;
  78. float offset = (m_numLeftI - low_watermark) * CONTROL_FACTOR;
  79. if (offset > MAX_FREQ_SHIFT)
  80. offset = MAX_FREQ_SHIFT;
  81. if (offset < -MAX_FREQ_SHIFT)
  82. offset = -MAX_FREQ_SHIFT;
  83. aid_sample_rate = (aid_sample_rate + offset) * emulationspeed;
  84. }
  85. const u32 ratio = (u32)(65536.0f * aid_sample_rate / (float)m_mixer->m_sampleRate);
  86. s32 lvolume = m_LVolume.load();
  87. s32 rvolume = m_RVolume.load();
  88. const auto read_buffer = [this](auto index) {
  89. return m_little_endian ? m_buffer[index] : Common::swap16(m_buffer[index]);
  90. };
  91. // TODO: consider a higher-quality resampling algorithm.
  92. for (; currentSample < numSamples * 2 && ((indexW - indexR) & INDEX_MASK) > 2; currentSample += 2)
  93. {
  94. u32 indexR2 = indexR + 2; // next sample
  95. s16 l1 = read_buffer(indexR & INDEX_MASK); // current
  96. s16 l2 = read_buffer(indexR2 & INDEX_MASK); // next
  97. int sampleL = ((l1 << 16) + (l2 - l1) * (u16)m_frac) >> 16;
  98. sampleL = (sampleL * lvolume) >> 8;
  99. sampleL += samples[currentSample + 1];
  100. samples[currentSample + 1] = std::clamp(sampleL, -32767, 32767);
  101. s16 r1 = read_buffer((indexR + 1) & INDEX_MASK); // current
  102. s16 r2 = read_buffer((indexR2 + 1) & INDEX_MASK); // next
  103. int sampleR = ((r1 << 16) + (r2 - r1) * (u16)m_frac) >> 16;
  104. sampleR = (sampleR * rvolume) >> 8;
  105. sampleR += samples[currentSample];
  106. samples[currentSample] = std::clamp(sampleR, -32767, 32767);
  107. m_frac += ratio;
  108. indexR += 2 * (u16)(m_frac >> 16);
  109. m_frac &= 0xffff;
  110. }
  111. // Actual number of samples written to the buffer without padding.
  112. unsigned int actual_sample_count = currentSample / 2;
  113. // Padding
  114. short s[2];
  115. s[0] = read_buffer((indexR - 1) & INDEX_MASK);
  116. s[1] = read_buffer((indexR - 2) & INDEX_MASK);
  117. s[0] = (s[0] * rvolume) >> 8;
  118. s[1] = (s[1] * lvolume) >> 8;
  119. for (; currentSample < numSamples * 2; currentSample += 2)
  120. {
  121. int sampleR = std::clamp(s[0] + samples[currentSample + 0], -32767, 32767);
  122. int sampleL = std::clamp(s[1] + samples[currentSample + 1], -32767, 32767);
  123. samples[currentSample + 0] = sampleR;
  124. samples[currentSample + 1] = sampleL;
  125. }
  126. // Flush cached variable
  127. m_indexR.store(indexR);
  128. return actual_sample_count;
  129. }
  130. unsigned int Mixer::Mix(short* samples, unsigned int num_samples)
  131. {
  132. if (!samples)
  133. return 0;
  134. memset(samples, 0, num_samples * 2 * sizeof(short));
  135. // TODO: Determine how emulation speed will be used in audio
  136. // const float emulation_speed = g_perf_metrics.GetSpeed();
  137. const float emulation_speed = m_config_emulation_speed;
  138. const int timing_variance = m_config_timing_variance;
  139. if (m_config_audio_stretch)
  140. {
  141. unsigned int available_samples =
  142. std::min(m_dma_mixer.AvailableSamples(), m_streaming_mixer.AvailableSamples());
  143. ASSERT_MSG(AUDIO, available_samples <= MAX_SAMPLES,
  144. "Audio stretching would overflow m_scratch_buffer: min({}, {}) -> {} > {} ({})",
  145. m_dma_mixer.AvailableSamples(), m_streaming_mixer.AvailableSamples(),
  146. available_samples, MAX_SAMPLES, num_samples);
  147. m_scratch_buffer.fill(0);
  148. m_dma_mixer.Mix(m_scratch_buffer.data(), available_samples, false, emulation_speed,
  149. timing_variance);
  150. m_streaming_mixer.Mix(m_scratch_buffer.data(), available_samples, false, emulation_speed,
  151. timing_variance);
  152. m_wiimote_speaker_mixer.Mix(m_scratch_buffer.data(), available_samples, false, emulation_speed,
  153. timing_variance);
  154. m_skylander_portal_mixer.Mix(m_scratch_buffer.data(), available_samples, false, emulation_speed,
  155. timing_variance);
  156. for (auto& mixer : m_gba_mixers)
  157. {
  158. mixer.Mix(m_scratch_buffer.data(), available_samples, false, emulation_speed,
  159. timing_variance);
  160. }
  161. if (!m_is_stretching)
  162. {
  163. m_stretcher.Clear();
  164. m_is_stretching = true;
  165. }
  166. m_stretcher.ProcessSamples(m_scratch_buffer.data(), available_samples, num_samples);
  167. m_stretcher.GetStretchedSamples(samples, num_samples);
  168. }
  169. else
  170. {
  171. m_dma_mixer.Mix(samples, num_samples, true, emulation_speed, timing_variance);
  172. m_streaming_mixer.Mix(samples, num_samples, true, emulation_speed, timing_variance);
  173. m_wiimote_speaker_mixer.Mix(samples, num_samples, true, emulation_speed, timing_variance);
  174. m_skylander_portal_mixer.Mix(samples, num_samples, true, emulation_speed, timing_variance);
  175. for (auto& mixer : m_gba_mixers)
  176. mixer.Mix(samples, num_samples, true, emulation_speed, timing_variance);
  177. m_is_stretching = false;
  178. }
  179. return num_samples;
  180. }
  181. unsigned int Mixer::MixSurround(float* samples, unsigned int num_samples)
  182. {
  183. if (!num_samples)
  184. return 0;
  185. memset(samples, 0, num_samples * SURROUND_CHANNELS * sizeof(float));
  186. size_t needed_frames = m_surround_decoder.QueryFramesNeededForSurroundOutput(num_samples);
  187. // Mix() may also use m_scratch_buffer internally, but is safe because it alternates reads
  188. // and writes.
  189. ASSERT_MSG(AUDIO, needed_frames <= MAX_SAMPLES,
  190. "needed_frames would overflow m_scratch_buffer: {} -> {} > {}", num_samples,
  191. needed_frames, MAX_SAMPLES);
  192. size_t available_frames = Mix(m_scratch_buffer.data(), static_cast<u32>(needed_frames));
  193. if (available_frames != needed_frames)
  194. {
  195. ERROR_LOG_FMT(AUDIO,
  196. "Error decoding surround frames: needed {} frames for {} samples but got {}",
  197. needed_frames, num_samples, available_frames);
  198. return 0;
  199. }
  200. m_surround_decoder.PutFrames(m_scratch_buffer.data(), needed_frames);
  201. m_surround_decoder.ReceiveFrames(samples, num_samples);
  202. return num_samples;
  203. }
  204. void Mixer::MixerFifo::PushSamples(const short* samples, unsigned int num_samples)
  205. {
  206. // Cache access in non-volatile variable
  207. // indexR isn't allowed to cache in the audio throttling loop as it
  208. // needs to get updates to not deadlock.
  209. u32 indexW = m_indexW.load();
  210. // Check if we have enough free space
  211. // indexW == m_indexR results in empty buffer, so indexR must always be smaller than indexW
  212. if (num_samples * 2 + ((indexW - m_indexR.load()) & INDEX_MASK) >= MAX_SAMPLES * 2)
  213. return;
  214. // AyuanX: Actual re-sampling work has been moved to sound thread
  215. // to alleviate the workload on main thread
  216. // and we simply store raw data here to make fast mem copy
  217. int over_bytes = num_samples * 4 - (MAX_SAMPLES * 2 - (indexW & INDEX_MASK)) * sizeof(short);
  218. if (over_bytes > 0)
  219. {
  220. memcpy(&m_buffer[indexW & INDEX_MASK], samples, num_samples * 4 - over_bytes);
  221. memcpy(&m_buffer[0], samples + (num_samples * 4 - over_bytes) / sizeof(short), over_bytes);
  222. }
  223. else
  224. {
  225. memcpy(&m_buffer[indexW & INDEX_MASK], samples, num_samples * 4);
  226. }
  227. m_indexW.fetch_add(num_samples * 2);
  228. }
  229. void Mixer::PushSamples(const short* samples, unsigned int num_samples)
  230. {
  231. m_dma_mixer.PushSamples(samples, num_samples);
  232. if (m_log_dsp_audio)
  233. {
  234. int sample_rate_divisor = m_dma_mixer.GetInputSampleRateDivisor();
  235. auto volume = m_dma_mixer.GetVolume();
  236. m_wave_writer_dsp.AddStereoSamplesBE(samples, num_samples, sample_rate_divisor, volume.first,
  237. volume.second);
  238. }
  239. }
  240. void Mixer::PushStreamingSamples(const short* samples, unsigned int num_samples)
  241. {
  242. m_streaming_mixer.PushSamples(samples, num_samples);
  243. if (m_log_dtk_audio)
  244. {
  245. int sample_rate_divisor = m_streaming_mixer.GetInputSampleRateDivisor();
  246. auto volume = m_streaming_mixer.GetVolume();
  247. m_wave_writer_dtk.AddStereoSamplesBE(samples, num_samples, sample_rate_divisor, volume.first,
  248. volume.second);
  249. }
  250. }
  251. void Mixer::PushWiimoteSpeakerSamples(const short* samples, unsigned int num_samples,
  252. unsigned int sample_rate_divisor)
  253. {
  254. // Max 20 bytes/speaker report, may be 4-bit ADPCM so multiply by 2
  255. static constexpr u32 MAX_SPEAKER_SAMPLES = 20 * 2;
  256. std::array<short, MAX_SPEAKER_SAMPLES * 2> samples_stereo;
  257. ASSERT_MSG(AUDIO, num_samples <= MAX_SPEAKER_SAMPLES,
  258. "num_samples would overflow samples_stereo: {} > {}", num_samples,
  259. MAX_SPEAKER_SAMPLES);
  260. if (num_samples <= MAX_SPEAKER_SAMPLES)
  261. {
  262. m_wiimote_speaker_mixer.SetInputSampleRateDivisor(sample_rate_divisor);
  263. for (unsigned int i = 0; i < num_samples; ++i)
  264. {
  265. samples_stereo[i * 2] = samples[i];
  266. samples_stereo[i * 2 + 1] = samples[i];
  267. }
  268. m_wiimote_speaker_mixer.PushSamples(samples_stereo.data(), num_samples);
  269. }
  270. }
  271. void Mixer::PushSkylanderPortalSamples(const u8* samples, unsigned int num_samples)
  272. {
  273. // Skylander samples are always supplied as 64 bytes, 32 x 16 bit samples
  274. // The portal speaker is 1 channel, so duplicate and play as stereo audio
  275. static constexpr u32 MAX_PORTAL_SPEAKER_SAMPLES = 32;
  276. std::array<short, MAX_PORTAL_SPEAKER_SAMPLES * 2> samples_stereo;
  277. ASSERT_MSG(AUDIO, num_samples <= MAX_PORTAL_SPEAKER_SAMPLES,
  278. "num_samples is not less or equal to 32: {} > {}", num_samples,
  279. MAX_PORTAL_SPEAKER_SAMPLES);
  280. if (num_samples <= MAX_PORTAL_SPEAKER_SAMPLES)
  281. {
  282. for (unsigned int i = 0; i < num_samples; ++i)
  283. {
  284. s16 sample = static_cast<u16>(samples[i * 2 + 1]) << 8 | static_cast<u16>(samples[i * 2]);
  285. samples_stereo[i * 2] = sample;
  286. samples_stereo[i * 2 + 1] = sample;
  287. }
  288. m_skylander_portal_mixer.PushSamples(samples_stereo.data(), num_samples);
  289. }
  290. }
  291. void Mixer::PushGBASamples(int device_number, const short* samples, unsigned int num_samples)
  292. {
  293. m_gba_mixers[device_number].PushSamples(samples, num_samples);
  294. }
  295. void Mixer::SetDMAInputSampleRateDivisor(unsigned int rate_divisor)
  296. {
  297. m_dma_mixer.SetInputSampleRateDivisor(rate_divisor);
  298. }
  299. void Mixer::SetStreamInputSampleRateDivisor(unsigned int rate_divisor)
  300. {
  301. m_streaming_mixer.SetInputSampleRateDivisor(rate_divisor);
  302. }
  303. void Mixer::SetGBAInputSampleRateDivisors(int device_number, unsigned int rate_divisor)
  304. {
  305. m_gba_mixers[device_number].SetInputSampleRateDivisor(rate_divisor);
  306. }
  307. void Mixer::SetStreamingVolume(unsigned int lvolume, unsigned int rvolume)
  308. {
  309. m_streaming_mixer.SetVolume(lvolume, rvolume);
  310. }
  311. void Mixer::SetWiimoteSpeakerVolume(unsigned int lvolume, unsigned int rvolume)
  312. {
  313. m_wiimote_speaker_mixer.SetVolume(lvolume, rvolume);
  314. }
  315. void Mixer::SetGBAVolume(int device_number, unsigned int lvolume, unsigned int rvolume)
  316. {
  317. m_gba_mixers[device_number].SetVolume(lvolume, rvolume);
  318. }
  319. void Mixer::StartLogDTKAudio(const std::string& filename)
  320. {
  321. if (!m_log_dtk_audio)
  322. {
  323. bool success = m_wave_writer_dtk.Start(filename, m_streaming_mixer.GetInputSampleRateDivisor());
  324. if (success)
  325. {
  326. m_log_dtk_audio = true;
  327. m_wave_writer_dtk.SetSkipSilence(false);
  328. NOTICE_LOG_FMT(AUDIO, "Starting DTK Audio logging");
  329. }
  330. else
  331. {
  332. m_wave_writer_dtk.Stop();
  333. NOTICE_LOG_FMT(AUDIO, "Unable to start DTK Audio logging");
  334. }
  335. }
  336. else
  337. {
  338. WARN_LOG_FMT(AUDIO, "DTK Audio logging has already been started");
  339. }
  340. }
  341. void Mixer::StopLogDTKAudio()
  342. {
  343. if (m_log_dtk_audio)
  344. {
  345. m_log_dtk_audio = false;
  346. m_wave_writer_dtk.Stop();
  347. NOTICE_LOG_FMT(AUDIO, "Stopping DTK Audio logging");
  348. }
  349. else
  350. {
  351. WARN_LOG_FMT(AUDIO, "DTK Audio logging has already been stopped");
  352. }
  353. }
  354. void Mixer::StartLogDSPAudio(const std::string& filename)
  355. {
  356. if (!m_log_dsp_audio)
  357. {
  358. bool success = m_wave_writer_dsp.Start(filename, m_dma_mixer.GetInputSampleRateDivisor());
  359. if (success)
  360. {
  361. m_log_dsp_audio = true;
  362. m_wave_writer_dsp.SetSkipSilence(false);
  363. NOTICE_LOG_FMT(AUDIO, "Starting DSP Audio logging");
  364. }
  365. else
  366. {
  367. m_wave_writer_dsp.Stop();
  368. NOTICE_LOG_FMT(AUDIO, "Unable to start DSP Audio logging");
  369. }
  370. }
  371. else
  372. {
  373. WARN_LOG_FMT(AUDIO, "DSP Audio logging has already been started");
  374. }
  375. }
  376. void Mixer::StopLogDSPAudio()
  377. {
  378. if (m_log_dsp_audio)
  379. {
  380. m_log_dsp_audio = false;
  381. m_wave_writer_dsp.Stop();
  382. NOTICE_LOG_FMT(AUDIO, "Stopping DSP Audio logging");
  383. }
  384. else
  385. {
  386. WARN_LOG_FMT(AUDIO, "DSP Audio logging has already been stopped");
  387. }
  388. }
  389. void Mixer::RefreshConfig()
  390. {
  391. m_config_emulation_speed = Config::Get(Config::MAIN_EMULATION_SPEED);
  392. m_config_timing_variance = Config::Get(Config::MAIN_TIMING_VARIANCE);
  393. m_config_audio_stretch = Config::Get(Config::MAIN_AUDIO_STRETCH);
  394. }
  395. void Mixer::MixerFifo::DoState(PointerWrap& p)
  396. {
  397. p.Do(m_input_sample_rate_divisor);
  398. p.Do(m_LVolume);
  399. p.Do(m_RVolume);
  400. }
  401. void Mixer::MixerFifo::SetInputSampleRateDivisor(unsigned int rate_divisor)
  402. {
  403. m_input_sample_rate_divisor = rate_divisor;
  404. }
  405. unsigned int Mixer::MixerFifo::GetInputSampleRateDivisor() const
  406. {
  407. return m_input_sample_rate_divisor;
  408. }
  409. void Mixer::MixerFifo::SetVolume(unsigned int lvolume, unsigned int rvolume)
  410. {
  411. m_LVolume.store(lvolume + (lvolume >> 7));
  412. m_RVolume.store(rvolume + (rvolume >> 7));
  413. }
  414. std::pair<s32, s32> Mixer::MixerFifo::GetVolume() const
  415. {
  416. return std::make_pair(m_LVolume.load(), m_RVolume.load());
  417. }
  418. unsigned int Mixer::MixerFifo::AvailableSamples() const
  419. {
  420. unsigned int samples_in_fifo = ((m_indexW.load() - m_indexR.load()) & INDEX_MASK) / 2;
  421. if (samples_in_fifo <= 1)
  422. return 0; // Mixer::MixerFifo::Mix always keeps one sample in the buffer.
  423. return (samples_in_fifo - 1) * static_cast<u64>(m_mixer->m_sampleRate) *
  424. m_input_sample_rate_divisor / FIXED_SAMPLE_RATE_DIVIDEND;
  425. }