FlacLoader.cpp 31 KB

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