FlacLoader.cpp 31 KB

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