FlacLoader.cpp 29 KB

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