FlacLoader.cpp 39 KB

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