QOALoader.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*
  2. * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "QOALoader.h"
  7. #include "Loader.h"
  8. #include "LoaderError.h"
  9. #include "QOATypes.h"
  10. #include <AK/Array.h>
  11. #include <AK/Assertions.h>
  12. #include <AK/Endian.h>
  13. #include <AK/FixedArray.h>
  14. #include <AK/MemoryStream.h>
  15. #include <AK/Stream.h>
  16. #include <AK/Types.h>
  17. #include <LibCore/File.h>
  18. namespace Audio {
  19. QOALoaderPlugin::QOALoaderPlugin(NonnullOwnPtr<AK::SeekableStream> stream)
  20. : LoaderPlugin(move(stream))
  21. {
  22. }
  23. bool QOALoaderPlugin::sniff(SeekableStream& stream)
  24. {
  25. auto maybe_qoa = stream.read_value<BigEndian<u32>>();
  26. return !maybe_qoa.is_error() && maybe_qoa.value() == QOA::magic;
  27. }
  28. ErrorOr<NonnullOwnPtr<LoaderPlugin>, LoaderError> QOALoaderPlugin::create(NonnullOwnPtr<SeekableStream> stream)
  29. {
  30. auto loader = make<QOALoaderPlugin>(move(stream));
  31. TRY(loader->initialize());
  32. return loader;
  33. }
  34. MaybeLoaderError QOALoaderPlugin::initialize()
  35. {
  36. TRY(parse_header());
  37. TRY(reset());
  38. return {};
  39. }
  40. MaybeLoaderError QOALoaderPlugin::parse_header()
  41. {
  42. u32 header_magic = TRY(m_stream->read_value<BigEndian<u32>>());
  43. if (header_magic != QOA::magic)
  44. return LoaderError { LoaderError::Category::Format, 0, "QOA header: Magic number must be 'qoaf'" };
  45. m_total_samples = TRY(m_stream->read_value<BigEndian<u32>>());
  46. return {};
  47. }
  48. MaybeLoaderError QOALoaderPlugin::load_one_frame(Span<Sample>& target, IsFirstFrame is_first_frame)
  49. {
  50. QOA::FrameHeader header = TRY(m_stream->read_value<QOA::FrameHeader>());
  51. if (header.num_channels > 8)
  52. dbgln("QOALoader: Warning: QOA frame at {} has more than 8 channels ({}), this is not supported by the reference implementation.", TRY(m_stream->tell()) - sizeof(QOA::FrameHeader), header.num_channels);
  53. if (header.num_channels == 0)
  54. return LoaderError { LoaderError::Category::Format, TRY(m_stream->tell()), "QOA frame: Number of channels must be greater than 0" };
  55. if (header.sample_count > QOA::max_frame_samples)
  56. return LoaderError { LoaderError::Category::Format, TRY(m_stream->tell()), "QOA frame: Too many samples in frame" };
  57. // We weren't given a large enough buffer; signal that we didn't write anything and return.
  58. if (header.sample_count > target.size()) {
  59. target = target.trim(0);
  60. TRY(m_stream->seek(-sizeof(QOA::frame_header_size), AK::SeekMode::FromCurrentPosition));
  61. return {};
  62. }
  63. target = target.trim(header.sample_count);
  64. auto lms_states = TRY(FixedArray<QOA::LMSState>::create(header.num_channels));
  65. for (size_t channel = 0; channel < header.num_channels; ++channel) {
  66. auto history_packed = TRY(m_stream->read_value<BigEndian<u64>>());
  67. auto weights_packed = TRY(m_stream->read_value<BigEndian<u64>>());
  68. lms_states[channel] = { history_packed, weights_packed };
  69. }
  70. // We pre-allocate very large arrays here, but that's the last allocation of the QOA loader!
  71. // Everything else is just shuffling data around.
  72. // (We will also be using all of the arrays in every frame but the last one.)
  73. auto channels = TRY((FixedArray<Array<i16, QOA::max_frame_samples>>::create(header.num_channels)));
  74. // There's usually (and at maximum) 256 slices per channel, but less at the very end.
  75. // If the final slice would be partial, we still need to decode it; integer division would tell us that this final slice doesn't exist.
  76. auto const slice_count = static_cast<size_t>(ceil(static_cast<double>(header.sample_count) / static_cast<double>(QOA::slice_samples)));
  77. VERIFY(slice_count <= QOA::max_slices_per_frame);
  78. // Observe the loop nesting: Slices are channel-interleaved.
  79. for (size_t slice = 0; slice < slice_count; ++slice) {
  80. for (size_t channel = 0; channel < header.num_channels; ++channel) {
  81. auto slice_samples = channels[channel].span().slice(slice * QOA::slice_samples, QOA::slice_samples);
  82. TRY(read_one_slice(lms_states[channel], slice_samples));
  83. }
  84. }
  85. if (is_first_frame == IsFirstFrame::Yes) {
  86. m_num_channels = header.num_channels;
  87. m_sample_rate = header.sample_rate;
  88. } else {
  89. if (m_sample_rate != header.sample_rate)
  90. return LoaderError { LoaderError::Category::Unimplemented, TRY(m_stream->tell()), "QOA: Differing sample rate in non-initial frame" };
  91. if (m_num_channels != header.num_channels)
  92. m_has_uniform_channel_count = false;
  93. }
  94. switch (header.num_channels) {
  95. case 1:
  96. for (size_t sample = 0; sample < header.sample_count; ++sample)
  97. target[sample] = Sample { static_cast<float>(channels[0][sample]) / static_cast<float>(NumericLimits<i16>::max()) };
  98. break;
  99. // FIXME: Combine surround channels sensibly, FlacLoader has the same simplification at the moment.
  100. case 2:
  101. case 3:
  102. case 4:
  103. case 5:
  104. case 6:
  105. case 7:
  106. case 8:
  107. default:
  108. for (size_t sample = 0; sample < header.sample_count; ++sample) {
  109. target[sample] = {
  110. static_cast<float>(channels[0][sample]) / static_cast<float>(NumericLimits<i16>::max()),
  111. static_cast<float>(channels[1][sample]) / static_cast<float>(NumericLimits<i16>::max()),
  112. };
  113. }
  114. break;
  115. }
  116. return {};
  117. }
  118. ErrorOr<Vector<FixedArray<Sample>>, LoaderError> QOALoaderPlugin::load_chunks(size_t samples_to_read_from_input)
  119. {
  120. ssize_t const remaining_samples = static_cast<ssize_t>(m_total_samples - m_loaded_samples);
  121. if (remaining_samples <= 0)
  122. return Vector<FixedArray<Sample>> {};
  123. size_t const samples_to_read = min(samples_to_read_from_input, remaining_samples);
  124. auto is_first_frame = m_loaded_samples == 0 ? IsFirstFrame::Yes : IsFirstFrame::No;
  125. Vector<FixedArray<Sample>> frames;
  126. size_t current_loaded_samples = 0;
  127. while (current_loaded_samples < samples_to_read) {
  128. auto samples = TRY(FixedArray<Sample>::create(QOA::max_frame_samples));
  129. auto slice_to_load_into = samples.span();
  130. TRY(this->load_one_frame(slice_to_load_into, is_first_frame));
  131. is_first_frame = IsFirstFrame::No;
  132. VERIFY(slice_to_load_into.size() <= QOA::max_frame_samples);
  133. current_loaded_samples += slice_to_load_into.size();
  134. if (slice_to_load_into.size() != samples.size()) {
  135. auto smaller_samples = TRY(FixedArray<Sample>::create(slice_to_load_into));
  136. samples.swap(smaller_samples);
  137. }
  138. TRY(frames.try_append(move(samples)));
  139. if (slice_to_load_into.size() != samples.size())
  140. break;
  141. }
  142. m_loaded_samples += current_loaded_samples;
  143. return frames;
  144. }
  145. MaybeLoaderError QOALoaderPlugin::reset()
  146. {
  147. TRY(m_stream->seek(QOA::header_size, AK::SeekMode::SetPosition));
  148. m_loaded_samples = 0;
  149. // Read the first frame, then seek back to the beginning. This is necessary since the first frame contains the sample rate and channel count.
  150. auto frame_samples = TRY(FixedArray<Sample>::create(QOA::max_frame_samples));
  151. auto span = frame_samples.span();
  152. TRY(load_one_frame(span, IsFirstFrame::Yes));
  153. TRY(m_stream->seek(QOA::header_size, AK::SeekMode::SetPosition));
  154. m_loaded_samples = 0;
  155. return {};
  156. }
  157. MaybeLoaderError QOALoaderPlugin::seek(int sample_index)
  158. {
  159. if (sample_index == 0 && m_loaded_samples == 0)
  160. return {};
  161. // A QOA file consists of 8 bytes header followed by a number of usually fixed-size frames.
  162. // This fixed bitrate allows us to seek in constant time.
  163. if (!m_has_uniform_channel_count)
  164. return LoaderError { LoaderError::Category::Unimplemented, TRY(m_stream->tell()), "QOA with non-uniform channel count is currently not seekable"sv };
  165. /// FIXME: Change the Loader API to use size_t.
  166. VERIFY(sample_index >= 0);
  167. // We seek to the frame "before"; i.e. the frame that contains that sample.
  168. auto const frame_of_sample = static_cast<size_t>(AK::floor<double>(static_cast<double>(sample_index) / static_cast<double>(QOA::max_frame_samples)));
  169. auto const frame_size = QOA::frame_header_size + m_num_channels * (QOA::lms_state_size + sizeof(QOA::PackedSlice) * QOA::max_slices_per_frame);
  170. auto const byte_index = QOA::header_size + frame_of_sample * frame_size;
  171. TRY(m_stream->seek(byte_index, AK::SeekMode::SetPosition));
  172. m_loaded_samples = frame_of_sample * QOA::max_frame_samples;
  173. return {};
  174. }
  175. MaybeLoaderError QOALoaderPlugin::read_one_slice(QOA::LMSState& lms_state, Span<i16>& samples)
  176. {
  177. VERIFY(samples.size() == QOA::slice_samples);
  178. auto packed_slice = TRY(m_stream->read_value<BigEndian<u64>>());
  179. auto unpacked_slice = unpack_slice(packed_slice);
  180. for (size_t i = 0; i < QOA::slice_samples; ++i) {
  181. auto const residual = unpacked_slice.residuals[i];
  182. auto const predicted = lms_state.predict();
  183. auto const dequantized = QOA::dequantization_table[unpacked_slice.scale_factor_index][residual];
  184. auto const reconstructed = clamp(predicted + dequantized, QOA::sample_minimum, QOA::sample_maximum);
  185. samples[i] = static_cast<i16>(reconstructed);
  186. lms_state.update(reconstructed, dequantized);
  187. }
  188. return {};
  189. }
  190. QOA::UnpackedSlice QOALoaderPlugin::unpack_slice(QOA::PackedSlice packed_slice)
  191. {
  192. size_t const scale_factor_index = (packed_slice >> 60) & 0b1111;
  193. Array<u8, 20> residuals = {};
  194. auto shifted_slice = packed_slice << 4;
  195. for (size_t i = 0; i < QOA::slice_samples; ++i) {
  196. residuals[i] = static_cast<u8>((shifted_slice >> 61) & 0b111);
  197. shifted_slice <<= 3;
  198. }
  199. return {
  200. .scale_factor_index = scale_factor_index,
  201. .residuals = residuals,
  202. };
  203. }
  204. i16 QOALoaderPlugin::qoa_divide(i16 value, i16 scale_factor)
  205. {
  206. auto const reciprocal = QOA::reciprocal_table[scale_factor];
  207. auto const n = (value * reciprocal + (1 << 15)) >> 16;
  208. // Rounding away from zero gives better quantization for small values.
  209. auto const n_rounded = n + (static_cast<int>(value > 0) - static_cast<int>(value < 0)) - (static_cast<int>(n > 0) - static_cast<int>(n < 0));
  210. return static_cast<i16>(n_rounded);
  211. }
  212. }