FlacLoader.cpp 44 KB

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