FlacLoader.cpp 45 KB

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