FlacLoader.cpp 33 KB

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