FlacLoader.cpp 30 KB

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