qoa.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /*
  2. Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org
  3. SPDX-License-Identifier: MIT
  4. QOA - The "Quite OK Audio" format for fast, lossy audio compression
  5. -- Data Format
  6. QOA encodes pulse-code modulated (PCM) audio data with up to 255 channels,
  7. sample rates from 1 up to 16777215 hertz and a bit depth of 16 bits.
  8. The compression method employed in QOA is lossy; it discards some information
  9. from the uncompressed PCM data. For many types of audio signals this compression
  10. is "transparent", i.e. the difference from the original file is often not
  11. audible.
  12. QOA encodes 20 samples of 16 bit PCM data into slices of 64 bits. A single
  13. sample therefore requires 3.2 bits of storage space, resulting in a 5x
  14. compression (16 / 3.2).
  15. A QOA file consists of an 8 byte file header, followed by a number of frames.
  16. Each frame contains an 8 byte frame header, the current 16 byte en-/decoder
  17. state per channel and 256 slices per channel. Each slice is 8 bytes wide and
  18. encodes 20 samples of audio data.
  19. All values, including the slices, are big endian. The file layout is as follows:
  20. struct {
  21. struct {
  22. char magic[4]; // magic bytes "qoaf"
  23. uint32_t samples; // samples per channel in this file
  24. } file_header;
  25. struct {
  26. struct {
  27. uint8_t num_channels; // no. of channels
  28. uint24_t samplerate; // samplerate in hz
  29. uint16_t fsamples; // samples per channel in this frame
  30. uint16_t fsize; // frame size (includes this header)
  31. } frame_header;
  32. struct {
  33. int16_t history[4]; // most recent last
  34. int16_t weights[4]; // most recent last
  35. } lms_state[num_channels];
  36. qoa_slice_t slices[256][num_channels];
  37. } frames[ceil(samples / (256 * 20))];
  38. } qoa_file_t;
  39. Each `qoa_slice_t` contains a quantized scalefactor `sf_quant` and 20 quantized
  40. residuals `qrNN`:
  41. .- QOA_SLICE -- 64 bits, 20 samples --------------------------/ /------------.
  42. | Byte[0] | Byte[1] | Byte[2] \ \ Byte[7] |
  43. | 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 / / 2 1 0 |
  44. |------------+--------+--------+--------+---------+---------+-\ \--+---------|
  45. | sf_quant | qr00 | qr01 | qr02 | qr03 | qr04 | / / | qr19 |
  46. `-------------------------------------------------------------\ \------------`
  47. Each frame except the last must contain exactly 256 slices per channel. The last
  48. frame may contain between 1 .. 256 (inclusive) slices per channel. The last
  49. slice (for each channel) in the last frame may contain less than 20 samples; the
  50. slice still must be 8 bytes wide, with the unused samples zeroed out.
  51. Channels are interleaved per slice. E.g. for 2 channel stereo:
  52. slice[0] = L, slice[1] = R, slice[2] = L, slice[3] = R ...
  53. A valid QOA file or stream must have at least one frame. Each frame must contain
  54. at least one channel and one sample with a samplerate between 1 .. 16777215
  55. (inclusive).
  56. If the total number of samples is not known by the encoder, the samples in the
  57. file header may be set to 0x00000000 to indicate that the encoder is
  58. "streaming". In a streaming context, the samplerate and number of channels may
  59. differ from frame to frame. For static files (those with samples set to a
  60. non-zero value), each frame must have the same number of channels and same
  61. samplerate.
  62. Note that this implementation of QOA only handles files with a known total
  63. number of samples.
  64. A decoder should support at least 8 channels. The channel layout for channel
  65. counts 1 .. 8 is:
  66. 1. Mono
  67. 2. L, R
  68. 3. L, R, C
  69. 4. FL, FR, B/SL, B/SR
  70. 5. FL, FR, C, B/SL, B/SR
  71. 6. FL, FR, C, LFE, B/SL, B/SR
  72. 7. FL, FR, C, LFE, B, SL, SR
  73. 8. FL, FR, C, LFE, BL, BR, SL, SR
  74. QOA predicts each audio sample based on the previously decoded ones using a
  75. "Sign-Sign Least Mean Squares Filter" (LMS). This prediction plus the
  76. dequantized residual forms the final output sample.
  77. */
  78. /* -----------------------------------------------------------------------------
  79. Header - Public functions */
  80. #ifndef QOA_H
  81. #define QOA_H
  82. #ifdef __cplusplus
  83. extern "C" {
  84. #endif
  85. #define QOA_MIN_FILESIZE 16
  86. #define QOA_MAX_CHANNELS 8
  87. #define QOA_SLICE_LEN 20
  88. #define QOA_SLICES_PER_FRAME 256
  89. #define QOA_FRAME_LEN (QOA_SLICES_PER_FRAME * QOA_SLICE_LEN)
  90. #define QOA_LMS_LEN 4
  91. #define QOA_MAGIC 0x716f6166 /* 'qoaf' */
  92. #define QOA_FRAME_SIZE(channels, slices) \
  93. (8 + QOA_LMS_LEN * 4 * channels + 8 * slices * channels)
  94. typedef struct {
  95. int history[QOA_LMS_LEN];
  96. int weights[QOA_LMS_LEN];
  97. } qoa_lms_t;
  98. typedef struct {
  99. unsigned int channels;
  100. unsigned int samplerate;
  101. unsigned int samples;
  102. qoa_lms_t lms[QOA_MAX_CHANNELS];
  103. #ifdef QOA_RECORD_TOTAL_ERROR
  104. double error;
  105. #endif
  106. } qoa_desc;
  107. unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes);
  108. unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes);
  109. void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len);
  110. unsigned int qoa_max_frame_size(qoa_desc *qoa);
  111. unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa);
  112. unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len);
  113. short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *file);
  114. #ifndef QOA_NO_STDIO
  115. int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa);
  116. void *qoa_read(const char *filename, qoa_desc *qoa);
  117. #endif /* QOA_NO_STDIO */
  118. #ifdef __cplusplus
  119. }
  120. #endif
  121. #endif /* QOA_H */
  122. /* -----------------------------------------------------------------------------
  123. Implementation */
  124. #ifdef QOA_IMPLEMENTATION
  125. #include <stdlib.h>
  126. #ifndef QOA_MALLOC
  127. #define QOA_MALLOC(sz) malloc(sz)
  128. #define QOA_FREE(p) free(p)
  129. #endif
  130. typedef unsigned long long qoa_uint64_t;
  131. /* The quant_tab provides an index into the dequant_tab for residuals in the
  132. range of -8 .. 8. It maps this range to just 3bits and becomes less accurate at
  133. the higher end. Note that the residual zero is identical to the lowest positive
  134. value. This is mostly fine, since the qoa_div() function always rounds away
  135. from zero. */
  136. static const int qoa_quant_tab[17] = {
  137. 7, 7, 7, 5, 5, 3, 3, 1, /* -8..-1 */
  138. 0, /* 0 */
  139. 0, 2, 2, 4, 4, 6, 6, 6 /* 1.. 8 */
  140. };
  141. /* We have 16 different scalefactors. Like the quantized residuals these become
  142. less accurate at the higher end. In theory, the highest scalefactor that we
  143. would need to encode the highest 16bit residual is (2**16)/8 = 8192. However we
  144. rely on the LMS filter to predict samples accurately enough that a maximum
  145. residual of one quarter of the 16 bit range is sufficient. I.e. with the
  146. scalefactor 2048 times the quant range of 8 we can encode residuals up to 2**14.
  147. The scalefactor values are computed as:
  148. scalefactor_tab[s] <- round(pow(s + 1, 2.75)) */
  149. static const int qoa_scalefactor_tab[16] = {
  150. 1, 7, 21, 45, 84, 138, 211, 304, 421, 562, 731, 928, 1157, 1419, 1715, 2048
  151. };
  152. /* The reciprocal_tab maps each of the 16 scalefactors to their rounded
  153. reciprocals 1/scalefactor. This allows us to calculate the scaled residuals in
  154. the encoder with just one multiplication instead of an expensive division. We
  155. do this in .16 fixed point with integers, instead of floats.
  156. The reciprocal_tab is computed as:
  157. reciprocal_tab[s] <- ((1<<16) + scalefactor_tab[s] - 1) / scalefactor_tab[s] */
  158. static const int qoa_reciprocal_tab[16] = {
  159. 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32
  160. };
  161. /* The dequant_tab maps each of the scalefactors and quantized residuals to
  162. their unscaled & dequantized version.
  163. Since qoa_div rounds away from the zero, the smallest entries are mapped to 3/4
  164. instead of 1. The dequant_tab assumes the following dequantized values for each
  165. of the quant_tab indices and is computed as:
  166. float dqt[8] = {0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7, -7};
  167. dequant_tab[s][q] <- round_ties_away_from_zero(scalefactor_tab[s] * dqt[q])
  168. The rounding employed here is "to nearest, ties away from zero", i.e. positive
  169. and negative values are treated symmetrically.
  170. */
  171. static const int qoa_dequant_tab[16][8] = {
  172. { 1, -1, 3, -3, 5, -5, 7, -7},
  173. { 5, -5, 18, -18, 32, -32, 49, -49},
  174. { 16, -16, 53, -53, 95, -95, 147, -147},
  175. { 34, -34, 113, -113, 203, -203, 315, -315},
  176. { 63, -63, 210, -210, 378, -378, 588, -588},
  177. { 104, -104, 345, -345, 621, -621, 966, -966},
  178. { 158, -158, 528, -528, 950, -950, 1477, -1477},
  179. { 228, -228, 760, -760, 1368, -1368, 2128, -2128},
  180. { 316, -316, 1053, -1053, 1895, -1895, 2947, -2947},
  181. { 422, -422, 1405, -1405, 2529, -2529, 3934, -3934},
  182. { 548, -548, 1828, -1828, 3290, -3290, 5117, -5117},
  183. { 696, -696, 2320, -2320, 4176, -4176, 6496, -6496},
  184. { 868, -868, 2893, -2893, 5207, -5207, 8099, -8099},
  185. {1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933},
  186. {1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005},
  187. {1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336},
  188. };
  189. /* The Least Mean Squares Filter is the heart of QOA. It predicts the next
  190. sample based on the previous 4 reconstructed samples. It does so by continuously
  191. adjusting 4 weights based on the residual of the previous prediction.
  192. The next sample is predicted as the sum of (weight[i] * history[i]).
  193. The adjustment of the weights is done with a "Sign-Sign-LMS" that adds or
  194. subtracts the residual to each weight, based on the corresponding sample from
  195. the history. This, surprisingly, is sufficient to get worthwhile predictions.
  196. This is all done with fixed point integers. Hence the right-shifts when updating
  197. the weights and calculating the prediction. */
  198. static int qoa_lms_predict(qoa_lms_t *lms) {
  199. int prediction = 0;
  200. for (int i = 0; i < QOA_LMS_LEN; i++) {
  201. prediction += lms->weights[i] * lms->history[i];
  202. }
  203. return prediction >> 13;
  204. }
  205. static void qoa_lms_update(qoa_lms_t *lms, int sample, int residual) {
  206. int delta = residual >> 4;
  207. for (int i = 0; i < QOA_LMS_LEN; i++) {
  208. lms->weights[i] += lms->history[i] < 0 ? -delta : delta;
  209. }
  210. for (int i = 0; i < QOA_LMS_LEN-1; i++) {
  211. lms->history[i] = lms->history[i+1];
  212. }
  213. lms->history[QOA_LMS_LEN-1] = sample;
  214. }
  215. /* qoa_div() implements a rounding division, but avoids rounding to zero for
  216. small numbers. E.g. 0.1 will be rounded to 1. Note that 0 itself still
  217. returns as 0, which is handled in the qoa_quant_tab[].
  218. qoa_div() takes an index into the .16 fixed point qoa_reciprocal_tab as an
  219. argument, so it can do the division with a cheaper integer multiplication. */
  220. static inline int qoa_div(int v, int scalefactor) {
  221. int reciprocal = qoa_reciprocal_tab[scalefactor];
  222. int n = (v * reciprocal + (1 << 15)) >> 16;
  223. n = n + ((v > 0) - (v < 0)) - ((n > 0) - (n < 0)); /* round away from 0 */
  224. return n;
  225. }
  226. static inline int qoa_clamp(int v, int min, int max) {
  227. if (v < min) { return min; }
  228. if (v > max) { return max; }
  229. return v;
  230. }
  231. /* This specialized clamp function for the signed 16 bit range improves decode
  232. performance quite a bit. The extra if() statement works nicely with the CPUs
  233. branch prediction as this branch is rarely taken. */
  234. static inline int qoa_clamp_s16(int v) {
  235. if ((unsigned int)(v + 32768) > 65535) {
  236. if (v < -32768) { return -32768; }
  237. if (v > 32767) { return 32767; }
  238. }
  239. return v;
  240. }
  241. static inline qoa_uint64_t qoa_read_u64(const unsigned char *bytes, unsigned int *p) {
  242. bytes += *p;
  243. *p += 8;
  244. return
  245. ((qoa_uint64_t)(bytes[0]) << 56) | ((qoa_uint64_t)(bytes[1]) << 48) |
  246. ((qoa_uint64_t)(bytes[2]) << 40) | ((qoa_uint64_t)(bytes[3]) << 32) |
  247. ((qoa_uint64_t)(bytes[4]) << 24) | ((qoa_uint64_t)(bytes[5]) << 16) |
  248. ((qoa_uint64_t)(bytes[6]) << 8) | ((qoa_uint64_t)(bytes[7]) << 0);
  249. }
  250. static inline void qoa_write_u64(qoa_uint64_t v, unsigned char *bytes, unsigned int *p) {
  251. bytes += *p;
  252. *p += 8;
  253. bytes[0] = (v >> 56) & 0xff;
  254. bytes[1] = (v >> 48) & 0xff;
  255. bytes[2] = (v >> 40) & 0xff;
  256. bytes[3] = (v >> 32) & 0xff;
  257. bytes[4] = (v >> 24) & 0xff;
  258. bytes[5] = (v >> 16) & 0xff;
  259. bytes[6] = (v >> 8) & 0xff;
  260. bytes[7] = (v >> 0) & 0xff;
  261. }
  262. /* -----------------------------------------------------------------------------
  263. Encoder */
  264. unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes) {
  265. unsigned int p = 0;
  266. qoa_write_u64(((qoa_uint64_t)QOA_MAGIC << 32) | qoa->samples, bytes, &p);
  267. return p;
  268. }
  269. unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes) {
  270. unsigned int channels = qoa->channels;
  271. unsigned int p = 0;
  272. unsigned int slices = (frame_len + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN;
  273. unsigned int frame_size = QOA_FRAME_SIZE(channels, slices);
  274. int prev_scalefactor[QOA_MAX_CHANNELS] = {0};
  275. /* Write the frame header */
  276. qoa_write_u64((
  277. (qoa_uint64_t)qoa->channels << 56 |
  278. (qoa_uint64_t)qoa->samplerate << 32 |
  279. (qoa_uint64_t)frame_len << 16 |
  280. (qoa_uint64_t)frame_size
  281. ), bytes, &p);
  282. for (unsigned int c = 0; c < channels; c++) {
  283. /* Write the current LMS state */
  284. qoa_uint64_t weights = 0;
  285. qoa_uint64_t history = 0;
  286. for (int i = 0; i < QOA_LMS_LEN; i++) {
  287. history = (history << 16) | (qoa->lms[c].history[i] & 0xffff);
  288. weights = (weights << 16) | (qoa->lms[c].weights[i] & 0xffff);
  289. }
  290. qoa_write_u64(history, bytes, &p);
  291. qoa_write_u64(weights, bytes, &p);
  292. }
  293. /* We encode all samples with the channels interleaved on a slice level.
  294. E.g. for stereo: (ch-0, slice 0), (ch 1, slice 0), (ch 0, slice 1), ...*/
  295. for (unsigned int sample_index = 0; sample_index < frame_len; sample_index += QOA_SLICE_LEN) {
  296. for (unsigned int c = 0; c < channels; c++) {
  297. int slice_len = qoa_clamp(QOA_SLICE_LEN, 0, frame_len - sample_index);
  298. int slice_start = sample_index * channels + c;
  299. int slice_end = (sample_index + slice_len) * channels + c;
  300. /* Brute force search for the best scalefactor. Just go through all
  301. 16 scalefactors, encode all samples for the current slice and
  302. meassure the total squared error. */
  303. qoa_uint64_t best_rank = -1;
  304. #ifdef QOA_RECORD_TOTAL_ERROR
  305. qoa_uint64_t best_error = -1;
  306. #endif
  307. qoa_uint64_t best_slice = 0;
  308. qoa_lms_t best_lms;
  309. int best_scalefactor = 0;
  310. for (int sfi = 0; sfi < 16; sfi++) {
  311. /* There is a strong correlation between the scalefactors of
  312. neighboring slices. As an optimization, start testing
  313. the best scalefactor of the previous slice first. */
  314. int scalefactor = (sfi + prev_scalefactor[c]) & (16 - 1);
  315. /* We have to reset the LMS state to the last known good one
  316. before trying each scalefactor, as each pass updates the LMS
  317. state when encoding. */
  318. qoa_lms_t lms = qoa->lms[c];
  319. qoa_uint64_t slice = scalefactor;
  320. qoa_uint64_t current_rank = 0;
  321. #ifdef QOA_RECORD_TOTAL_ERROR
  322. qoa_uint64_t current_error = 0;
  323. #endif
  324. for (int si = slice_start; si < slice_end; si += channels) {
  325. int sample = sample_data[si];
  326. int predicted = qoa_lms_predict(&lms);
  327. int residual = sample - predicted;
  328. int scaled = qoa_div(residual, scalefactor);
  329. int clamped = qoa_clamp(scaled, -8, 8);
  330. int quantized = qoa_quant_tab[clamped + 8];
  331. int dequantized = qoa_dequant_tab[scalefactor][quantized];
  332. int reconstructed = qoa_clamp_s16(predicted + dequantized);
  333. /* If the weights have grown too large, we introduce a penalty
  334. here. This prevents pops/clicks in certain problem cases */
  335. int weights_penalty = ((
  336. lms.weights[0] * lms.weights[0] +
  337. lms.weights[1] * lms.weights[1] +
  338. lms.weights[2] * lms.weights[2] +
  339. lms.weights[3] * lms.weights[3]
  340. ) >> 18) - 0x8ff;
  341. if (weights_penalty < 0) {
  342. weights_penalty = 0;
  343. }
  344. long long error = (sample - reconstructed);
  345. qoa_uint64_t error_sq = error * error;
  346. current_rank += error_sq + weights_penalty * weights_penalty;
  347. #ifdef QOA_RECORD_TOTAL_ERROR
  348. current_error += error_sq;
  349. #endif
  350. if (current_rank > best_rank) {
  351. break;
  352. }
  353. qoa_lms_update(&lms, reconstructed, dequantized);
  354. slice = (slice << 3) | quantized;
  355. }
  356. if (current_rank < best_rank) {
  357. best_rank = current_rank;
  358. #ifdef QOA_RECORD_TOTAL_ERROR
  359. best_error = current_error;
  360. #endif
  361. best_slice = slice;
  362. best_lms = lms;
  363. best_scalefactor = scalefactor;
  364. }
  365. }
  366. prev_scalefactor[c] = best_scalefactor;
  367. qoa->lms[c] = best_lms;
  368. #ifdef QOA_RECORD_TOTAL_ERROR
  369. qoa->error += best_error;
  370. #endif
  371. /* If this slice was shorter than QOA_SLICE_LEN, we have to left-
  372. shift all encoded data, to ensure the rightmost bits are the empty
  373. ones. This should only happen in the last frame of a file as all
  374. slices are completely filled otherwise. */
  375. best_slice <<= (QOA_SLICE_LEN - slice_len) * 3;
  376. qoa_write_u64(best_slice, bytes, &p);
  377. }
  378. }
  379. return p;
  380. }
  381. void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len) {
  382. if (
  383. qoa->samples == 0 ||
  384. qoa->samplerate == 0 || qoa->samplerate > 0xffffff ||
  385. qoa->channels == 0 || qoa->channels > QOA_MAX_CHANNELS
  386. ) {
  387. return NULL;
  388. }
  389. /* Calculate the encoded size and allocate */
  390. unsigned int num_frames = (qoa->samples + QOA_FRAME_LEN-1) / QOA_FRAME_LEN;
  391. unsigned int num_slices = (qoa->samples + QOA_SLICE_LEN-1) / QOA_SLICE_LEN;
  392. unsigned int encoded_size = 8 + /* 8 byte file header */
  393. num_frames * 8 + /* 8 byte frame headers */
  394. num_frames * QOA_LMS_LEN * 4 * qoa->channels + /* 4 * 4 bytes lms state per channel */
  395. num_slices * 8 * qoa->channels; /* 8 byte slices */
  396. unsigned char *bytes = QOA_MALLOC(encoded_size);
  397. for (unsigned int c = 0; c < qoa->channels; c++) {
  398. /* Set the initial LMS weights to {0, 0, -1, 2}. This helps with the
  399. prediction of the first few ms of a file. */
  400. qoa->lms[c].weights[0] = 0;
  401. qoa->lms[c].weights[1] = 0;
  402. qoa->lms[c].weights[2] = -(1<<13);
  403. qoa->lms[c].weights[3] = (1<<14);
  404. /* Explicitly set the history samples to 0, as we might have some
  405. garbage in there. */
  406. for (int i = 0; i < QOA_LMS_LEN; i++) {
  407. qoa->lms[c].history[i] = 0;
  408. }
  409. }
  410. /* Encode the header and go through all frames */
  411. unsigned int p = qoa_encode_header(qoa, bytes);
  412. #ifdef QOA_RECORD_TOTAL_ERROR
  413. qoa->error = 0;
  414. #endif
  415. int frame_len = QOA_FRAME_LEN;
  416. for (unsigned int sample_index = 0; sample_index < qoa->samples; sample_index += frame_len) {
  417. frame_len = qoa_clamp(QOA_FRAME_LEN, 0, qoa->samples - sample_index);
  418. const short *frame_samples = sample_data + sample_index * qoa->channels;
  419. unsigned int frame_size = qoa_encode_frame(frame_samples, qoa, frame_len, bytes + p);
  420. p += frame_size;
  421. }
  422. *out_len = p;
  423. return bytes;
  424. }
  425. /* -----------------------------------------------------------------------------
  426. Decoder */
  427. unsigned int qoa_max_frame_size(qoa_desc *qoa) {
  428. return QOA_FRAME_SIZE(qoa->channels, QOA_SLICES_PER_FRAME);
  429. }
  430. unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa) {
  431. unsigned int p = 0;
  432. if (size < QOA_MIN_FILESIZE) {
  433. return 0;
  434. }
  435. /* Read the file header, verify the magic number ('qoaf') and read the
  436. total number of samples. */
  437. qoa_uint64_t file_header = qoa_read_u64(bytes, &p);
  438. if ((file_header >> 32) != QOA_MAGIC) {
  439. return 0;
  440. }
  441. qoa->samples = file_header & 0xffffffff;
  442. if (!qoa->samples) {
  443. return 0;
  444. }
  445. /* Peek into the first frame header to get the number of channels and
  446. the samplerate. */
  447. qoa_uint64_t frame_header = qoa_read_u64(bytes, &p);
  448. qoa->channels = (frame_header >> 56) & 0x0000ff;
  449. qoa->samplerate = (frame_header >> 32) & 0xffffff;
  450. if (qoa->channels == 0 || qoa->samples == 0 || qoa->samplerate == 0) {
  451. return 0;
  452. }
  453. return 8;
  454. }
  455. unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len) {
  456. unsigned int p = 0;
  457. *frame_len = 0;
  458. if (size < 8 + QOA_LMS_LEN * 4 * qoa->channels) {
  459. return 0;
  460. }
  461. /* Read and verify the frame header */
  462. qoa_uint64_t frame_header = qoa_read_u64(bytes, &p);
  463. unsigned int channels = (frame_header >> 56) & 0x0000ff;
  464. unsigned int samplerate = (frame_header >> 32) & 0xffffff;
  465. unsigned int samples = (frame_header >> 16) & 0x00ffff;
  466. unsigned int frame_size = (frame_header ) & 0x00ffff;
  467. unsigned int data_size = frame_size - 8 - QOA_LMS_LEN * 4 * channels;
  468. unsigned int num_slices = data_size / 8;
  469. unsigned int max_total_samples = num_slices * QOA_SLICE_LEN;
  470. if (
  471. channels != qoa->channels ||
  472. samplerate != qoa->samplerate ||
  473. frame_size > size ||
  474. samples * channels > max_total_samples
  475. ) {
  476. return 0;
  477. }
  478. /* Read the LMS state: 4 x 2 bytes history, 4 x 2 bytes weights per channel */
  479. for (unsigned int c = 0; c < channels; c++) {
  480. qoa_uint64_t history = qoa_read_u64(bytes, &p);
  481. qoa_uint64_t weights = qoa_read_u64(bytes, &p);
  482. for (int i = 0; i < QOA_LMS_LEN; i++) {
  483. qoa->lms[c].history[i] = ((signed short)(history >> 48));
  484. history <<= 16;
  485. qoa->lms[c].weights[i] = ((signed short)(weights >> 48));
  486. weights <<= 16;
  487. }
  488. }
  489. /* Decode all slices for all channels in this frame */
  490. for (unsigned int sample_index = 0; sample_index < samples; sample_index += QOA_SLICE_LEN) {
  491. for (unsigned int c = 0; c < channels; c++) {
  492. qoa_uint64_t slice = qoa_read_u64(bytes, &p);
  493. int scalefactor = (slice >> 60) & 0xf;
  494. slice <<= 4;
  495. int slice_start = sample_index * channels + c;
  496. int slice_end = qoa_clamp(sample_index + QOA_SLICE_LEN, 0, samples) * channels + c;
  497. for (int si = slice_start; si < slice_end; si += channels) {
  498. int predicted = qoa_lms_predict(&qoa->lms[c]);
  499. int quantized = (slice >> 61) & 0x7;
  500. int dequantized = qoa_dequant_tab[scalefactor][quantized];
  501. int reconstructed = qoa_clamp_s16(predicted + dequantized);
  502. sample_data[si] = reconstructed;
  503. slice <<= 3;
  504. qoa_lms_update(&qoa->lms[c], reconstructed, dequantized);
  505. }
  506. }
  507. }
  508. *frame_len = samples;
  509. return p;
  510. }
  511. short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *qoa) {
  512. unsigned int p = qoa_decode_header(bytes, size, qoa);
  513. if (!p) {
  514. return NULL;
  515. }
  516. /* Calculate the required size of the sample buffer and allocate */
  517. int total_samples = qoa->samples * qoa->channels;
  518. short *sample_data = QOA_MALLOC(total_samples * sizeof(short));
  519. unsigned int sample_index = 0;
  520. unsigned int frame_len;
  521. unsigned int frame_size;
  522. /* Decode all frames */
  523. do {
  524. short *sample_ptr = sample_data + sample_index * qoa->channels;
  525. frame_size = qoa_decode_frame(bytes + p, size - p, qoa, sample_ptr, &frame_len);
  526. p += frame_size;
  527. sample_index += frame_len;
  528. } while (frame_size && sample_index < qoa->samples);
  529. qoa->samples = sample_index;
  530. return sample_data;
  531. }
  532. /* -----------------------------------------------------------------------------
  533. File read/write convenience functions */
  534. #ifndef QOA_NO_STDIO
  535. #include <stdio.h>
  536. int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa) {
  537. FILE *f = fopen(filename, "wb");
  538. unsigned int size;
  539. void *encoded;
  540. if (!f) {
  541. return 0;
  542. }
  543. encoded = qoa_encode(sample_data, qoa, &size);
  544. if (!encoded) {
  545. fclose(f);
  546. return 0;
  547. }
  548. fwrite(encoded, 1, size, f);
  549. fclose(f);
  550. QOA_FREE(encoded);
  551. return size;
  552. }
  553. void *qoa_read(const char *filename, qoa_desc *qoa) {
  554. FILE *f = fopen(filename, "rb");
  555. int size, bytes_read;
  556. void *data;
  557. short *sample_data;
  558. if (!f) {
  559. return NULL;
  560. }
  561. fseek(f, 0, SEEK_END);
  562. size = ftell(f);
  563. if (size <= 0) {
  564. fclose(f);
  565. return NULL;
  566. }
  567. fseek(f, 0, SEEK_SET);
  568. data = QOA_MALLOC(size);
  569. if (!data) {
  570. fclose(f);
  571. return NULL;
  572. }
  573. bytes_read = fread(data, 1, size, f);
  574. fclose(f);
  575. sample_data = qoa_decode(data, bytes_read, qoa);
  576. QOA_FREE(data);
  577. return sample_data;
  578. }
  579. #endif /* QOA_NO_STDIO */
  580. #endif /* QOA_IMPLEMENTATION */