FlacLoader.cpp 32 KB

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