FlacLoader.cpp 40 KB

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