FlacLoader.cpp 41 KB

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