FlacLoader.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/FixedArray.h>
  8. #include <AK/FlyString.h>
  9. #include <AK/Format.h>
  10. #include <AK/IntegralMath.h>
  11. #include <AK/Math.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/StdLibExtras.h>
  14. #include <AK/String.h>
  15. #include <AK/StringBuilder.h>
  16. #include <AK/Try.h>
  17. #include <AK/TypedTransfer.h>
  18. #include <AK/UFixedBigInt.h>
  19. #include <LibAudio/Buffer.h>
  20. #include <LibAudio/FlacLoader.h>
  21. #include <LibAudio/FlacTypes.h>
  22. #include <LibAudio/LoaderError.h>
  23. #include <LibCore/MemoryStream.h>
  24. #include <LibCore/Stream.h>
  25. namespace Audio {
  26. FlacLoaderPlugin::FlacLoaderPlugin(StringView path)
  27. : m_file(Core::File::construct(path))
  28. {
  29. if (!m_file->open(Core::OpenMode::ReadOnly)) {
  30. m_error = LoaderError { String::formatted("Can't open file: {}", m_file->error_string()) };
  31. return;
  32. }
  33. auto maybe_stream = Core::Stream::BufferedFile::create(MUST(Core::Stream::File::open(path, Core::Stream::OpenMode::Read)), FLAC_BUFFER_SIZE);
  34. if (maybe_stream.is_error())
  35. m_error = LoaderError { "Can't open file stream" };
  36. else
  37. m_stream = maybe_stream.release_value();
  38. }
  39. FlacLoaderPlugin::FlacLoaderPlugin(Bytes& buffer)
  40. {
  41. auto maybe_stream = Core::Stream::MemoryStream::construct(buffer);
  42. if (maybe_stream.is_error())
  43. m_error = LoaderError { "Can't open memory stream" };
  44. else
  45. m_stream = maybe_stream.release_value();
  46. }
  47. MaybeLoaderError FlacLoaderPlugin::initialize()
  48. {
  49. if (m_error.has_value())
  50. return m_error.release_value();
  51. TRY(parse_header());
  52. TRY(reset());
  53. return {};
  54. }
  55. MaybeLoaderError FlacLoaderPlugin::parse_header()
  56. {
  57. auto bit_input = LOADER_TRY(BigEndianInputBitStream::construct(*m_stream));
  58. // A mixture of VERIFY and the non-crashing TRY().
  59. #define FLAC_VERIFY(check, category, msg) \
  60. do { \
  61. if (!(check)) { \
  62. return LoaderError { category, static_cast<size_t>(m_data_start_location), String::formatted("FLAC header: {}", msg) }; \
  63. } \
  64. } while (0)
  65. // Magic number
  66. u32 flac = LOADER_TRY(bit_input->read_bits<u32>(32));
  67. m_data_start_location += 4;
  68. FLAC_VERIFY(flac == 0x664C6143, LoaderError::Category::Format, "Magic number must be 'flaC'"); // "flaC"
  69. // Receive the streaminfo block
  70. auto streaminfo = TRY(next_meta_block(*bit_input));
  71. FLAC_VERIFY(streaminfo.type == FlacMetadataBlockType::STREAMINFO, LoaderError::Category::Format, "First block must be STREAMINFO");
  72. auto streaminfo_data_memory = LOADER_TRY(Core::Stream::MemoryStream::construct(streaminfo.data.bytes()));
  73. auto streaminfo_data = LOADER_TRY(BigEndianInputBitStream::construct(*streaminfo_data_memory));
  74. // STREAMINFO block
  75. m_min_block_size = LOADER_TRY(streaminfo_data->read_bits<u16>(16));
  76. FLAC_VERIFY(m_min_block_size >= 16, LoaderError::Category::Format, "Minimum block size must be 16");
  77. m_max_block_size = LOADER_TRY(streaminfo_data->read_bits<u16>(16));
  78. FLAC_VERIFY(m_max_block_size >= 16, LoaderError::Category::Format, "Maximum block size");
  79. m_min_frame_size = LOADER_TRY(streaminfo_data->read_bits<u32>(24));
  80. m_max_frame_size = LOADER_TRY(streaminfo_data->read_bits<u32>(24));
  81. m_sample_rate = LOADER_TRY(streaminfo_data->read_bits<u32>(20));
  82. FLAC_VERIFY(m_sample_rate <= 655350, LoaderError::Category::Format, "Sample rate");
  83. m_num_channels = LOADER_TRY(streaminfo_data->read_bits<u8>(3)) + 1; // 0 = one channel
  84. u8 bits_per_sample = LOADER_TRY(streaminfo_data->read_bits<u8>(5)) + 1;
  85. if (bits_per_sample == 8) {
  86. // FIXME: Signed/Unsigned issues?
  87. m_sample_format = PcmSampleFormat::Uint8;
  88. } else if (bits_per_sample == 16) {
  89. m_sample_format = PcmSampleFormat::Int16;
  90. } else if (bits_per_sample == 24) {
  91. m_sample_format = PcmSampleFormat::Int24;
  92. } else if (bits_per_sample == 32) {
  93. m_sample_format = PcmSampleFormat::Int32;
  94. } else {
  95. FLAC_VERIFY(false, LoaderError::Category::Format, "Sample bit depth invalid");
  96. }
  97. m_total_samples = LOADER_TRY(streaminfo_data->read_bits<u64>(36));
  98. FLAC_VERIFY(m_total_samples > 0, LoaderError::Category::Format, "Number of samples is zero");
  99. // Parse checksum into a buffer first
  100. [[maybe_unused]] u128 md5_checksum;
  101. VERIFY(streaminfo_data->is_aligned_to_byte_boundary());
  102. auto md5_bytes_read = LOADER_TRY(streaminfo_data->read(md5_checksum.bytes()));
  103. FLAC_VERIFY(md5_bytes_read.size() == md5_checksum.my_size(), LoaderError::Category::IO, "MD5 Checksum size");
  104. md5_checksum.bytes().copy_to({ m_md5_checksum, sizeof(m_md5_checksum) });
  105. // Parse other blocks
  106. [[maybe_unused]] u16 meta_blocks_parsed = 1;
  107. [[maybe_unused]] u16 total_meta_blocks = meta_blocks_parsed;
  108. FlacRawMetadataBlock block = streaminfo;
  109. while (!block.is_last_block) {
  110. block = TRY(next_meta_block(*bit_input));
  111. switch (block.type) {
  112. case (FlacMetadataBlockType::SEEKTABLE):
  113. TRY(load_seektable(block));
  114. break;
  115. default:
  116. // TODO: Parse the remaining metadata block types.
  117. // Currently only STREAMINFO and SEEKTABLE are handled.
  118. break;
  119. }
  120. ++total_meta_blocks;
  121. }
  122. 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<double>(m_total_samples) / static_cast<double>(m_sample_rate), md5_checksum, m_data_start_location, total_meta_blocks, total_meta_blocks - meta_blocks_parsed);
  123. return {};
  124. }
  125. MaybeLoaderError FlacLoaderPlugin::load_seektable(FlacRawMetadataBlock& block)
  126. {
  127. auto memory_stream = LOADER_TRY(Core::Stream::MemoryStream::construct(block.data.bytes()));
  128. auto seektable_bytes = LOADER_TRY(BigEndianInputBitStream::construct(*memory_stream));
  129. for (size_t i = 0; i < block.length / 18; ++i) {
  130. FlacSeekPoint seekpoint {
  131. .sample_index = LOADER_TRY(seektable_bytes->read_bits<u64>(64)),
  132. .byte_offset = LOADER_TRY(seektable_bytes->read_bits<u64>(64)),
  133. .num_samples = LOADER_TRY(seektable_bytes->read_bits<u16>(16))
  134. };
  135. m_seektable.append(seekpoint);
  136. }
  137. dbgln_if(AFLACLOADER_DEBUG, "Loaded seektable of size {}", m_seektable.size());
  138. return {};
  139. }
  140. ErrorOr<FlacRawMetadataBlock, LoaderError> FlacLoaderPlugin::next_meta_block(BigEndianInputBitStream& bit_input)
  141. {
  142. bool is_last_block = LOADER_TRY(bit_input.read_bit());
  143. // The block type enum constants agree with the specification
  144. FlacMetadataBlockType type = (FlacMetadataBlockType)LOADER_TRY(bit_input.read_bits<u8>(7));
  145. m_data_start_location += 1;
  146. FLAC_VERIFY(type != FlacMetadataBlockType::INVALID, LoaderError::Category::Format, "Invalid metadata block");
  147. u32 block_length = LOADER_TRY(bit_input.read_bits<u32>(24));
  148. m_data_start_location += 3;
  149. // Blocks can be zero-sized, which would trip up the raw data reader below.
  150. if (block_length == 0)
  151. return FlacRawMetadataBlock {
  152. .is_last_block = is_last_block,
  153. .type = type,
  154. .length = 0,
  155. .data = LOADER_TRY(ByteBuffer::create_uninitialized(0))
  156. };
  157. auto block_data_result = ByteBuffer::create_uninitialized(block_length);
  158. FLAC_VERIFY(!block_data_result.is_error(), LoaderError::Category::IO, "Out of memory");
  159. auto block_data = block_data_result.release_value();
  160. // Reads exactly the bytes necessary into the Bytes container
  161. LOADER_TRY(bit_input.read(block_data));
  162. m_data_start_location += block_length;
  163. return FlacRawMetadataBlock {
  164. is_last_block,
  165. type,
  166. block_length,
  167. block_data,
  168. };
  169. }
  170. #undef FLAC_VERIFY
  171. MaybeLoaderError FlacLoaderPlugin::reset()
  172. {
  173. TRY(seek(m_data_start_location));
  174. m_current_frame.clear();
  175. return {};
  176. }
  177. MaybeLoaderError FlacLoaderPlugin::seek(int int_sample_index)
  178. {
  179. auto sample_index = static_cast<size_t>(int_sample_index);
  180. if (sample_index == m_loaded_samples)
  181. return {};
  182. auto maybe_target_seekpoint = m_seektable.last_matching([sample_index](auto& seekpoint) { return seekpoint.sample_index <= sample_index; });
  183. // No seektable or no fitting entry: Perform normal forward read
  184. if (!maybe_target_seekpoint.has_value()) {
  185. if (sample_index < m_loaded_samples) {
  186. LOADER_TRY(m_stream->seek(m_data_start_location, Core::Stream::SeekMode::SetPosition));
  187. m_loaded_samples = 0;
  188. }
  189. auto to_read = sample_index - m_loaded_samples;
  190. if (to_read == 0)
  191. return {};
  192. dbgln_if(AFLACLOADER_DEBUG, "Seeking {} samples manually", to_read);
  193. (void)TRY(get_more_samples(to_read));
  194. } else {
  195. auto target_seekpoint = maybe_target_seekpoint.release_value();
  196. // When a small seek happens, we may already be closer to the target than the seekpoint.
  197. if (sample_index - target_seekpoint.sample_index > sample_index - m_loaded_samples) {
  198. dbgln_if(AFLACLOADER_DEBUG, "Close enough to target: seeking {} samples manually", sample_index - m_loaded_samples);
  199. (void)TRY(get_more_samples(sample_index - m_loaded_samples));
  200. return {};
  201. }
  202. dbgln_if(AFLACLOADER_DEBUG, "Seeking to seektable: sample index {}, byte offset {}, sample count {}", target_seekpoint.sample_index, target_seekpoint.byte_offset, target_seekpoint.num_samples);
  203. auto position = target_seekpoint.byte_offset + m_data_start_location;
  204. if (m_stream->seek(static_cast<i64>(position), Core::Stream::SeekMode::SetPosition).is_error())
  205. return LoaderError { LoaderError::Category::IO, m_loaded_samples, String::formatted("Invalid seek position {}", position) };
  206. auto remaining_samples_after_seekpoint = sample_index - m_data_start_location;
  207. if (remaining_samples_after_seekpoint > 0)
  208. (void)TRY(get_more_samples(remaining_samples_after_seekpoint));
  209. m_loaded_samples = target_seekpoint.sample_index;
  210. }
  211. return {};
  212. }
  213. LoaderSamples FlacLoaderPlugin::get_more_samples(size_t max_bytes_to_read_from_input)
  214. {
  215. ssize_t remaining_samples = static_cast<ssize_t>(m_total_samples - m_loaded_samples);
  216. if (remaining_samples <= 0)
  217. return FixedArray<Sample> {};
  218. // FIXME: samples_to_read is calculated wrong, because when seeking not all samples are loaded.
  219. size_t samples_to_read = min(max_bytes_to_read_from_input, remaining_samples);
  220. auto samples = FixedArray<Sample>::must_create_but_fixme_should_propagate_errors(samples_to_read);
  221. size_t sample_index = 0;
  222. if (m_unread_data.size() > 0) {
  223. size_t to_transfer = min(m_unread_data.size(), samples_to_read);
  224. dbgln_if(AFLACLOADER_DEBUG, "Reading {} samples from unread sample buffer (size {})", to_transfer, m_unread_data.size());
  225. AK::TypedTransfer<Sample>::move(samples.data(), m_unread_data.data(), to_transfer);
  226. if (to_transfer < m_unread_data.size())
  227. m_unread_data.remove(0, to_transfer);
  228. else
  229. m_unread_data.clear_with_capacity();
  230. sample_index += to_transfer;
  231. }
  232. while (sample_index < samples_to_read) {
  233. TRY(next_frame(samples.span().slice(sample_index)));
  234. sample_index += m_current_frame->sample_count;
  235. }
  236. m_loaded_samples += sample_index;
  237. return samples;
  238. }
  239. MaybeLoaderError FlacLoaderPlugin::next_frame(Span<Sample> target_vector)
  240. {
  241. #define FLAC_VERIFY(check, category, msg) \
  242. do { \
  243. if (!(check)) { \
  244. return LoaderError { category, static_cast<size_t>(m_current_sample_or_frame), String::formatted("FLAC header: {}", msg) }; \
  245. } \
  246. } while (0)
  247. auto bit_stream = LOADER_TRY(BigEndianInputBitStream::construct(*m_stream));
  248. // TODO: Check the CRC-16 checksum (and others) by keeping track of read data
  249. // FLAC frame sync code starts header
  250. u16 sync_code = LOADER_TRY(bit_stream->read_bits<u16>(14));
  251. FLAC_VERIFY(sync_code == 0b11111111111110, LoaderError::Category::Format, "Sync code");
  252. bool reserved_bit = LOADER_TRY(bit_stream->read_bit());
  253. FLAC_VERIFY(reserved_bit == 0, LoaderError::Category::Format, "Reserved frame header bit");
  254. [[maybe_unused]] bool blocking_strategy = LOADER_TRY(bit_stream->read_bit());
  255. u32 sample_count = TRY(convert_sample_count_code(LOADER_TRY(bit_stream->read_bits<u8>(4))));
  256. u32 frame_sample_rate = TRY(convert_sample_rate_code(LOADER_TRY(bit_stream->read_bits<u8>(4))));
  257. u8 channel_type_num = LOADER_TRY(bit_stream->read_bits<u8>(4));
  258. FLAC_VERIFY(channel_type_num < 0b1011, LoaderError::Category::Format, "Channel assignment");
  259. FlacFrameChannelType channel_type = (FlacFrameChannelType)channel_type_num;
  260. PcmSampleFormat bit_depth = TRY(convert_bit_depth_code(LOADER_TRY(bit_stream->read_bits<u8>(3))));
  261. reserved_bit = LOADER_TRY(bit_stream->read_bit());
  262. FLAC_VERIFY(reserved_bit == 0, LoaderError::Category::Format, "Reserved frame header end bit");
  263. // FIXME: sample number can be 8-56 bits, frame number can be 8-48 bits
  264. m_current_sample_or_frame = LOADER_TRY(read_utf8_char(*bit_stream));
  265. // Conditional header variables
  266. if (sample_count == FLAC_BLOCKSIZE_AT_END_OF_HEADER_8) {
  267. sample_count = LOADER_TRY(bit_stream->read_bits<u32>(8)) + 1;
  268. } else if (sample_count == FLAC_BLOCKSIZE_AT_END_OF_HEADER_16) {
  269. sample_count = LOADER_TRY(bit_stream->read_bits<u32>(16)) + 1;
  270. }
  271. if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_8) {
  272. frame_sample_rate = LOADER_TRY(bit_stream->read_bits<u32>(8)) * 1000;
  273. } else if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_16) {
  274. frame_sample_rate = LOADER_TRY(bit_stream->read_bits<u32>(16));
  275. } else if (frame_sample_rate == FLAC_SAMPLERATE_AT_END_OF_HEADER_16X10) {
  276. frame_sample_rate = LOADER_TRY(bit_stream->read_bits<u32>(16)) * 10;
  277. }
  278. // TODO: check header checksum, see above
  279. [[maybe_unused]] u8 checksum = LOADER_TRY(bit_stream->read_bits<u8>(8));
  280. dbgln_if(AFLACLOADER_DEBUG, "Frame: {} samples, {}bit {}Hz, channeltype {:x}, {} number {}, header checksum {}", sample_count, pcm_bits_per_sample(bit_depth), frame_sample_rate, channel_type_num, blocking_strategy ? "sample" : "frame", m_current_sample_or_frame, checksum);
  281. m_current_frame = FlacFrameHeader {
  282. sample_count,
  283. frame_sample_rate,
  284. channel_type,
  285. bit_depth,
  286. };
  287. u8 subframe_count = frame_channel_type_to_channel_count(channel_type);
  288. Vector<Vector<i32>> current_subframes;
  289. current_subframes.ensure_capacity(subframe_count);
  290. for (u8 i = 0; i < subframe_count; ++i) {
  291. FlacSubframeHeader new_subframe = TRY(next_subframe_header(*bit_stream, i));
  292. Vector<i32> subframe_samples = TRY(parse_subframe(new_subframe, *bit_stream));
  293. current_subframes.unchecked_append(move(subframe_samples));
  294. }
  295. bit_stream->align_to_byte_boundary();
  296. // TODO: check checksum, see above
  297. [[maybe_unused]] u16 footer_checksum = LOADER_TRY(bit_stream->read_bits<u16>(16));
  298. dbgln_if(AFLACLOADER_DEBUG, "Subframe footer checksum: {}", footer_checksum);
  299. Vector<i32> left;
  300. Vector<i32> right;
  301. switch (channel_type) {
  302. case FlacFrameChannelType::Mono:
  303. left = right = current_subframes[0];
  304. break;
  305. case FlacFrameChannelType::Stereo:
  306. // TODO mix together surround channels on each side?
  307. case FlacFrameChannelType::StereoCenter:
  308. case FlacFrameChannelType::Surround4p0:
  309. case FlacFrameChannelType::Surround5p0:
  310. case FlacFrameChannelType::Surround5p1:
  311. case FlacFrameChannelType::Surround6p1:
  312. case FlacFrameChannelType::Surround7p1:
  313. left = current_subframes[0];
  314. right = current_subframes[1];
  315. break;
  316. case FlacFrameChannelType::LeftSideStereo:
  317. // channels are left (0) and side (1)
  318. left = current_subframes[0];
  319. right.ensure_capacity(left.size());
  320. for (size_t i = 0; i < left.size(); ++i) {
  321. // right = left - side
  322. right.unchecked_append(left[i] - current_subframes[1][i]);
  323. }
  324. break;
  325. case FlacFrameChannelType::RightSideStereo:
  326. // channels are side (0) and right (1)
  327. right = current_subframes[1];
  328. left.ensure_capacity(right.size());
  329. for (size_t i = 0; i < right.size(); ++i) {
  330. // left = right + side
  331. left.unchecked_append(right[i] + current_subframes[0][i]);
  332. }
  333. break;
  334. case FlacFrameChannelType::MidSideStereo:
  335. // channels are mid (0) and side (1)
  336. left.ensure_capacity(current_subframes[0].size());
  337. right.ensure_capacity(current_subframes[0].size());
  338. for (size_t i = 0; i < current_subframes[0].size(); ++i) {
  339. i64 mid = current_subframes[0][i];
  340. i64 side = current_subframes[1][i];
  341. mid *= 2;
  342. // prevent integer division errors
  343. left.unchecked_append(static_cast<i32>((mid + side) / 2));
  344. right.unchecked_append(static_cast<i32>((mid - side) / 2));
  345. }
  346. break;
  347. }
  348. VERIFY(left.size() == right.size() && left.size() == m_current_frame->sample_count);
  349. double sample_rescale = static_cast<double>(1 << (pcm_bits_per_sample(m_current_frame->bit_depth) - 1));
  350. dbgln_if(AFLACLOADER_DEBUG, "Sample rescaled from {} bits: factor {:.1f}", pcm_bits_per_sample(m_current_frame->bit_depth), sample_rescale);
  351. // zip together channels
  352. auto samples_to_directly_copy = min(target_vector.size(), m_current_frame->sample_count);
  353. for (size_t i = 0; i < samples_to_directly_copy; ++i) {
  354. Sample frame = { left[i] / sample_rescale, right[i] / sample_rescale };
  355. target_vector[i] = frame;
  356. }
  357. // move superfluous data into the class buffer instead
  358. auto result = m_unread_data.try_grow_capacity(m_current_frame->sample_count - samples_to_directly_copy);
  359. if (result.is_error())
  360. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(samples_to_directly_copy + m_current_sample_or_frame), "Couldn't allocate sample buffer for superfluous data" };
  361. for (size_t i = samples_to_directly_copy; i < m_current_frame->sample_count; ++i) {
  362. Sample frame = { left[i] / sample_rescale, right[i] / sample_rescale };
  363. m_unread_data.unchecked_append(frame);
  364. }
  365. return {};
  366. #undef FLAC_VERIFY
  367. }
  368. ErrorOr<u32, LoaderError> FlacLoaderPlugin::convert_sample_count_code(u8 sample_count_code)
  369. {
  370. // single codes
  371. switch (sample_count_code) {
  372. case 0:
  373. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved block size" };
  374. case 1:
  375. return 192;
  376. case 6:
  377. return FLAC_BLOCKSIZE_AT_END_OF_HEADER_8;
  378. case 7:
  379. return FLAC_BLOCKSIZE_AT_END_OF_HEADER_16;
  380. }
  381. if (sample_count_code >= 2 && sample_count_code <= 5) {
  382. return 576 * AK::exp2(sample_count_code - 2);
  383. }
  384. return 256 * AK::exp2(sample_count_code - 8);
  385. }
  386. ErrorOr<u32, LoaderError> FlacLoaderPlugin::convert_sample_rate_code(u8 sample_rate_code)
  387. {
  388. switch (sample_rate_code) {
  389. case 0:
  390. return m_sample_rate;
  391. case 1:
  392. return 88200;
  393. case 2:
  394. return 176400;
  395. case 3:
  396. return 192000;
  397. case 4:
  398. return 8000;
  399. case 5:
  400. return 16000;
  401. case 6:
  402. return 22050;
  403. case 7:
  404. return 24000;
  405. case 8:
  406. return 32000;
  407. case 9:
  408. return 44100;
  409. case 10:
  410. return 48000;
  411. case 11:
  412. return 96000;
  413. case 12:
  414. return FLAC_SAMPLERATE_AT_END_OF_HEADER_8;
  415. case 13:
  416. return FLAC_SAMPLERATE_AT_END_OF_HEADER_16;
  417. case 14:
  418. return FLAC_SAMPLERATE_AT_END_OF_HEADER_16X10;
  419. default:
  420. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Invalid sample rate code" };
  421. }
  422. }
  423. ErrorOr<PcmSampleFormat, LoaderError> FlacLoaderPlugin::convert_bit_depth_code(u8 bit_depth_code)
  424. {
  425. switch (bit_depth_code) {
  426. case 0:
  427. return m_sample_format;
  428. case 1:
  429. return PcmSampleFormat::Uint8;
  430. case 4:
  431. return PcmSampleFormat::Int16;
  432. case 6:
  433. return PcmSampleFormat::Int24;
  434. case 3:
  435. case 7:
  436. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved sample size" };
  437. default:
  438. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), String::formatted("Unsupported sample size {}", bit_depth_code) };
  439. }
  440. }
  441. u8 frame_channel_type_to_channel_count(FlacFrameChannelType channel_type)
  442. {
  443. if (channel_type <= FlacFrameChannelType::Surround7p1)
  444. return to_underlying(channel_type) + 1;
  445. return 2;
  446. }
  447. ErrorOr<FlacSubframeHeader, LoaderError> FlacLoaderPlugin::next_subframe_header(BigEndianInputBitStream& bit_stream, u8 channel_index)
  448. {
  449. u8 bits_per_sample = static_cast<u16>(pcm_bits_per_sample(m_current_frame->bit_depth));
  450. // For inter-channel correlation, the side channel needs an extra bit for its samples
  451. switch (m_current_frame->channels) {
  452. case FlacFrameChannelType::LeftSideStereo:
  453. case FlacFrameChannelType::MidSideStereo:
  454. if (channel_index == 1) {
  455. ++bits_per_sample;
  456. }
  457. break;
  458. case FlacFrameChannelType::RightSideStereo:
  459. if (channel_index == 0) {
  460. ++bits_per_sample;
  461. }
  462. break;
  463. // "normal" channel types
  464. default:
  465. break;
  466. }
  467. // zero-bit padding
  468. if (LOADER_TRY(bit_stream.read_bit()) != 0)
  469. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Zero bit padding" };
  470. // subframe type (encoding)
  471. u8 subframe_code = LOADER_TRY(bit_stream.read_bits<u8>(6));
  472. if ((subframe_code >= 0b000010 && subframe_code <= 0b000111) || (subframe_code > 0b001100 && subframe_code < 0b100000))
  473. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Subframe type" };
  474. FlacSubframeType subframe_type;
  475. u8 order = 0;
  476. // LPC has the highest bit set
  477. if ((subframe_code & 0b100000) > 0) {
  478. subframe_type = FlacSubframeType::LPC;
  479. order = (subframe_code & 0b011111) + 1;
  480. } else if ((subframe_code & 0b001000) > 0) {
  481. // Fixed has the third-highest bit set
  482. subframe_type = FlacSubframeType::Fixed;
  483. order = (subframe_code & 0b000111);
  484. } else {
  485. subframe_type = (FlacSubframeType)subframe_code;
  486. }
  487. // wasted bits per sample (unary encoding)
  488. bool has_wasted_bits = LOADER_TRY(bit_stream.read_bit());
  489. u8 k = 0;
  490. if (has_wasted_bits) {
  491. bool current_k_bit = 0;
  492. do {
  493. current_k_bit = LOADER_TRY(bit_stream.read_bit());
  494. ++k;
  495. } while (current_k_bit != 1);
  496. }
  497. return FlacSubframeHeader {
  498. subframe_type,
  499. order,
  500. k,
  501. bits_per_sample
  502. };
  503. }
  504. ErrorOr<Vector<i32>, LoaderError> FlacLoaderPlugin::parse_subframe(FlacSubframeHeader& subframe_header, BigEndianInputBitStream& bit_input)
  505. {
  506. Vector<i32> samples;
  507. switch (subframe_header.type) {
  508. case FlacSubframeType::Constant: {
  509. u64 constant_value = LOADER_TRY(bit_input.read_bits<u64>(subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample));
  510. dbgln_if(AFLACLOADER_DEBUG, "Constant subframe: {}", constant_value);
  511. samples.ensure_capacity(m_current_frame->sample_count);
  512. VERIFY(subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample != 0);
  513. i32 constant = sign_extend(static_cast<u32>(constant_value), subframe_header.bits_per_sample - subframe_header.wasted_bits_per_sample);
  514. for (u32 i = 0; i < m_current_frame->sample_count; ++i) {
  515. samples.unchecked_append(constant);
  516. }
  517. break;
  518. }
  519. case FlacSubframeType::Fixed: {
  520. dbgln_if(AFLACLOADER_DEBUG, "Fixed LPC subframe order {}", subframe_header.order);
  521. samples = TRY(decode_fixed_lpc(subframe_header, bit_input));
  522. break;
  523. }
  524. case FlacSubframeType::Verbatim: {
  525. dbgln_if(AFLACLOADER_DEBUG, "Verbatim subframe");
  526. samples = TRY(decode_verbatim(subframe_header, bit_input));
  527. break;
  528. }
  529. case FlacSubframeType::LPC: {
  530. dbgln_if(AFLACLOADER_DEBUG, "Custom LPC subframe order {}", subframe_header.order);
  531. samples = TRY(decode_custom_lpc(subframe_header, bit_input));
  532. break;
  533. }
  534. default:
  535. return LoaderError { LoaderError::Category::Unimplemented, static_cast<size_t>(m_current_sample_or_frame), "Unhandled FLAC subframe type" };
  536. }
  537. for (size_t i = 0; i < samples.size(); ++i) {
  538. samples[i] <<= subframe_header.wasted_bits_per_sample;
  539. }
  540. ResampleHelper<i32> resampler(m_current_frame->sample_rate, m_sample_rate);
  541. return resampler.resample(samples);
  542. }
  543. // Decode a subframe that isn't actually encoded, usually seen in random data
  544. ErrorOr<Vector<i32>, LoaderError> FlacLoaderPlugin::decode_verbatim(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  545. {
  546. Vector<i32> decoded;
  547. decoded.ensure_capacity(m_current_frame->sample_count);
  548. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  549. for (size_t i = 0; i < m_current_frame->sample_count; ++i) {
  550. decoded.unchecked_append(sign_extend(
  551. LOADER_TRY(bit_input.read_bits<u32>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  552. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  553. }
  554. return decoded;
  555. }
  556. // Decode a subframe encoded with a custom linear predictor coding, i.e. the subframe provides the polynomial order and coefficients
  557. ErrorOr<Vector<i32>, LoaderError> FlacLoaderPlugin::decode_custom_lpc(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  558. {
  559. Vector<i32> decoded;
  560. decoded.ensure_capacity(m_current_frame->sample_count);
  561. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  562. // warm-up samples
  563. for (auto i = 0; i < subframe.order; ++i) {
  564. decoded.unchecked_append(sign_extend(
  565. LOADER_TRY(bit_input.read_bits<u32>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  566. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  567. }
  568. // precision of the coefficients
  569. u8 lpc_precision = LOADER_TRY(bit_input.read_bits<u8>(4));
  570. if (lpc_precision == 0b1111)
  571. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Invalid linear predictor coefficient precision" };
  572. lpc_precision += 1;
  573. // shift needed on the data (signed!)
  574. i8 lpc_shift = sign_extend(LOADER_TRY(bit_input.read_bits<u8>(5)), 5);
  575. Vector<i32> coefficients;
  576. coefficients.ensure_capacity(subframe.order);
  577. // read coefficients
  578. for (auto i = 0; i < subframe.order; ++i) {
  579. u32 raw_coefficient = LOADER_TRY(bit_input.read_bits<u32>(lpc_precision));
  580. i32 coefficient = static_cast<i32>(sign_extend(raw_coefficient, lpc_precision));
  581. coefficients.unchecked_append(coefficient);
  582. }
  583. dbgln_if(AFLACLOADER_DEBUG, "{}-bit {} shift coefficients: {}", lpc_precision, lpc_shift, coefficients);
  584. TRY(decode_residual(decoded, subframe, bit_input));
  585. // approximate the waveform with the predictor
  586. for (size_t i = subframe.order; i < m_current_frame->sample_count; ++i) {
  587. // (see below)
  588. i64 sample = 0;
  589. for (size_t t = 0; t < subframe.order; ++t) {
  590. // It's really important that we compute in 64-bit land here.
  591. // Even though FLAC operates at a maximum bit depth of 32 bits, modern encoders use super-large coefficients for maximum compression.
  592. // These will easily overflow 32 bits and cause strange white noise that abruptly stops intermittently (at the end of a frame).
  593. // The simple fix of course is to do intermediate computations in 64 bits.
  594. sample += static_cast<i64>(coefficients[t]) * static_cast<i64>(decoded[i - t - 1]);
  595. }
  596. decoded[i] += sample >> lpc_shift;
  597. }
  598. return decoded;
  599. }
  600. // Decode a subframe encoded with one of the fixed linear predictor codings
  601. ErrorOr<Vector<i32>, LoaderError> FlacLoaderPlugin::decode_fixed_lpc(FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  602. {
  603. Vector<i32> decoded;
  604. decoded.ensure_capacity(m_current_frame->sample_count);
  605. VERIFY(subframe.bits_per_sample - subframe.wasted_bits_per_sample != 0);
  606. // warm-up samples
  607. for (auto i = 0; i < subframe.order; ++i) {
  608. decoded.unchecked_append(sign_extend(
  609. LOADER_TRY(bit_input.read_bits<u32>(subframe.bits_per_sample - subframe.wasted_bits_per_sample)),
  610. subframe.bits_per_sample - subframe.wasted_bits_per_sample));
  611. }
  612. TRY(decode_residual(decoded, subframe, bit_input));
  613. dbgln_if(AFLACLOADER_DEBUG, "decoded length {}, {} order predictor", decoded.size(), subframe.order);
  614. switch (subframe.order) {
  615. case 0:
  616. // s_0(t) = 0
  617. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  618. decoded[i] += 0;
  619. break;
  620. case 1:
  621. // s_1(t) = s(t-1)
  622. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  623. decoded[i] += decoded[i - 1];
  624. break;
  625. case 2:
  626. // s_2(t) = 2s(t-1) - s(t-2)
  627. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  628. decoded[i] += 2 * decoded[i - 1] - decoded[i - 2];
  629. break;
  630. case 3:
  631. // s_3(t) = 3s(t-1) - 3s(t-2) + s(t-3)
  632. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  633. decoded[i] += 3 * decoded[i - 1] - 3 * decoded[i - 2] + decoded[i - 3];
  634. break;
  635. case 4:
  636. // s_4(t) = 4s(t-1) - 6s(t-2) + 4s(t-3) - s(t-4)
  637. for (u32 i = subframe.order; i < m_current_frame->sample_count; ++i)
  638. decoded[i] += 4 * decoded[i - 1] - 6 * decoded[i - 2] + 4 * decoded[i - 3] - decoded[i - 4];
  639. break;
  640. default:
  641. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), String::formatted("Unrecognized predictor order {}", subframe.order) };
  642. }
  643. return decoded;
  644. }
  645. // Decode the residual, the "error" between the function approximation and the actual audio data
  646. MaybeLoaderError FlacLoaderPlugin::decode_residual(Vector<i32>& decoded, FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  647. {
  648. auto residual_mode = static_cast<FlacResidualMode>(LOADER_TRY(bit_input.read_bits<u8>(2)));
  649. u8 partition_order = LOADER_TRY(bit_input.read_bits<u8>(4));
  650. size_t partitions = 1 << partition_order;
  651. if (residual_mode == FlacResidualMode::Rice4Bit) {
  652. // decode a single Rice partition with four bits for the order k
  653. for (size_t i = 0; i < partitions; ++i) {
  654. auto rice_partition = TRY(decode_rice_partition(4, partitions, i, subframe, bit_input));
  655. decoded.extend(move(rice_partition));
  656. }
  657. } else if (residual_mode == FlacResidualMode::Rice5Bit) {
  658. // five bits equivalent
  659. for (size_t i = 0; i < partitions; ++i) {
  660. auto rice_partition = TRY(decode_rice_partition(5, partitions, i, subframe, bit_input));
  661. decoded.extend(move(rice_partition));
  662. }
  663. } else
  664. return LoaderError { LoaderError::Category::Format, static_cast<size_t>(m_current_sample_or_frame), "Reserved residual coding method" };
  665. return {};
  666. }
  667. // Decode a single Rice partition as part of the residual, every partition can have its own Rice parameter k
  668. ALWAYS_INLINE ErrorOr<Vector<i32>, LoaderError> FlacLoaderPlugin::decode_rice_partition(u8 partition_type, u32 partitions, u32 partition_index, FlacSubframeHeader& subframe, BigEndianInputBitStream& bit_input)
  669. {
  670. // Rice parameter / Exp-Golomb order
  671. u8 k = LOADER_TRY(bit_input.read_bits<u8>(partition_type));
  672. u32 residual_sample_count;
  673. if (partitions == 0)
  674. residual_sample_count = m_current_frame->sample_count - subframe.order;
  675. else
  676. residual_sample_count = m_current_frame->sample_count / partitions;
  677. if (partition_index == 0)
  678. residual_sample_count -= subframe.order;
  679. Vector<i32> rice_partition;
  680. rice_partition.resize(residual_sample_count);
  681. // escape code for unencoded binary partition
  682. if (k == (1 << partition_type) - 1) {
  683. u8 unencoded_bps = LOADER_TRY(bit_input.read_bits<u8>(5));
  684. for (size_t r = 0; r < residual_sample_count; ++r) {
  685. rice_partition[r] = LOADER_TRY(bit_input.read_bits<u8>(unencoded_bps));
  686. }
  687. } else {
  688. for (size_t r = 0; r < residual_sample_count; ++r) {
  689. rice_partition[r] = LOADER_TRY(decode_unsigned_exp_golomb(k, bit_input));
  690. }
  691. }
  692. return rice_partition;
  693. }
  694. // Decode a single number encoded with Rice/Exponential-Golomb encoding (the unsigned variant)
  695. ALWAYS_INLINE ErrorOr<i32> decode_unsigned_exp_golomb(u8 k, BigEndianInputBitStream& bit_input)
  696. {
  697. u8 q = 0;
  698. while (TRY(bit_input.read_bit()) == 0)
  699. ++q;
  700. // least significant bits (remainder)
  701. u32 rem = TRY(bit_input.read_bits<u32>(k));
  702. u32 value = q << k | rem;
  703. return rice_to_signed(value);
  704. }
  705. ErrorOr<u64> read_utf8_char(BigEndianInputBitStream& input)
  706. {
  707. u64 character;
  708. u8 buffer = 0;
  709. Bytes buffer_bytes { &buffer, 1 };
  710. TRY(input.read(buffer_bytes));
  711. u8 start_byte = buffer_bytes[0];
  712. // Signal byte is zero: ASCII character
  713. if ((start_byte & 0b10000000) == 0) {
  714. return start_byte;
  715. } else if ((start_byte & 0b11000000) == 0b10000000) {
  716. return Error::from_string_literal("Illegal continuation byte"sv);
  717. }
  718. // This algorithm is too good and supports the theoretical max 0xFF start byte
  719. u8 length = 1;
  720. while (((start_byte << length) & 0b10000000) == 0b10000000)
  721. ++length;
  722. u8 bits_from_start_byte = 8 - (length + 1);
  723. u8 start_byte_bitmask = AK::exp2(bits_from_start_byte) - 1;
  724. character = start_byte_bitmask & start_byte;
  725. for (u8 i = length - 1; i > 0; --i) {
  726. TRY(input.read(buffer_bytes));
  727. u8 current_byte = buffer_bytes[0];
  728. character = (character << 6) | (current_byte & 0b00111111);
  729. }
  730. return character;
  731. }
  732. i64 sign_extend(u32 n, u8 size)
  733. {
  734. // negative
  735. if ((n & (1 << (size - 1))) > 0) {
  736. return static_cast<i64>(n | (0xffffffff << size));
  737. }
  738. // positive
  739. return n;
  740. }
  741. i32 rice_to_signed(u32 x)
  742. {
  743. // positive numbers are even, negative numbers are odd
  744. // bitmask for conditionally inverting the entire number, thereby "negating" it
  745. i32 sign = -static_cast<i32>(x & 1);
  746. // copies the sign's sign onto the actual magnitude of x
  747. return static_cast<i32>(sign ^ (x >> 1));
  748. }
  749. }