codec.cpp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include "audio_core/codec.h"
  6. namespace AudioCore::Codec {
  7. std::vector<s16> DecodeADPCM(const u8* const data, std::size_t size, const ADPCM_Coeff& coeff,
  8. ADPCMState& state) {
  9. // GC-ADPCM with scale factor and variable coefficients.
  10. // Frames are 8 bytes long containing 14 samples each.
  11. // Samples are 4 bits (one nibble) long.
  12. constexpr std::size_t FRAME_LEN = 8;
  13. constexpr std::size_t SAMPLES_PER_FRAME = 14;
  14. constexpr std::array<int, 16> SIGNED_NIBBLES = {
  15. {0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1}};
  16. const std::size_t sample_count = (size / FRAME_LEN) * SAMPLES_PER_FRAME;
  17. const std::size_t ret_size =
  18. sample_count % 2 == 0 ? sample_count : sample_count + 1; // Ensure multiple of two.
  19. std::vector<s16> ret(ret_size);
  20. int yn1 = state.yn1, yn2 = state.yn2;
  21. const std::size_t NUM_FRAMES =
  22. (sample_count + (SAMPLES_PER_FRAME - 1)) / SAMPLES_PER_FRAME; // Round up.
  23. for (std::size_t framei = 0; framei < NUM_FRAMES; framei++) {
  24. const int frame_header = data[framei * FRAME_LEN];
  25. const int scale = 1 << (frame_header & 0xF);
  26. const int idx = (frame_header >> 4) & 0x7;
  27. // Coefficients are fixed point with 11 bits fractional part.
  28. const int coef1 = coeff[idx * 2 + 0];
  29. const int coef2 = coeff[idx * 2 + 1];
  30. // Decodes an audio sample. One nibble produces one sample.
  31. const auto decode_sample = [&](const int nibble) -> s16 {
  32. const int xn = nibble * scale;
  33. // We first transform everything into 11 bit fixed point, perform the second order
  34. // digital filter, then transform back.
  35. // 0x400 == 0.5 in 11 bit fixed point.
  36. // Filter: y[n] = x[n] + 0.5 + c1 * y[n-1] + c2 * y[n-2]
  37. int val = ((xn << 11) + 0x400 + coef1 * yn1 + coef2 * yn2) >> 11;
  38. // Clamp to output range.
  39. val = std::clamp<s32>(val, -32768, 32767);
  40. // Advance output feedback.
  41. yn2 = yn1;
  42. yn1 = val;
  43. return static_cast<s16>(val);
  44. };
  45. std::size_t outputi = framei * SAMPLES_PER_FRAME;
  46. std::size_t datai = framei * FRAME_LEN + 1;
  47. for (std::size_t i = 0; i < SAMPLES_PER_FRAME && outputi < sample_count; i += 2) {
  48. const s16 sample1 = decode_sample(SIGNED_NIBBLES[data[datai] >> 4]);
  49. ret[outputi] = sample1;
  50. outputi++;
  51. const s16 sample2 = decode_sample(SIGNED_NIBBLES[data[datai] & 0xF]);
  52. ret[outputi] = sample2;
  53. outputi++;
  54. datai++;
  55. }
  56. }
  57. state.yn1 = yn1;
  58. state.yn2 = yn2;
  59. return ret;
  60. }
  61. } // namespace AudioCore::Codec