FlacLoader.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <malu.bertsch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include "Buffer.h"
  8. #include "FlacTypes.h"
  9. #include "Loader.h"
  10. #include <AK/BitStream.h>
  11. #include <AK/Buffered.h>
  12. #include <AK/Error.h>
  13. #include <AK/Stream.h>
  14. #include <AK/Types.h>
  15. #include <AK/Variant.h>
  16. #include <LibCore/FileStream.h>
  17. namespace Audio {
  18. // Experimentally determined to be a decent buffer size on i686:
  19. // 4K (the default) is slightly worse, and 64K is much worse.
  20. // At sufficiently large buffer sizes, the advantage of infrequent read() calls is outweighed by the memmove() overhead.
  21. // There was no intensive fine-tuning done to determine this value, so improvements may definitely be possible.
  22. constexpr size_t FLAC_BUFFER_SIZE = 8 * KiB;
  23. template<size_t Size = FLAC_BUFFER_SIZE>
  24. class FlacInputStream : public Variant<Buffered<Core::InputFileStream, Size>, InputMemoryStream> {
  25. public:
  26. using Variant<Buffered<Core::InputFileStream, Size>, InputMemoryStream>::Variant;
  27. bool seek(size_t pos)
  28. {
  29. return this->visit(
  30. [&](Buffered<Core::InputFileStream, Size>& buffered) {
  31. // Discard the buffer, then seek normally.
  32. if (!buffered.discard_or_error(buffered.buffered()))
  33. return false;
  34. return buffered.underlying_stream().seek(pos);
  35. },
  36. [&](InputMemoryStream& stream) {
  37. if (pos >= stream.bytes().size()) {
  38. return false;
  39. }
  40. stream.seek(pos);
  41. return true;
  42. });
  43. }
  44. bool handle_any_error()
  45. {
  46. return this->visit(
  47. [&](auto& stream) {
  48. return stream.handle_any_error();
  49. });
  50. }
  51. InputBitStream bit_stream()
  52. {
  53. return this->visit(
  54. [&](auto& stream) {
  55. return InputBitStream(stream);
  56. });
  57. }
  58. };
  59. ALWAYS_INLINE u8 frame_channel_type_to_channel_count(FlacFrameChannelType channel_type);
  60. // Sign-extend an arbitrary-size signed number to 64 bit signed
  61. ALWAYS_INLINE i64 sign_extend(u32 n, u8 size);
  62. // Decodes the sign representation method used in Rice coding.
  63. // Numbers alternate between positive and negative: 0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5, ...
  64. ALWAYS_INLINE i32 rice_to_signed(u32 x);
  65. // decoders
  66. // read a UTF-8 encoded number, even if it is not a valid codepoint
  67. ALWAYS_INLINE u64 read_utf8_char(InputStream& input);
  68. // decode a single number encoded with exponential golomb encoding of the specified order
  69. ALWAYS_INLINE i32 decode_unsigned_exp_golomb(u8 order, InputBitStream& bit_input);
  70. class FlacLoaderPlugin : public LoaderPlugin {
  71. public:
  72. explicit FlacLoaderPlugin(StringView path);
  73. explicit FlacLoaderPlugin(const ByteBuffer& buffer);
  74. ~FlacLoaderPlugin()
  75. {
  76. if (m_stream)
  77. m_stream->handle_any_error();
  78. }
  79. virtual MaybeLoaderError initialize() override;
  80. virtual LoaderSamples get_more_samples(size_t max_bytes_to_read_from_input = 128 * KiB) override;
  81. virtual MaybeLoaderError reset() override;
  82. virtual MaybeLoaderError seek(const int position) override;
  83. virtual int loaded_samples() override { return static_cast<int>(m_loaded_samples); }
  84. virtual int total_samples() override { return static_cast<int>(m_total_samples); }
  85. virtual u32 sample_rate() override { return m_sample_rate; }
  86. virtual u16 num_channels() override { return m_num_channels; }
  87. virtual PcmSampleFormat pcm_format() override { return m_sample_format; }
  88. virtual RefPtr<Core::File> file() override { return m_file; }
  89. bool is_fixed_blocksize_stream() const { return m_min_block_size == m_max_block_size; }
  90. bool sample_count_unknown() const { return m_total_samples == 0; }
  91. private:
  92. MaybeLoaderError parse_header();
  93. // Either returns the metadata block or sets error message.
  94. // Additionally, increments m_data_start_location past the read meta block.
  95. ErrorOr<FlacRawMetadataBlock, LoaderError> next_meta_block(InputBitStream& bit_input);
  96. // Fetches and writes the next FLAC frame
  97. MaybeLoaderError next_frame(Span<Sample>);
  98. // Helper of next_frame that fetches a sub frame's header
  99. ErrorOr<FlacSubframeHeader, LoaderError> next_subframe_header(InputBitStream& bit_input, u8 channel_index);
  100. // Helper of next_frame that decompresses a subframe
  101. ErrorOr<Vector<i32>, LoaderError> parse_subframe(FlacSubframeHeader& subframe_header, InputBitStream& bit_input);
  102. // Subframe-internal data decoders (heavy lifting)
  103. ErrorOr<Vector<i32>, LoaderError> decode_fixed_lpc(FlacSubframeHeader& subframe, InputBitStream& bit_input);
  104. ErrorOr<Vector<i32>, LoaderError> decode_verbatim(FlacSubframeHeader& subframe, InputBitStream& bit_input);
  105. ErrorOr<Vector<i32>, LoaderError> decode_custom_lpc(FlacSubframeHeader& subframe, InputBitStream& bit_input);
  106. MaybeLoaderError decode_residual(Vector<i32>& decoded, FlacSubframeHeader& subframe, InputBitStream& bit_input);
  107. // decode a single rice partition that has its own rice parameter
  108. ALWAYS_INLINE Vector<i32> decode_rice_partition(u8 partition_type, u32 partitions, u32 partition_index, FlacSubframeHeader& subframe, InputBitStream& bit_input);
  109. // Converters for special coding used in frame headers
  110. ALWAYS_INLINE ErrorOr<u32, LoaderError> convert_sample_count_code(u8 sample_count_code);
  111. ALWAYS_INLINE ErrorOr<u32, LoaderError> convert_sample_rate_code(u8 sample_rate_code);
  112. ALWAYS_INLINE ErrorOr<PcmSampleFormat, LoaderError> convert_bit_depth_code(u8 bit_depth_code);
  113. RefPtr<Core::File> m_file;
  114. Optional<LoaderError> m_error {};
  115. // Data obtained directly from the FLAC metadata: many values have specific bit counts
  116. u32 m_sample_rate { 0 }; // 20 bit
  117. u8 m_num_channels { 0 }; // 3 bit
  118. PcmSampleFormat m_sample_format; // 5 bits for the integer bit depth
  119. // Blocks are units of decoded audio data
  120. u16 m_min_block_size { 0 };
  121. u16 m_max_block_size { 0 };
  122. // Frames are units of encoded audio data, both of these are 24-bit
  123. u32 m_min_frame_size { 0 }; //24 bit
  124. u32 m_max_frame_size { 0 }; // 24 bit
  125. u64 m_total_samples { 0 }; // 36 bit
  126. u8 m_md5_checksum[128 / 8]; // 128 bit (!)
  127. size_t m_loaded_samples { 0 };
  128. // keep track of the start of the data in the FLAC stream to seek back more easily
  129. u64 m_data_start_location { 0 };
  130. OwnPtr<FlacInputStream<FLAC_BUFFER_SIZE>> m_stream;
  131. Optional<FlacFrameHeader> m_current_frame;
  132. // Whatever the last get_more_samples() call couldn't return gets stored here.
  133. Vector<Sample, FLAC_BUFFER_SIZE> m_unread_data;
  134. u64 m_current_sample_or_frame { 0 };
  135. };
  136. }