FlacLoader.cpp 39 KB

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