dsp.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. // Copyright 2016 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <cstddef>
  6. #include <type_traits>
  7. #include "audio_core/audio_core.h"
  8. #include "common/bit_field.h"
  9. #include "common/common_funcs.h"
  10. #include "common/common_types.h"
  11. #include "common/swap.h"
  12. namespace DSP {
  13. namespace HLE {
  14. // The application-accessible region of DSP memory consists of two parts.
  15. // Both are marked as IO and have Read/Write permissions.
  16. //
  17. // First Region: 0x1FF50000 (Size: 0x8000)
  18. // Second Region: 0x1FF70000 (Size: 0x8000)
  19. //
  20. // The DSP reads from each region alternately based on the frame counter for each region much like a
  21. // double-buffer. The frame counter is located as the very last u16 of each region and is incremented
  22. // each audio tick.
  23. struct SharedMemory;
  24. constexpr VAddr region0_base = 0x1FF50000;
  25. extern SharedMemory g_region0;
  26. constexpr VAddr region1_base = 0x1FF70000;
  27. extern SharedMemory g_region1;
  28. /**
  29. * The DSP is native 16-bit. The DSP also appears to be big-endian. When reading 32-bit numbers from
  30. * its memory regions, the higher and lower 16-bit halves are swapped compared to the little-endian
  31. * layout of the ARM11. Hence from the ARM11's point of view the memory space appears to be
  32. * middle-endian.
  33. *
  34. * Unusually this does not appear to be an issue for floating point numbers. The DSP makes the more
  35. * sensible choice of keeping that little-endian. There are also some exceptions such as the
  36. * IntermediateMixSamples structure, which is little-endian.
  37. *
  38. * This struct implements the conversion to and from this middle-endianness.
  39. */
  40. struct u32_dsp {
  41. u32_dsp() = default;
  42. operator u32() const {
  43. return Convert(storage);
  44. }
  45. void operator=(u32 new_value) {
  46. storage = Convert(new_value);
  47. }
  48. private:
  49. static constexpr u32 Convert(u32 value) {
  50. return (value << 16) | (value >> 16);
  51. }
  52. u32_le storage;
  53. };
  54. #if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER)
  55. static_assert(std::is_trivially_copyable<u32_dsp>::value, "u32_dsp isn't trivially copyable");
  56. #endif
  57. // There are 15 structures in each memory region. A table of them in the order they appear in memory
  58. // is presented below:
  59. //
  60. // # First Region DSP Address Purpose Control
  61. // 5 0x8400 DSP Status DSP
  62. // 9 0x8410 DSP Debug Info DSP
  63. // 6 0x8540 Final Mix Samples DSP
  64. // 2 0x8680 Source Status [24] DSP
  65. // 8 0x8710 Compressor Table Application
  66. // 4 0x9430 DSP Configuration Application
  67. // 7 0x9492 Intermediate Mix Samples DSP + App
  68. // 1 0x9E92 Source Configuration [24] Application
  69. // 3 0xA792 Source ADPCM Coefficients [24] Application
  70. // 10 0xA912 Surround Sound Related
  71. // 11 0xAA12 Surround Sound Related
  72. // 12 0xAAD2 Surround Sound Related
  73. // 13 0xAC52 Surround Sound Related
  74. // 14 0xAC5C Surround Sound Related
  75. // 0 0xBFFF Frame Counter Application
  76. //
  77. // #: This refers to the order in which they appear in the DspPipe::Audio DSP pipe.
  78. // See also: DSP::HLE::PipeRead.
  79. //
  80. // Note that the above addresses do vary slightly between audio firmwares observed; the addresses are
  81. // not fixed in stone. The addresses above are only an examplar; they're what this implementation
  82. // does and provides to applications.
  83. //
  84. // Application requests the DSP service to convert DSP addresses into ARM11 virtual addresses using the
  85. // ConvertProcessAddressFromDspDram service call. Applications seem to derive the addresses for the
  86. // second region via:
  87. // second_region_dsp_addr = first_region_dsp_addr | 0x10000
  88. //
  89. // Applications maintain most of its own audio state, the memory region is used mainly for
  90. // communication and not storage of state.
  91. //
  92. // In the documentation below, filter and effect transfer functions are specified in the z domain.
  93. // (If you are more familiar with the Laplace transform, z = exp(sT). The z domain is the digital
  94. // frequency domain, just like how the s domain is the analog frequency domain.)
  95. #define INSERT_PADDING_DSPWORDS(num_words) INSERT_PADDING_BYTES(2 * (num_words))
  96. // GCC versions < 5.0 do not implement std::is_trivially_copyable.
  97. // Excluding MSVC because it has weird behaviour for std::is_trivially_copyable.
  98. #if (__GNUC__ >= 5) || defined(__clang__)
  99. #define ASSERT_DSP_STRUCT(name, size) \
  100. static_assert(std::is_standard_layout<name>::value, "DSP structure " #name " doesn't use standard layout"); \
  101. static_assert(std::is_trivially_copyable<name>::value, "DSP structure " #name " isn't trivially copyable"); \
  102. static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name)
  103. #else
  104. #define ASSERT_DSP_STRUCT(name, size) \
  105. static_assert(std::is_standard_layout<name>::value, "DSP structure " #name " doesn't use standard layout"); \
  106. static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name)
  107. #endif
  108. struct SourceConfiguration {
  109. struct Configuration {
  110. /// These dirty flags are set by the application when it updates the fields in this struct.
  111. /// The DSP clears these each audio frame.
  112. union {
  113. u32_le dirty_raw;
  114. BitField<0, 1, u32_le> format_dirty;
  115. BitField<1, 1, u32_le> mono_or_stereo_dirty;
  116. BitField<2, 1, u32_le> adpcm_coefficients_dirty;
  117. BitField<3, 1, u32_le> partial_embedded_buffer_dirty; ///< Tends to be set when a looped buffer is queued.
  118. BitField<4, 1, u32_le> partial_reset_flag;
  119. BitField<16, 1, u32_le> enable_dirty;
  120. BitField<17, 1, u32_le> interpolation_dirty;
  121. BitField<18, 1, u32_le> rate_multiplier_dirty;
  122. BitField<19, 1, u32_le> buffer_queue_dirty;
  123. BitField<20, 1, u32_le> loop_related_dirty;
  124. BitField<21, 1, u32_le> play_position_dirty; ///< Tends to also be set when embedded buffer is updated.
  125. BitField<22, 1, u32_le> filters_enabled_dirty;
  126. BitField<23, 1, u32_le> simple_filter_dirty;
  127. BitField<24, 1, u32_le> biquad_filter_dirty;
  128. BitField<25, 1, u32_le> gain_0_dirty;
  129. BitField<26, 1, u32_le> gain_1_dirty;
  130. BitField<27, 1, u32_le> gain_2_dirty;
  131. BitField<28, 1, u32_le> sync_dirty;
  132. BitField<29, 1, u32_le> reset_flag;
  133. BitField<30, 1, u32_le> embedded_buffer_dirty;
  134. };
  135. // Gain control
  136. /**
  137. * Gain is between 0.0-1.0. This determines how much will this source appear on
  138. * each of the 12 channels that feed into the intermediate mixers.
  139. * Each of the three intermediate mixers is fed two left and two right channels.
  140. */
  141. float_le gain[3][4];
  142. // Interpolation
  143. /// Multiplier for sample rate. Resampling occurs with the selected interpolation method.
  144. float_le rate_multiplier;
  145. enum class InterpolationMode : u8 {
  146. None = 0,
  147. Linear = 1,
  148. Polyphase = 2
  149. };
  150. InterpolationMode interpolation_mode;
  151. INSERT_PADDING_BYTES(1); ///< Interpolation related
  152. // Filters
  153. /**
  154. * This is the simplest normalized first-order digital recursive filter.
  155. * The transfer function of this filter is:
  156. * H(z) = b0 / (1 - a1 z^-1)
  157. * Note the feedbackward coefficient is negated.
  158. * Values are signed fixed point with 15 fractional bits.
  159. */
  160. struct SimpleFilter {
  161. s16_le b0;
  162. s16_le a1;
  163. };
  164. /**
  165. * This is a normalised biquad filter (second-order).
  166. * The transfer function of this filter is:
  167. * H(z) = (b0 + b1 z^-1 + b2 z^-2) / (1 - a1 z^-1 - a2 z^-2)
  168. * Nintendo chose to negate the feedbackward coefficients. This differs from standard notation
  169. * as in: https://ccrma.stanford.edu/~jos/filters/Direct_Form_I.html
  170. * Values are signed fixed point with 14 fractional bits.
  171. */
  172. struct BiquadFilter {
  173. s16_le a2;
  174. s16_le a1;
  175. s16_le b2;
  176. s16_le b1;
  177. s16_le b0;
  178. };
  179. union {
  180. u16_le filters_enabled;
  181. BitField<0, 1, u16_le> simple_filter_enabled;
  182. BitField<1, 1, u16_le> biquad_filter_enabled;
  183. };
  184. SimpleFilter simple_filter;
  185. BiquadFilter biquad_filter;
  186. // Buffer Queue
  187. /// A buffer of audio data from the application, along with metadata about it.
  188. struct Buffer {
  189. /// Physical memory address of the start of the buffer
  190. u32_dsp physical_address;
  191. /// This is length in terms of samples.
  192. /// Note that in different buffer formats a sample takes up different number of bytes.
  193. u32_dsp length;
  194. /// ADPCM Predictor (4 bits) and Scale (4 bits)
  195. union {
  196. u16_le adpcm_ps;
  197. BitField<0, 4, u16_le> adpcm_scale;
  198. BitField<4, 4, u16_le> adpcm_predictor;
  199. };
  200. /// ADPCM Historical Samples (y[n-1] and y[n-2])
  201. u16_le adpcm_yn[2];
  202. /// This is non-zero when the ADPCM values above are to be updated.
  203. u8 adpcm_dirty;
  204. /// Is a looping buffer.
  205. u8 is_looping;
  206. /// This value is shown in SourceStatus::previous_buffer_id when this buffer has finished.
  207. /// This allows the emulated application to tell what buffer is currently playing
  208. u16_le buffer_id;
  209. INSERT_PADDING_DSPWORDS(1);
  210. };
  211. u16_le buffers_dirty; ///< Bitmap indicating which buffers are dirty (bit i -> buffers[i])
  212. Buffer buffers[4]; ///< Queued Buffers
  213. // Playback controls
  214. u32_dsp loop_related;
  215. u8 enable;
  216. INSERT_PADDING_BYTES(1);
  217. u16_le sync; ///< Application-side sync (See also: SourceStatus::sync)
  218. u32_dsp play_position; ///< Position. (Units: number of samples)
  219. INSERT_PADDING_DSPWORDS(2);
  220. // Embedded Buffer
  221. // This buffer is often the first buffer to be used when initiating audio playback,
  222. // after which the buffer queue is used.
  223. u32_dsp physical_address;
  224. /// This is length in terms of samples.
  225. /// Note a sample takes up different number of bytes in different buffer formats.
  226. u32_dsp length;
  227. enum class MonoOrStereo : u16_le {
  228. Mono = 1,
  229. Stereo = 2
  230. };
  231. enum class Format : u16_le {
  232. PCM8 = 0,
  233. PCM16 = 1,
  234. ADPCM = 2
  235. };
  236. union {
  237. u16_le flags1_raw;
  238. BitField<0, 2, MonoOrStereo> mono_or_stereo;
  239. BitField<2, 2, Format> format;
  240. BitField<5, 1, u16_le> fade_in;
  241. };
  242. /// ADPCM Predictor (4 bit) and Scale (4 bit)
  243. union {
  244. u16_le adpcm_ps;
  245. BitField<0, 4, u16_le> adpcm_scale;
  246. BitField<4, 4, u16_le> adpcm_predictor;
  247. };
  248. /// ADPCM Historical Samples (y[n-1] and y[n-2])
  249. u16_le adpcm_yn[2];
  250. union {
  251. u16_le flags2_raw;
  252. BitField<0, 1, u16_le> adpcm_dirty; ///< Has the ADPCM info above been changed?
  253. BitField<1, 1, u16_le> is_looping; ///< Is this a looping buffer?
  254. };
  255. /// Buffer id of embedded buffer (used as a buffer id in SourceStatus to reference this buffer).
  256. u16_le buffer_id;
  257. };
  258. Configuration config[AudioCore::num_sources];
  259. };
  260. ASSERT_DSP_STRUCT(SourceConfiguration::Configuration, 192);
  261. ASSERT_DSP_STRUCT(SourceConfiguration::Configuration::Buffer, 20);
  262. struct SourceStatus {
  263. struct Status {
  264. u8 is_enabled; ///< Is this channel enabled? (Doesn't have to be playing anything.)
  265. u8 previous_buffer_id_dirty; ///< Non-zero when previous_buffer_id changes
  266. u16_le sync; ///< Is set by the DSP to the value of SourceConfiguration::sync
  267. u32_dsp buffer_position; ///< Number of samples into the current buffer
  268. u16_le previous_buffer_id; ///< Updated when a buffer finishes playing
  269. INSERT_PADDING_DSPWORDS(1);
  270. };
  271. Status status[AudioCore::num_sources];
  272. };
  273. ASSERT_DSP_STRUCT(SourceStatus::Status, 12);
  274. struct DspConfiguration {
  275. /// These dirty flags are set by the application when it updates the fields in this struct.
  276. /// The DSP clears these each audio frame.
  277. union {
  278. u32_le dirty_raw;
  279. BitField<8, 1, u32_le> mixer1_enabled_dirty;
  280. BitField<9, 1, u32_le> mixer2_enabled_dirty;
  281. BitField<10, 1, u32_le> delay_effect_0_dirty;
  282. BitField<11, 1, u32_le> delay_effect_1_dirty;
  283. BitField<12, 1, u32_le> reverb_effect_0_dirty;
  284. BitField<13, 1, u32_le> reverb_effect_1_dirty;
  285. BitField<16, 1, u32_le> volume_0_dirty;
  286. BitField<24, 1, u32_le> volume_1_dirty;
  287. BitField<25, 1, u32_le> volume_2_dirty;
  288. BitField<26, 1, u32_le> output_format_dirty;
  289. BitField<27, 1, u32_le> limiter_enabled_dirty;
  290. BitField<28, 1, u32_le> headphones_connected_dirty;
  291. };
  292. /// The DSP has three intermediate audio mixers. This controls the volume level (0.0-1.0) for each at the final mixer
  293. float_le volume[3];
  294. INSERT_PADDING_DSPWORDS(3);
  295. enum class OutputFormat : u16_le {
  296. Mono = 0,
  297. Stereo = 1,
  298. Surround = 2
  299. };
  300. OutputFormat output_format;
  301. u16_le limiter_enabled; ///< Not sure of the exact gain equation for the limiter.
  302. u16_le headphones_connected; ///< Application updates the DSP on headphone status.
  303. INSERT_PADDING_DSPWORDS(4); ///< TODO: Surround sound related
  304. INSERT_PADDING_DSPWORDS(2); ///< TODO: Intermediate mixer 1/2 related
  305. u16_le mixer1_enabled;
  306. u16_le mixer2_enabled;
  307. /**
  308. * This is delay with feedback.
  309. * Transfer function:
  310. * H(z) = a z^-N / (1 - b z^-1 + a g z^-N)
  311. * where
  312. * N = frame_count * samples_per_frame
  313. * g, a and b are fixed point with 7 fractional bits
  314. */
  315. struct DelayEffect {
  316. /// These dirty flags are set by the application when it updates the fields in this struct.
  317. /// The DSP clears these each audio frame.
  318. union {
  319. u16_le dirty_raw;
  320. BitField<0, 1, u16_le> enable_dirty;
  321. BitField<1, 1, u16_le> work_buffer_address_dirty;
  322. BitField<2, 1, u16_le> other_dirty; ///< Set when anything else has been changed
  323. };
  324. u16_le enable;
  325. INSERT_PADDING_DSPWORDS(1);
  326. u16_le outputs;
  327. u32_dsp work_buffer_address; ///< The application allocates a block of memory for the DSP to use as a work buffer.
  328. u16_le frame_count; ///< Frames to delay by
  329. // Coefficients
  330. s16_le g; ///< Fixed point with 7 fractional bits
  331. s16_le a; ///< Fixed point with 7 fractional bits
  332. s16_le b; ///< Fixed point with 7 fractional bits
  333. };
  334. DelayEffect delay_effect[2];
  335. struct ReverbEffect {
  336. INSERT_PADDING_DSPWORDS(26); ///< TODO
  337. };
  338. ReverbEffect reverb_effect[2];
  339. INSERT_PADDING_DSPWORDS(4);
  340. };
  341. ASSERT_DSP_STRUCT(DspConfiguration, 196);
  342. ASSERT_DSP_STRUCT(DspConfiguration::DelayEffect, 20);
  343. ASSERT_DSP_STRUCT(DspConfiguration::ReverbEffect, 52);
  344. struct AdpcmCoefficients {
  345. /// Coefficients are signed fixed point with 11 fractional bits.
  346. /// Each source has 16 coefficients associated with it.
  347. s16_le coeff[AudioCore::num_sources][16];
  348. };
  349. ASSERT_DSP_STRUCT(AdpcmCoefficients, 768);
  350. struct DspStatus {
  351. u16_le unknown;
  352. u16_le dropped_frames;
  353. INSERT_PADDING_DSPWORDS(0xE);
  354. };
  355. ASSERT_DSP_STRUCT(DspStatus, 32);
  356. /// Final mixed output in PCM16 stereo format, what you hear out of the speakers.
  357. /// When the application writes to this region it has no effect.
  358. struct FinalMixSamples {
  359. s16_le pcm16[2 * AudioCore::samples_per_frame];
  360. };
  361. ASSERT_DSP_STRUCT(FinalMixSamples, 640);
  362. /// DSP writes output of intermediate mixers 1 and 2 here.
  363. /// Writes to this region by the application edits the output of the intermediate mixers.
  364. /// This seems to be intended to allow the application to do custom effects on the ARM11.
  365. /// Values that exceed s16 range will be clipped by the DSP after further processing.
  366. struct IntermediateMixSamples {
  367. struct Samples {
  368. s32_le pcm32[4][AudioCore::samples_per_frame]; ///< Little-endian as opposed to DSP middle-endian.
  369. };
  370. Samples mix1;
  371. Samples mix2;
  372. };
  373. ASSERT_DSP_STRUCT(IntermediateMixSamples, 5120);
  374. /// Compressor table
  375. struct Compressor {
  376. INSERT_PADDING_DSPWORDS(0xD20); ///< TODO
  377. };
  378. /// There is no easy way to implement this in a HLE implementation.
  379. struct DspDebug {
  380. INSERT_PADDING_DSPWORDS(0x130);
  381. };
  382. ASSERT_DSP_STRUCT(DspDebug, 0x260);
  383. struct SharedMemory {
  384. /// Padding
  385. INSERT_PADDING_DSPWORDS(0x400);
  386. DspStatus dsp_status;
  387. DspDebug dsp_debug;
  388. FinalMixSamples final_samples;
  389. SourceStatus source_statuses;
  390. Compressor compressor;
  391. DspConfiguration dsp_configuration;
  392. IntermediateMixSamples intermediate_mix_samples;
  393. SourceConfiguration source_configurations;
  394. AdpcmCoefficients adpcm_coefficients;
  395. struct {
  396. INSERT_PADDING_DSPWORDS(0x100);
  397. } unknown10;
  398. struct {
  399. INSERT_PADDING_DSPWORDS(0xC0);
  400. } unknown11;
  401. struct {
  402. INSERT_PADDING_DSPWORDS(0x180);
  403. } unknown12;
  404. struct {
  405. INSERT_PADDING_DSPWORDS(0xA);
  406. } unknown13;
  407. struct {
  408. INSERT_PADDING_DSPWORDS(0x13A3);
  409. } unknown14;
  410. u16_le frame_counter;
  411. };
  412. ASSERT_DSP_STRUCT(SharedMemory, 0x8000);
  413. // Structures must have an offset that is a multiple of two.
  414. static_assert(offsetof(SharedMemory, frame_counter) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  415. static_assert(offsetof(SharedMemory, source_configurations) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  416. static_assert(offsetof(SharedMemory, source_statuses) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  417. static_assert(offsetof(SharedMemory, adpcm_coefficients) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  418. static_assert(offsetof(SharedMemory, dsp_configuration) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  419. static_assert(offsetof(SharedMemory, dsp_status) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  420. static_assert(offsetof(SharedMemory, final_samples) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  421. static_assert(offsetof(SharedMemory, intermediate_mix_samples) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  422. static_assert(offsetof(SharedMemory, compressor) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  423. static_assert(offsetof(SharedMemory, dsp_debug) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  424. static_assert(offsetof(SharedMemory, unknown10) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  425. static_assert(offsetof(SharedMemory, unknown11) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  426. static_assert(offsetof(SharedMemory, unknown12) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  427. static_assert(offsetof(SharedMemory, unknown13) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  428. static_assert(offsetof(SharedMemory, unknown14) % 2 == 0, "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
  429. #undef INSERT_PADDING_DSPWORDS
  430. #undef ASSERT_DSP_STRUCT
  431. /// Initialize DSP hardware
  432. void Init();
  433. /// Shutdown DSP hardware
  434. void Shutdown();
  435. /**
  436. * Perform processing and updates state of current shared memory buffer.
  437. * This function is called every audio tick before triggering the audio interrupt.
  438. * @return Whether an audio interrupt should be triggered this frame.
  439. */
  440. bool Tick();
  441. /// Returns a mutable reference to the current region. Current region is selected based on the frame counter.
  442. SharedMemory& CurrentRegion();
  443. } // namespace HLE
  444. } // namespace DSP