FlacLoader.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/DeprecatedFlyString.h>
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/FixedArray.h>
  10. #include <AK/Format.h>
  11. #include <AK/IntegralMath.h>
  12. #include <AK/Math.h>
  13. #include <AK/MemoryStream.h>
  14. #include <AK/NonnullOwnPtr.h>
  15. #include <AK/ScopeGuard.h>
  16. #include <AK/StdLibExtras.h>
  17. #include <AK/Try.h>
  18. #include <AK/TypedTransfer.h>
  19. #include <AK/UFixedBigInt.h>
  20. #include <LibAudio/FlacLoader.h>
  21. #include <LibAudio/FlacTypes.h>
  22. #include <LibAudio/GenericTypes.h>
  23. #include <LibAudio/LoaderError.h>
  24. #include <LibAudio/MultiChannel.h>
  25. #include <LibAudio/Resampler.h>
  26. #include <LibAudio/VorbisComment.h>
  27. #include <LibCore/File.h>
  28. #include <LibCrypto/Checksum/ChecksumFunction.h>
  29. #include <LibCrypto/Checksum/ChecksummingStream.h>
  30. namespace Audio {
  31. FlacLoaderPlugin::FlacLoaderPlugin(NonnullOwnPtr<SeekableStream> stream)
  32. : LoaderPlugin(move(stream))
  33. {
  34. }
  35. ErrorOr<NonnullOwnPtr<LoaderPlugin>, LoaderError> FlacLoaderPlugin::create(NonnullOwnPtr<SeekableStream> stream)
  36. {
  37. auto loader = make<FlacLoaderPlugin>(move(stream));
  38. TRY(loader->initialize());
  39. return loader;
  40. }
  41. MaybeLoaderError FlacLoaderPlugin::initialize()
  42. {
  43. TRY(parse_header());
  44. TRY(reset());
  45. return {};
  46. }
  47. bool FlacLoaderPlugin::sniff(SeekableStream& stream)
  48. {
  49. BigEndianInputBitStream bit_input { MaybeOwned<Stream>(stream) };
  50. auto maybe_flac = bit_input.read_bits<u32>(32);
  51. return !maybe_flac.is_error() && maybe_flac.value() == 0x664C6143; // "flaC"
  52. }
  53. // 11.5 STREAM
  54. MaybeLoaderError FlacLoaderPlugin::parse_header()
  55. {
  56. BigEndianInputBitStream bit_input { MaybeOwned<Stream>(*m_stream) };
  57. // A mixture of VERIFY and the non-crashing TRY().
  58. #define FLAC_VERIFY(check, category, msg) \
  59. do { \
  60. if (!(check)) { \
  61. return LoaderError { category, TRY(m_stream->tell()), DeprecatedString::formatted("FLAC header: {}", msg) }; \
  62. } \
  63. } while (0)
  64. // Magic number
  65. u32 flac = TRY(bit_input.read_bits<u32>(32));
  66. m_data_start_location += 4;
  67. FLAC_VERIFY(flac == 0x664C6143, LoaderError::Category::Format, "Magic number must be 'flaC'"); // "flaC"
  68. // Receive the streaminfo block
  69. auto streaminfo = TRY(next_meta_block(bit_input));
  70. FLAC_VERIFY(streaminfo.type == FlacMetadataBlockType::STREAMINFO, LoaderError::Category::Format, "First block must be STREAMINFO");
  71. FixedMemoryStream streaminfo_data_memory { streaminfo.data.bytes() };
  72. BigEndianInputBitStream streaminfo_data { MaybeOwned<Stream>(streaminfo_data_memory) };
  73. // 11.10 METADATA_BLOCK_STREAMINFO
  74. m_min_block_size = TRY(streaminfo_data.read_bits<u16>(16));
  75. FLAC_VERIFY(m_min_block_size >= 16, LoaderError::Category::Format, "Minimum block size must be 16");
  76. m_max_block_size = TRY(streaminfo_data.read_bits<u16>(16));
  77. FLAC_VERIFY(m_max_block_size >= 16, LoaderError::Category::Format, "Maximum block size");
  78. m_min_frame_size = TRY(streaminfo_data.read_bits<u32>(24));
  79. m_max_frame_size = TRY(streaminfo_data.read_bits<u32>(24));
  80. m_sample_rate = TRY(streaminfo_data.read_bits<u32>(20));
  81. FLAC_VERIFY(m_sample_rate <= 655350, LoaderError::Category::Format, "Sample rate");
  82. m_num_channels = TRY(streaminfo_data.read_bits<u8>(3)) + 1; // 0 = one channel
  83. m_bits_per_sample = TRY(streaminfo_data.read_bits<u8>(5)) + 1;
  84. if (m_bits_per_sample <= 8) {
  85. // FIXME: Signed/Unsigned issues?
  86. m_sample_format = PcmSampleFormat::Uint8;
  87. } else if (m_bits_per_sample <= 16) {
  88. m_sample_format = PcmSampleFormat::Int16;
  89. } else if (m_bits_per_sample <= 24) {
  90. m_sample_format = PcmSampleFormat::Int24;
  91. } else if (m_bits_per_sample <= 32) {
  92. m_sample_format = PcmSampleFormat::Int32;
  93. } else {
  94. FLAC_VERIFY(false, LoaderError::Category::Format, "Sample bit depth too large");
  95. }
  96. m_total_samples = TRY(streaminfo_data.read_bits<u64>(36));
  97. if (m_total_samples == 0) {
  98. // "A value of zero here means the number of total samples is unknown."
  99. dbgln("FLAC Warning: File has unknown amount of samples, the loader will not stop before EOF");
  100. m_total_samples = NumericLimits<decltype(m_total_samples)>::max();
  101. }
  102. VERIFY(streaminfo_data.is_aligned_to_byte_boundary());
  103. TRY(streaminfo_data.read_until_filled({ m_md5_checksum, sizeof(m_md5_checksum) }));
  104. // Parse other blocks
  105. [[maybe_unused]] u16 meta_blocks_parsed = 1;
  106. [[maybe_unused]] u16 total_meta_blocks = meta_blocks_parsed;
  107. FlacRawMetadataBlock block = streaminfo;
  108. while (!block.is_last_block) {
  109. block = TRY(next_meta_block(bit_input));
  110. switch (block.type) {
  111. case (FlacMetadataBlockType::SEEKTABLE):
  112. TRY(load_seektable(block));
  113. break;
  114. case FlacMetadataBlockType::PICTURE:
  115. TRY(load_picture(block));
  116. break;
  117. case FlacMetadataBlockType::APPLICATION:
  118. // Note: Third-party library can encode specific data in this.
  119. dbgln("FLAC Warning: Unknown 'Application' metadata block encountered.");
  120. [[fallthrough]];
  121. case FlacMetadataBlockType::PADDING:
  122. // Note: A padding block is empty and does not need any treatment.
  123. break;
  124. case FlacMetadataBlockType::VORBIS_COMMENT:
  125. load_vorbis_comment(block);
  126. break;
  127. default:
  128. // TODO: Parse the remaining metadata block types.
  129. break;
  130. }
  131. ++total_meta_blocks;
  132. }
  133. dbgln_if(AFLACLOADER_DEBUG, "Parsed FLAC header: blocksize {}-{}{}, framesize {}-{}, {}Hz, {}bit, {} channels, {} samples total ({:.2f}s), MD5 {}, data start at {:x} bytes, {} headers total (skipped {})", m_min_block_size, m_max_block_size, is_fixed_blocksize_stream() ? " (constant)" : "", m_min_frame_size, m_max_frame_size, m_sample_rate, pcm_bits_per_sample(m_sample_format), m_num_channels, m_total_samples, static_cast<float>(m_total_samples) / static_cast<float>(m_sample_rate), m_md5_checksum, m_data_start_location, total_meta_blocks, total_meta_blocks - meta_blocks_parsed);
  134. return {};
  135. }
  136. // 11.19. METADATA_BLOCK_PICTURE
  137. MaybeLoaderError FlacLoaderPlugin::load_picture(FlacRawMetadataBlock& block)
  138. {
  139. FixedMemoryStream memory_stream { block.data.bytes() };
  140. BigEndianInputBitStream picture_block_bytes { MaybeOwned<Stream>(memory_stream) };
  141. PictureData picture;
  142. picture.type = static_cast<ID3PictureType>(TRY(picture_block_bytes.read_bits(32)));
  143. auto const mime_string_length = TRY(picture_block_bytes.read_bits(32));
  144. auto offset_before_seeking = memory_stream.offset();
  145. if (offset_before_seeking + mime_string_length >= block.data.size())
  146. return LoaderError { LoaderError::Category::Format, TRY(m_stream->tell()), "Picture MIME type exceeds available data" };
  147. // "The MIME type string, in printable ASCII characters 0x20-0x7E."
  148. picture.mime_string = TRY(String::from_stream(memory_stream, mime_string_length));
  149. for (auto code_point : picture.mime_string.code_points()) {
  150. if (code_point < 0x20 || code_point > 0x7E)
  151. return LoaderError { LoaderError::Category::Format, TRY(m_stream->tell()), "Picture MIME type is not ASCII in range 0x20 - 0x7E" };
  152. }
  153. auto const description_string_length = TRY(picture_block_bytes.read_bits(32));
  154. offset_before_seeking = memory_stream.offset();
  155. if (offset_before_seeking + description_string_length >= block.data.size())
  156. return LoaderError { LoaderError::Category::Format, TRY(m_stream->tell()), "Picture description exceeds available data" };
  157. picture.description_string = TRY(String::from_stream(memory_stream, description_string_length));
  158. picture.width = TRY(picture_block_bytes.read_bits(32));
  159. picture.height = TRY(picture_block_bytes.read_bits(32));
  160. picture.color_depth = TRY(picture_block_bytes.read_bits(32));
  161. picture.colors = TRY(picture_block_bytes.read_bits(32));
  162. auto const picture_size = TRY(picture_block_bytes.read_bits(32));
  163. offset_before_seeking = memory_stream.offset();
  164. if (offset_before_seeking + picture_size > block.data.size())
  165. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(TRY(m_stream->tell())), "Picture size exceeds available data" };
  166. TRY(memory_stream.seek(picture_size, SeekMode::FromCurrentPosition));
  167. picture.data = Vector<u8> { block.data.bytes().slice(offset_before_seeking, picture_size) };
  168. m_pictures.append(move(picture));
  169. return {};
  170. }
  171. // 11.15. METADATA_BLOCK_VORBIS_COMMENT
  172. void FlacLoaderPlugin::load_vorbis_comment(FlacRawMetadataBlock& block)
  173. {
  174. auto metadata_or_error = Audio::load_vorbis_comment(block.data);
  175. if (metadata_or_error.is_error()) {
  176. dbgln("FLAC Warning: Vorbis comment invalid, error: {}", metadata_or_error.release_error());
  177. return;
  178. }
  179. m_metadata = metadata_or_error.release_value();
  180. }
  181. // 11.13. METADATA_BLOCK_SEEKTABLE
  182. MaybeLoaderError FlacLoaderPlugin::load_seektable(FlacRawMetadataBlock& block)
  183. {
  184. FixedMemoryStream memory_stream { block.data.bytes() };
  185. BigEndianInputBitStream seektable_bytes { MaybeOwned<Stream>(memory_stream) };
  186. for (size_t i = 0; i < block.length / 18; ++i) {
  187. // 11.14. SEEKPOINT
  188. u64 sample_index = TRY(seektable_bytes.read_bits<u64>(64));
  189. u64 byte_offset = TRY(seektable_bytes.read_bits<u64>(64));
  190. // The sample count of a seek point is not relevant to us.
  191. [[maybe_unused]] u16 sample_count = TRY(seektable_bytes.read_bits<u16>(16));
  192. // Placeholder, to be ignored.
  193. if (sample_index == 0xFFFFFFFFFFFFFFFF)
  194. continue;
  195. SeekPoint seekpoint {
  196. .sample_index = sample_index,
  197. .byte_offset = byte_offset,
  198. };
  199. TRY(m_seektable.insert_seek_point(seekpoint));
  200. }
  201. dbgln_if(AFLACLOADER_DEBUG, "Loaded seektable of size {}", m_seektable.size());
  202. return {};
  203. }
  204. // 11.6 METADATA_BLOCK
  205. ErrorOr<FlacRawMetadataBlock, LoaderError> FlacLoaderPlugin::next_meta_block(BigEndianInputBitStream& bit_input)
  206. {
  207. // 11.7 METADATA_BLOCK_HEADER
  208. bool is_last_block = TRY(bit_input.read_bit());
  209. // The block type enum constants agree with the specification
  210. FlacMetadataBlockType type = (FlacMetadataBlockType)TRY(bit_input.read_bits<u8>(7));
  211. m_data_start_location += 1;
  212. FLAC_VERIFY(type != FlacMetadataBlockType::INVALID, LoaderError::Category::Format, "Invalid metadata block");
  213. u32 block_length = TRY(bit_input.read_bits<u32>(24));
  214. m_data_start_location += 3;
  215. // Blocks can be zero-sized, which would trip up the raw data reader below.
  216. if (block_length == 0)
  217. return FlacRawMetadataBlock {
  218. .is_last_block = is_last_block,
  219. .type = type,
  220. .length = 0,
  221. .data = TRY(ByteBuffer::create_uninitialized(0))
  222. };
  223. auto block_data_result = ByteBuffer::create_uninitialized(block_length);
  224. FLAC_VERIFY(!block_data_result.is_error(), LoaderError::Category::IO, "Out of memory");
  225. auto block_data = block_data_result.release_value();
  226. TRY(bit_input.read_until_filled(block_data));
  227. m_data_start_location += block_length;
  228. return FlacRawMetadataBlock {
  229. is_last_block,
  230. type,
  231. block_length,
  232. block_data,
  233. };
  234. }
  235. #undef FLAC_VERIFY
  236. MaybeLoaderError FlacLoaderPlugin::reset()
  237. {
  238. TRY(seek(0));
  239. m_current_frame.clear();
  240. return {};
  241. }
  242. MaybeLoaderError FlacLoaderPlugin::seek(int int_sample_index)
  243. {
  244. auto sample_index = static_cast<size_t>(int_sample_index);
  245. if (sample_index == m_loaded_samples)
  246. return {};
  247. auto maybe_target_seekpoint = m_seektable.seek_point_before(sample_index);
  248. auto const seek_tolerance = (seek_tolerance_ms * m_sample_rate) / 1000;
  249. // No seektable or no fitting entry: Perform normal forward read
  250. if (!maybe_target_seekpoint.has_value()) {
  251. if (sample_index < m_loaded_samples) {
  252. TRY(m_stream->seek(m_data_start_location, SeekMode::SetPosition));
  253. m_loaded_samples = 0;
  254. }
  255. if (sample_index - m_loaded_samples == 0)
  256. return {};
  257. dbgln_if(AFLACLOADER_DEBUG, "Seeking {} samples manually", sample_index - m_loaded_samples);
  258. } else {
  259. auto target_seekpoint = maybe_target_seekpoint.release_value();
  260. // When a small seek happens, we may already be closer to the target than the seekpoint.
  261. if (sample_index - target_seekpoint.sample_index > sample_index - m_loaded_samples) {
  262. dbgln_if(AFLACLOADER_DEBUG, "Close enough to target ({} samples): not seeking", sample_index - m_loaded_samples);
  263. return {};
  264. }
  265. dbgln_if(AFLACLOADER_DEBUG, "Seeking to seektable: sample index {}, byte offset {}", target_seekpoint.sample_index, target_seekpoint.byte_offset);
  266. auto position = target_seekpoint.byte_offset + m_data_start_location;
  267. if (m_stream->seek(static_cast<i64>(position), SeekMode::SetPosition).is_error())
  268. return LoaderError { LoaderError::Category::IO, m_loaded_samples, DeprecatedString::formatted("Invalid seek position {}", position) };
  269. m_loaded_samples = target_seekpoint.sample_index;
  270. }
  271. // Skip frames until we're within the seek tolerance.
  272. while (sample_index - m_loaded_samples > seek_tolerance) {
  273. (void)TRY(next_frame());
  274. m_loaded_samples += m_current_frame->sample_count;
  275. }
  276. return {};
  277. }
  278. bool FlacLoaderPlugin::should_insert_seekpoint_at(u64 sample_index) const
  279. {
  280. auto const max_seekpoint_distance = (maximum_seekpoint_distance_ms * m_sample_rate) / 1000;
  281. auto const seek_tolerance = (seek_tolerance_ms * m_sample_rate) / 1000;
  282. auto const current_seekpoint_distance = m_seektable.seek_point_sample_distance_around(sample_index).value_or(NumericLimits<u64>::max());
  283. auto const previous_seekpoint = m_seektable.seek_point_before(sample_index);
  284. auto const distance_to_previous_seekpoint = previous_seekpoint.has_value() ? sample_index - previous_seekpoint->sample_index : NumericLimits<u64>::max();
  285. // We insert a seekpoint only under two conditions:
  286. // - The seek points around us are spaced too far for what the loader recommends.
  287. // Prevents inserting too many seek points between pre-loaded seek points.
  288. // - We are so far away from the previous seek point that seeking will become too imprecise if we don't insert a seek point at least here.
  289. // Prevents inserting too many seek points at the end of files without pre-loaded seek points.
  290. return current_seekpoint_distance >= max_seekpoint_distance && distance_to_previous_seekpoint >= seek_tolerance;
  291. }
  292. ErrorOr<Vector<FixedArray<Sample>>, LoaderError> FlacLoaderPlugin::load_chunks(size_t samples_to_read_from_input)
  293. {
  294. ssize_t remaining_samples = static_cast<ssize_t>(m_total_samples - m_loaded_samples);
  295. // The first condition is relevant for unknown-size streams (total samples = 0 in the header)
  296. if (m_stream->is_eof() || (m_total_samples < NumericLimits<u64>::max() && remaining_samples <= 0))
  297. return Vector<FixedArray<Sample>> {};
  298. size_t samples_to_read = min(samples_to_read_from_input, remaining_samples);
  299. Vector<FixedArray<Sample>> frames;
  300. size_t sample_index = 0;
  301. while (!m_stream->is_eof() && sample_index < samples_to_read) {
  302. TRY(frames.try_append(TRY(next_frame())));
  303. sample_index += m_current_frame->sample_count;
  304. }
  305. m_loaded_samples += sample_index;
  306. return frames;
  307. }
  308. // 11.21. FRAME
  309. LoaderSamples FlacLoaderPlugin::next_frame()
  310. {
  311. #define FLAC_VERIFY(check, category, msg) \
  312. do { \
  313. if (!(check)) { \
  314. return LoaderError { category, static_cast<size_t>(m_current_sample_or_frame), DeprecatedString::formatted("FLAC header: {}", msg) }; \
  315. } \
  316. } while (0)
  317. auto frame_byte_index = TRY(m_stream->tell());
  318. auto sample_index = m_loaded_samples;
  319. // Insert a new seek point if we don't have enough here.
  320. if (should_insert_seekpoint_at(sample_index)) {
  321. dbgln_if(AFLACLOADER_DEBUG, "Inserting ad-hoc seek point for sample {} at byte {:x} (seekpoint spacing {} samples)", sample_index, frame_byte_index, m_seektable.seek_point_sample_distance_around(sample_index).value_or(NumericLimits<u64>::max()));
  322. auto maybe_error = m_seektable.insert_seek_point({ .sample_index = sample_index, .byte_offset = frame_byte_index - m_data_start_location });
  323. if (maybe_error.is_error())
  324. dbgln("FLAC Warning: Inserting seek point for sample {} failed: {}", sample_index, maybe_error.release_error());
  325. }
  326. auto checksum_stream = TRY(try_make<Crypto::Checksum::ChecksummingStream<FlacFrameHeaderCRC>>(MaybeOwned<Stream>(*m_stream)));
  327. BigEndianInputBitStream bit_stream { MaybeOwned<Stream> { *checksum_stream } };
  328. // TODO: Check the CRC-16 checksum by keeping track of read data.
  329. // 11.22. FRAME_HEADER
  330. u16 sync_code = TRY(bit_stream.read_bits<u16>(14));
  331. FLAC_VERIFY(sync_code == 0b11111111111110, LoaderError::Category::Format, "Sync code");
  332. bool reserved_bit = TRY(bit_stream.read_bit());
  333. FLAC_VERIFY(reserved_bit == 0, LoaderError::Category::Format, "Reserved frame header bit");
  334. // 11.22.2. BLOCKING STRATEGY
  335. [[maybe_unused]] bool blocking_strategy = TRY(bit_stream.read_bit());
  336. u32 sample_count = TRY(convert_sample_count_code(TRY(bit_stream.read_bits<u8>(4))));
  337. u32 frame_sample_rate = TRY(convert_sample_rate_code(TRY(bit_stream.read_bits<u8>(4))));
  338. u8 channel_type_num = TRY(bit_stream.read_bits<u8>(4));
  339. FLAC_VERIFY(channel_type_num < 0b1011, LoaderError::Category::Format, "Channel assignment");
  340. FlacFrameChannelType channel_type = (FlacFrameChannelType)channel_type_num;
  341. u8 bit_depth = TRY(convert_bit_depth_code(TRY(bit_stream.read_bits<u8>(3))));
  342. reserved_bit = TRY(bit_stream.read_bit());
  343. FLAC_VERIFY(reserved_bit == 0, LoaderError::Category::Format, "Reserved frame header end bit");
  344. // 11.22.8. CODED NUMBER
  345. m_current_sample_or_frame = TRY(read_utf8_char(bit_stream));
  346. // Conditional header variables
  347. // 11.22.9. BLOCK SIZE INT
  348. if (sample_count == FLAC_BLOCKSIZE_AT_END_OF_HEADER_8) {
  349. sample_count = TRY(bit_stream.read_bits<u32>(8)) + 1;
  350. } else if (sample_count == FLAC_BLOCKSIZE_AT_END_OF_HEADER_16) {
  351. sample_count = TRY(bit_stream.read_bits<u32>(16)) + 1;
  352. }
  353. // 11.22.10. SAMPLE RATE INT
  354. if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_8) {
  355. frame_sample_rate = TRY(bit_stream.read_bits<u32>(8)) * 1000;
  356. } else if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_16) {
  357. frame_sample_rate = TRY(bit_stream.read_bits<u32>(16));
  358. } else if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_16X10) {
  359. frame_sample_rate = TRY(bit_stream.read_bits<u32>(16)) * 10;
  360. }
  361. // It does not matter whether we extract the checksum from the digest here, or extract the digest 0x00 after processing the checksum.
  362. auto const calculated_checksum = checksum_stream->digest();
  363. // 11.22.11. FRAME CRC
  364. u8 specified_checksum = TRY(bit_stream.read_bits<u8>(8));
  365. VERIFY(bit_stream.is_aligned_to_byte_boundary());
  366. if (specified_checksum != calculated_checksum)
  367. dbgln("FLAC frame {}: Calculated header checksum {:02x} is different from specified checksum {:02x}", m_current_sample_or_frame, calculated_checksum, specified_checksum);
  368. dbgln_if(AFLACLOADER_DEBUG, "Frame: {} samples, {}bit {}Hz, channeltype {:x}, {} number {}, header checksum {:02x}{}", sample_count, bit_depth, frame_sample_rate, channel_type_num, blocking_strategy ? "sample" : "frame", m_current_sample_or_frame, specified_checksum, specified_checksum != calculated_checksum ? " (checksum error)"sv : ""sv);
  369. m_current_frame = FlacFrameHeader {
  370. sample_count,
  371. frame_sample_rate,
  372. channel_type,
  373. bit_depth,
  374. specified_checksum,
  375. };
  376. u8 subframe_count = frame_channel_type_to_channel_count(channel_type);
  377. Vector<FixedArray<float>> current_subframes;
  378. current_subframes.ensure_capacity(subframe_count);
  379. float sample_rescale = 1 / static_cast<float>(1 << (m_current_frame->bit_depth - 1));
  380. dbgln_if(AFLACLOADER_DEBUG, "Samples will be rescaled from {} bits: factor {:.8f}", m_current_frame->bit_depth, sample_rescale);
  381. for (u8 i = 0; i < subframe_count; ++i) {
  382. FlacSubframeHeader new_subframe = TRY(next_subframe_header(bit_stream, i));
  383. Vector<i64> subframe_samples = TRY(parse_subframe(new_subframe, bit_stream));
  384. VERIFY(subframe_samples.size() == m_current_frame->sample_count);
  385. FixedArray<float> scaled_samples = TRY(FixedArray<float>::create(m_current_frame->sample_count));
  386. for (size_t i = 0; i < m_current_frame->sample_count; ++i)
  387. scaled_samples[i] = static_cast<float>(subframe_samples[i]) * sample_rescale;
  388. current_subframes.unchecked_append(move(scaled_samples));
  389. }
  390. // 11.2. Overview ("The audio data is composed of...")
  391. bit_stream.align_to_byte_boundary();
  392. // 11.23. FRAME_FOOTER
  393. // TODO: check checksum, see above
  394. [[maybe_unused]] u16 footer_checksum = TRY(bit_stream.read_bits<u16>(16));
  395. dbgln_if(AFLACLOADER_DEBUG, "Subframe footer checksum: {}", footer_checksum);
  396. FixedArray<Sample> samples;
  397. switch (channel_type) {
  398. case FlacFrameChannelType::Mono:
  399. case FlacFrameChannelType::Stereo:
  400. case FlacFrameChannelType::StereoCenter:
  401. case FlacFrameChannelType::Surround4p0:
  402. case FlacFrameChannelType::Surround5p0:
  403. case FlacFrameChannelType::Surround5p1:
  404. case FlacFrameChannelType::Surround6p1:
  405. case FlacFrameChannelType::Surround7p1: {
  406. auto new_samples = TRY(downmix_surround_to_stereo<FixedArray<float>>(move(current_subframes)));
  407. samples.swap(new_samples);
  408. break;
  409. }
  410. case FlacFrameChannelType::LeftSideStereo: {
  411. auto new_samples = TRY(FixedArray<Sample>::create(m_current_frame->sample_count));
  412. samples.swap(new_samples);
  413. // channels are left (0) and side (1)
  414. for (size_t i = 0; i < m_current_frame->sample_count; ++i) {
  415. // right = left - side
  416. samples[i] = { current_subframes[0][i],
  417. current_subframes[0][i] - current_subframes[1][i] };
  418. }
  419. break;
  420. }
  421. case FlacFrameChannelType::RightSideStereo: {
  422. auto new_samples = TRY(FixedArray<Sample>::create(m_current_frame->sample_count));
  423. samples.swap(new_samples);
  424. // channels are side (0) and right (1)
  425. for (size_t i = 0; i < m_current_frame->sample_count; ++i) {
  426. // left = right + side
  427. samples[i] = { current_subframes[1][i] + current_subframes[0][i],
  428. current_subframes[1][i] };
  429. }
  430. break;
  431. }
  432. case FlacFrameChannelType::MidSideStereo: {
  433. auto new_samples = TRY(FixedArray<Sample>::create(m_current_frame->sample_count));
  434. samples.swap(new_samples);
  435. // channels are mid (0) and side (1)
  436. for (size_t i = 0; i < current_subframes[0].size(); ++i) {
  437. float mid = current_subframes[0][i];
  438. float side = current_subframes[1][i];
  439. mid *= 2;
  440. // prevent integer division errors
  441. samples[i] = { (mid + side) * .5f,
  442. (mid - side) * .5f };
  443. }
  444. break;
  445. }
  446. }
  447. return samples;
  448. #undef FLAC_VERIFY
  449. }
  450. // 11.22.3. INTERCHANNEL SAMPLE BLOCK SIZE
  451. ErrorOr<u32, LoaderError> FlacLoaderPlugin::convert_sample_count_code(u8 sample_count_code)
  452. {
  453. // single codes
  454. switch (sample_count_code) {
  455. case 0:
  456. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved block size" };
  457. case 1:
  458. return 192;
  459. case 6:
  460. return FLAC_BLOCKSIZE_AT_END_OF_HEADER_8;
  461. case 7:
  462. return FLAC_BLOCKSIZE_AT_END_OF_HEADER_16;
  463. }
  464. if (sample_count_code >= 2 && sample_count_code <= 5) {
  465. return 576 * AK::exp2(sample_count_code - 2);
  466. }
  467. return 256 * AK::exp2(sample_count_code - 8);
  468. }
  469. // 11.22.4. SAMPLE RATE
  470. ErrorOr<u32, LoaderError> FlacLoaderPlugin::convert_sample_rate_code(u8 sample_rate_code)
  471. {
  472. switch (sample_rate_code) {
  473. case 0:
  474. return m_sample_rate;
  475. case 1:
  476. return 88200;
  477. case 2:
  478. return 176400;
  479. case 3:
  480. return 192000;
  481. case 4:
  482. return 8000;
  483. case 5:
  484. return 16000;
  485. case 6:
  486. return 22050;
  487. case 7:
  488. return 24000;
  489. case 8:
  490. return 32000;
  491. case 9:
  492. return 44100;
  493. case 10:
  494. return 48000;
  495. case 11:
  496. return 96000;
  497. case 12:
  498. return FLAC_SAMPLERATE_AT_END_OF_HEADER_8;
  499. case 13:
  500. return FLAC_SAMPLERATE_AT_END_OF_HEADER_16;
  501. case 14:
  502. return FLAC_SAMPLERATE_AT_END_OF_HEADER_16X10;
  503. default:
  504. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Invalid sample rate code" };
  505. }
  506. }
  507. // 11.22.6. SAMPLE SIZE
  508. ErrorOr<u8, LoaderError> FlacLoaderPlugin::convert_bit_depth_code(u8 bit_depth_code)
  509. {
  510. switch (bit_depth_code) {
  511. case 0:
  512. return m_bits_per_sample;
  513. case 1:
  514. return 8;
  515. case 2:
  516. return 12;
  517. case 3:
  518. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved sample size" };
  519. case 4:
  520. return 16;
  521. case 5:
  522. return 20;
  523. case 6:
  524. return 24;
  525. case 7:
  526. return 32;
  527. default:
  528. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), DeprecatedString::formatted("Unsupported sample size {}", bit_depth_code) };
  529. }
  530. }
  531. // 11.22.5. CHANNEL ASSIGNMENT
  532. u8 frame_channel_type_to_channel_count(FlacFrameChannelType channel_type)
  533. {
  534. if (channel_type <= FlacFrameChannelType::Surround7p1)
  535. return to_underlying(channel_type) + 1;
  536. return 2;
  537. }
  538. // 11.25. SUBFRAME_HEADER
  539. ErrorOr<FlacSubframeHeader, LoaderError> FlacLoaderPlugin::next_subframe_header(BigEndianInputBitStream& bit_stream, u8 channel_index)
  540. {
  541. u8 bits_per_sample = m_current_frame->bit_depth;
  542. // For inter-channel correlation, the side channel needs an extra bit for its samples
  543. switch (m_current_frame->channels) {
  544. case FlacFrameChannelType::LeftSideStereo:
  545. case FlacFrameChannelType::MidSideStereo:
  546. if (channel_index == 1) {
  547. ++bits_per_sample;
  548. }
  549. break;
  550. case FlacFrameChannelType::RightSideStereo:
  551. if (channel_index == 0) {
  552. ++bits_per_sample;
  553. }
  554. break;
  555. // "normal" channel types
  556. default:
  557. break;
  558. }
  559. // zero-bit padding
  560. if (TRY(bit_stream.read_bit()) != 0)
  561. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Zero bit padding" };
  562. // 11.25.1. SUBFRAME TYPE
  563. u8 subframe_code = TRY(bit_stream.read_bits<u8>(6));
  564. if ((subframe_code >= 0b000010 && subframe_code <= 0b000111) || (subframe_code > 0b001100 && subframe_code < 0b100000))
  565. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Subframe type" };
  566. FlacSubframeType subframe_type;
  567. u8 order = 0;
  568. // LPC has the highest bit set
  569. if ((subframe_code & 0b100000) > 0) {
  570. subframe_type = FlacSubframeType::LPC;
  571. order = (subframe_code & 0b011111) + 1;
  572. } else if ((subframe_code & 0b001000) > 0) {
  573. // Fixed has the third-highest bit set
  574. subframe_type = FlacSubframeType::Fixed;
  575. order = (subframe_code & 0b000111);
  576. } else {
  577. subframe_type = (FlacSubframeType)subframe_code;
  578. }
  579. // 11.25.2. WASTED BITS PER SAMPLE FLAG
  580. bool has_wasted_bits = TRY(bit_stream.read_bit());
  581. u8 k = 0;
  582. if (has_wasted_bits) {
  583. bool current_k_bit = 0;
  584. do {
  585. current_k_bit = TRY(bit_stream.read_bit());
  586. ++k;
  587. } while (current_k_bit != 1);
  588. }
  589. return FlacSubframeHeader {
  590. subframe_type,
  591. order,
  592. k,
  593. bits_per_sample
  594. };
  595. }
  596. ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::parse_subframe(FlacSubframeHeader& subframe_header, BigEndianInputBitStream& bit_input)
  597. {
  598. Vector<i64> samples;
  599. switch (subframe_header.type) {
  600. case FlacSubframeType::Constant: {
  601. // 11.26. SUBFRAME_CONSTANT
  602. u64 constant_value = TRY(bit_input.read_bits<u64>(subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample));
  603. dbgln_if(AFLACLOADER_DEBUG, "Constant subframe: {}", constant_value);
  604. samples.ensure_capacity(m_current_frame->sample_count);
  605. VERIFY(subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample != 0);
  606. i64 constant = sign_extend(static_cast<u64>(constant_value), subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample);
  607. for (u64 i = 0; i < m_current_frame->sample_count; ++i) {
  608. samples.unchecked_append(constant);
  609. }
  610. break;
  611. }
  612. case FlacSubframeType::Fixed: {
  613. dbgln_if(AFLACLOADER_DEBUG, "Fixed LPC subframe order {}", subframe_header.order);
  614. samples = TRY(decode_fixed_lpc(subframe_header, bit_input));
  615. break;
  616. }
  617. case FlacSubframeType::Verbatim: {
  618. dbgln_if(AFLACLOADER_DEBUG, "Verbatim subframe");
  619. samples = TRY(decode_verbatim(subframe_header, bit_input));
  620. break;
  621. }
  622. case FlacSubframeType::LPC: {
  623. dbgln_if(AFLACLOADER_DEBUG, "Custom LPC subframe order {}", subframe_header.order);
  624. samples = TRY(decode_custom_lpc(subframe_header, bit_input));
  625. break;
  626. }
  627. default:
  628. return LoaderError { LoaderError::Category::Unimplemented, static_cast<size_t>(m_current_sample_or_frame), "Unhandled FLAC subframe type" };
  629. }
  630. for (size_t i = 0; i < samples.size(); ++i) {
  631. samples[i] <<= subframe_header.wasted_bits_per_sample;
  632. }
  633. // Resamplers VERIFY that the sample rate is non-zero.
  634. if (m_current_frame->sample_rate == 0 || m_sample_rate == 0)
  635. return samples;
  636. ResampleHelper<i64> resampler(m_current_frame->sample_rate, m_sample_rate);
  637. return resampler.resample(samples);
  638. }
  639. // 11.29. SUBFRAME_VERBATIM
  640. // Decode a subframe that isn't actually encoded, usually seen in random data
  641. ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::decode_verbatim(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  642. {
  643. Vector<i64> decoded;
  644. decoded.ensure_capacity(m_current_frame->sample_count);
  645. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  646. for (size_t i = 0; i < m_current_frame->sample_count; ++i) {
  647. decoded.unchecked_append(sign_extend(
  648. TRY(bit_input.read_bits<u64>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  649. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  650. }
  651. return decoded;
  652. }
  653. // 11.28. SUBFRAME_LPC
  654. // Decode a subframe encoded with a custom linear predictor coding, i.e. the subframe provides the polynomial order and coefficients
  655. ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::decode_custom_lpc(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  656. {
  657. // LPC must provide at least as many samples as its order.
  658. if (subframe.order > m_current_frame->sample_count)
  659. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Too small frame for LPC order" };
  660. Vector<i64> decoded;
  661. decoded.ensure_capacity(m_current_frame->sample_count);
  662. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  663. // warm-up samples
  664. for (auto i = 0; i < subframe.order; ++i) {
  665. decoded.unchecked_append(sign_extend(
  666. TRY(bit_input.read_bits<u64>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  667. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  668. }
  669. // precision of the coefficients
  670. u8 lpc_precision = TRY(bit_input.read_bits<u8>(4));
  671. if (lpc_precision == 0b1111)
  672. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Invalid linear predictor coefficient precision" };
  673. lpc_precision += 1;
  674. // shift needed on the data (signed!)
  675. i8 lpc_shift = static_cast<i8>(sign_extend(TRY(bit_input.read_bits<u8>(5)), 5));
  676. Vector<i64> coefficients;
  677. coefficients.ensure_capacity(subframe.order);
  678. // read coefficients
  679. for (auto i = 0; i < subframe.order; ++i) {
  680. u64 raw_coefficient = TRY(bit_input.read_bits<u64>(lpc_precision));
  681. i64 coefficient = sign_extend(raw_coefficient, lpc_precision);
  682. coefficients.unchecked_append(coefficient);
  683. }
  684. dbgln_if(AFLACLOADER_DEBUG, "{}-bit {} shift coefficients: {}", lpc_precision, lpc_shift, coefficients);
  685. TRY(decode_residual(decoded, subframe, bit_input));
  686. // approximate the waveform with the predictor
  687. for (size_t i = subframe.order; i < m_current_frame->sample_count; ++i) {
  688. // (see below)
  689. i64 sample = 0;
  690. for (size_t t = 0; t < subframe.order; ++t) {
  691. // It's really important that we compute in 64-bit land here.
  692. // Even though FLAC operates at a maximum bit depth of 32 bits, modern encoders use super-large coefficients for maximum compression.
  693. // These will easily overflow 32 bits and cause strange white noise that abruptly stops intermittently (at the end of a frame).
  694. // The simple fix of course is to do intermediate computations in 64 bits.
  695. // These considerations are not in the original FLAC spec, but have been added to the IETF standard: https://datatracker.ietf.org/doc/html/draft-ietf-cellar-flac-03#appendix-A.3
  696. sample += static_cast<i64>(coefficients[t]) * static_cast<i64>(decoded[i - t - 1]);
  697. }
  698. decoded[i] += sample >> lpc_shift;
  699. }
  700. return decoded;
  701. }
  702. // 11.27. SUBFRAME_FIXED
  703. // Decode a subframe encoded with one of the fixed linear predictor codings
  704. ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::decode_fixed_lpc(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  705. {
  706. // LPC must provide at least as many samples as its order.
  707. if (subframe.order > m_current_frame->sample_count)
  708. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Too small frame for LPC order" };
  709. Vector<i64> decoded;
  710. decoded.ensure_capacity(m_current_frame->sample_count);
  711. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  712. // warm-up samples
  713. for (auto i = 0; i < subframe.order; ++i) {
  714. decoded.unchecked_append(sign_extend(
  715. TRY(bit_input.read_bits<u64>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  716. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  717. }
  718. TRY(decode_residual(decoded, subframe, bit_input));
  719. dbgln_if(AFLACLOADER_DEBUG, "decoded length {}, {} order predictor", decoded.size(), subframe.order);
  720. // Skip these comments if you don't care about the neat math behind fixed LPC :^)
  721. // These coefficients for the recursive prediction formula are the only ones that can be resolved to polynomial predictor functions.
  722. // The order equals the degree of the polynomial - 1, so the second-order predictor has an underlying polynomial of degree 1, a straight line.
  723. // More specifically, the closest approximation to a polynomial is used, and the degree depends on how many previous values are available.
  724. // This makes use of a very neat property of polynomials, which is that they are entirely characterized by their finitely many derivatives.
  725. // (Mathematically speaking, the infinite Taylor series of any polynomial equals the polynomial itself.)
  726. // Now remember that derivation is just the slope of the function, which is the same as the difference of two close-by values.
  727. // Therefore, with two samples we can calculate the first derivative at a sample via the difference, which gives us a polynomial of degree 1.
  728. // With three samples, we can do the same but also calculate the second derivative via the difference in the first derivatives.
  729. // This gives us a polynomial of degree 2, as it has two "proper" (non-constant) derivatives.
  730. // This can be continued for higher-order derivatives when we have more coefficients, giving us higher-order polynomials.
  731. // In essence, it's akin to a Lagrangian polynomial interpolation for every sample (but already pre-solved).
  732. // The coefficients for orders 0-3 originate from the SHORTEN codec:
  733. // http://mi.eng.cam.ac.uk/reports/svr-ftp/auto-pdf/robinson_tr156.pdf page 4
  734. // The coefficients for order 4 are undocumented in the original FLAC specification(s), but can now be found in
  735. // https://datatracker.ietf.org/doc/html/draft-ietf-cellar-flac-03#section-10.2.5
  736. switch (subframe.order) {
  737. case 0:
  738. // s_0(t) = 0
  739. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  740. decoded[i] += 0;
  741. break;
  742. case 1:
  743. // s_1(t) = s(t-1)
  744. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  745. decoded[i] += decoded[i - 1];
  746. break;
  747. case 2:
  748. // s_2(t) = 2s(t-1) - s(t-2)
  749. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  750. decoded[i] += 2 * decoded[i - 1] - decoded[i - 2];
  751. break;
  752. case 3:
  753. // s_3(t) = 3s(t-1) - 3s(t-2) + s(t-3)
  754. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  755. decoded[i] += 3 * decoded[i - 1] - 3 * decoded[i - 2] + decoded[i - 3];
  756. break;
  757. case 4:
  758. // s_4(t) = 4s(t-1) - 6s(t-2) + 4s(t-3) - s(t-4)
  759. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  760. decoded[i] += 4 * decoded[i - 1] - 6 * decoded[i - 2] + 4 * decoded[i - 3] - decoded[i - 4];
  761. break;
  762. default:
  763. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), DeprecatedString::formatted("Unrecognized predictor order {}", subframe.order) };
  764. }
  765. return decoded;
  766. }
  767. // 11.30. RESIDUAL
  768. // Decode the residual, the "error" between the function approximation and the actual audio data
  769. MaybeLoaderError FlacLoaderPlugin::decode_residual(Vector<i64>& decoded, FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  770. {
  771. // 11.30.1. RESIDUAL_CODING_METHOD
  772. auto residual_mode = static_cast<FlacResidualMode>(TRY(bit_input.read_bits<u8>(2)));
  773. u8 partition_order = TRY(bit_input.read_bits<u8>(4));
  774. size_t partitions = 1 << partition_order;
  775. if (partitions > m_current_frame->sample_count)
  776. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Too many Rice partitions, each partition must contain at least one sample" };
  777. if (residual_mode == FlacResidualMode::Rice4Bit) {
  778. // 11.30.2. RESIDUAL_CODING_METHOD_PARTITIONED_EXP_GOLOMB
  779. // decode a single Rice partition with four bits for the order k
  780. for (size_t i = 0; i < partitions; ++i) {
  781. auto rice_partition = TRY(decode_rice_partition(4, partitions, i, subframe, bit_input));
  782. decoded.extend(move(rice_partition));
  783. }
  784. } else if (residual_mode == FlacResidualMode::Rice5Bit) {
  785. // 11.30.3. RESIDUAL_CODING_METHOD_PARTITIONED_EXP_GOLOMB2
  786. // five bits equivalent
  787. for (size_t i = 0; i < partitions; ++i) {
  788. auto rice_partition = TRY(decode_rice_partition(5, partitions, i, subframe, bit_input));
  789. decoded.extend(move(rice_partition));
  790. }
  791. } else
  792. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved residual coding method" };
  793. return {};
  794. }
  795. // 11.30.2.1. EXP_GOLOMB_PARTITION and 11.30.3.1. EXP_GOLOMB2_PARTITION
  796. // Decode a single Rice partition as part of the residual, every partition can have its own Rice parameter k
  797. ALWAYS_INLINE ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::decode_rice_partition(u8 partition_type, u32 partitions, u32 partition_index, FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  798. {
  799. // 11.30.2.2. EXP GOLOMB PARTITION ENCODING PARAMETER and 11.30.3.2. EXP-GOLOMB2 PARTITION ENCODING PARAMETER
  800. u8 k = TRY(bit_input.read_bits<u8>(partition_type));
  801. u32 residual_sample_count;
  802. if (partitions == 0)
  803. residual_sample_count = m_current_frame->sample_count - subframe.order;
  804. else
  805. residual_sample_count = m_current_frame->sample_count / partitions;
  806. if (partition_index == 0) {
  807. if (subframe.order > residual_sample_count)
  808. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "First Rice partition must advertise more residuals than LPC order" };
  809. residual_sample_count -= subframe.order;
  810. }
  811. Vector<i64> rice_partition;
  812. rice_partition.resize(residual_sample_count);
  813. // escape code for unencoded binary partition
  814. if (k == (1 << partition_type) - 1) {
  815. u8 unencoded_bps = TRY(bit_input.read_bits<u8>(5));
  816. for (size_t r = 0; r < residual_sample_count; ++r) {
  817. rice_partition[r] = sign_extend(TRY(bit_input.read_bits<u32>(unencoded_bps)), unencoded_bps);
  818. }
  819. } else {
  820. for (size_t r = 0; r < residual_sample_count; ++r) {
  821. rice_partition[r] = TRY(decode_unsigned_exp_golomb(k, bit_input));
  822. }
  823. }
  824. return rice_partition;
  825. }
  826. // Decode a single number encoded with Rice/Exponential-Golomb encoding (the unsigned variant)
  827. ALWAYS_INLINE ErrorOr<i32> decode_unsigned_exp_golomb(u8 k, BigEndianInputBitStream& bit_input)
  828. {
  829. u8 q = 0;
  830. while (TRY(bit_input.read_bit()) == 0)
  831. ++q;
  832. // least significant bits (remainder)
  833. u32 rem = TRY(bit_input.read_bits<u32>(k));
  834. u32 value = q << k | rem;
  835. return rice_to_signed(value);
  836. }
  837. ErrorOr<u64> read_utf8_char(BigEndianInputBitStream& input)
  838. {
  839. u64 character;
  840. u8 start_byte = TRY(input.read_value<u8>());
  841. // Signal byte is zero: ASCII character
  842. if ((start_byte & 0b10000000) == 0) {
  843. return start_byte;
  844. } else if ((start_byte & 0b11000000) == 0b10000000) {
  845. return Error::from_string_literal("Illegal continuation byte");
  846. }
  847. // This algorithm supports the theoretical max 0xFF start byte, which is not part of the regular UTF-8 spec.
  848. u8 length = 1;
  849. while (((start_byte << length) & 0b10000000) == 0b10000000)
  850. ++length;
  851. // This is technically not spec-compliant, but if we take UTF-8 to its logical extreme,
  852. // we can say 0xFF means there's 7 following continuation bytes and no data at all in the leading character.
  853. if (length == 8) [[unlikely]] {
  854. character = 0;
  855. } else {
  856. u8 bits_from_start_byte = 8 - (length + 1);
  857. u8 start_byte_bitmask = AK::exp2(bits_from_start_byte) - 1;
  858. character = start_byte_bitmask & start_byte;
  859. }
  860. for (u8 i = length - 1; i > 0; --i) {
  861. u8 current_byte = TRY(input.read_value<u8>());
  862. character = (character << 6) | (current_byte & 0b00111111);
  863. }
  864. return character;
  865. }
  866. i64 sign_extend(u32 n, u8 size)
  867. {
  868. // negative
  869. if ((n & (1 << (size - 1))) > 0) {
  870. return static_cast<i64>(n | (0xffffffffffffffffLL << size));
  871. }
  872. // positive
  873. return n;
  874. }
  875. i32 rice_to_signed(u32 x)
  876. {
  877. // positive numbers are even, negative numbers are odd
  878. // bitmask for conditionally inverting the entire number, thereby "negating" it
  879. i32 sign = -static_cast<i32>(x & 1);
  880. // copies the sign's sign onto the actual magnitude of x
  881. return static_cast<i32>(sign ^ (x >> 1));
  882. }
  883. }