FlacLoader.cpp 41 KB

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