QOATypes.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "QOATypes.h"
  7. #include <AK/Endian.h>
  8. #include <AK/Stream.h>
  9. namespace Audio::QOA {
  10. ErrorOr<FrameHeader> FrameHeader::read_from_stream(Stream& stream)
  11. {
  12. FrameHeader header;
  13. header.num_channels = TRY(stream.read_value<u8>());
  14. u8 sample_rate[3];
  15. // Enforce the order of the reads here, since the order of expression evaluations further down is implementation-defined.
  16. sample_rate[0] = TRY(stream.read_value<u8>());
  17. sample_rate[1] = TRY(stream.read_value<u8>());
  18. sample_rate[2] = TRY(stream.read_value<u8>());
  19. header.sample_rate = (sample_rate[0] << 16) | (sample_rate[1] << 8) | sample_rate[2];
  20. header.sample_count = TRY(stream.read_value<BigEndian<u16>>());
  21. header.frame_size = TRY(stream.read_value<BigEndian<u16>>());
  22. return header;
  23. }
  24. LMSState::LMSState(u64 history_packed, u64 weights_packed)
  25. {
  26. for (size_t i = 0; i < lms_history; ++i) {
  27. // The casts ensure proper sign extension.
  28. history[i] = static_cast<i16>(history_packed >> 48);
  29. history_packed <<= 16;
  30. weights[i] = static_cast<i16>(weights_packed >> 48);
  31. weights_packed <<= 16;
  32. }
  33. }
  34. i32 LMSState::predict() const
  35. {
  36. // The spec specifies that overflows are not allowed, but we do a safe thing anyways.
  37. Checked<i32> prediction = 0;
  38. for (size_t i = 0; i < lms_history; ++i)
  39. prediction.saturating_add(Checked<i32>::saturating_mul(history[i], weights[i]));
  40. return prediction.value() >> 13;
  41. }
  42. void LMSState::update(i32 sample, i32 residual)
  43. {
  44. i32 delta = residual >> 4;
  45. for (size_t i = 0; i < lms_history; ++i)
  46. weights[i] += history[i] < 0 ? -delta : delta;
  47. for (size_t i = 0; i < lms_history - 1; ++i)
  48. history[i] = history[i + 1];
  49. history[lms_history - 1] = sample;
  50. }
  51. }