You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1661 lines
55KB

  1. /*
  2. * WavPack lossless audio decoder
  3. * Copyright (c) 2006,2011 Konstantin Shishkov
  4. * Copyright (c) 2020 David Bryant
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "libavutil/channel_layout.h"
  23. #define BITSTREAM_READER_LE
  24. #include "avcodec.h"
  25. #include "bytestream.h"
  26. #include "get_bits.h"
  27. #include "internal.h"
  28. #include "thread.h"
  29. #include "unary.h"
  30. #include "wavpack.h"
  31. #include "dsd.h"
  32. /**
  33. * @file
  34. * WavPack lossless audio decoder
  35. */
  36. #define DSD_BYTE_READY(low,high) (!(((low) ^ (high)) & 0xff000000))
  37. #define PTABLE_BITS 8
  38. #define PTABLE_BINS (1<<PTABLE_BITS)
  39. #define PTABLE_MASK (PTABLE_BINS-1)
  40. #define UP 0x010000fe
  41. #define DOWN 0x00010000
  42. #define DECAY 8
  43. #define PRECISION 20
  44. #define VALUE_ONE (1 << PRECISION)
  45. #define PRECISION_USE 12
  46. #define RATE_S 20
  47. #define MAX_HISTORY_BITS 5
  48. #define MAX_HISTORY_BINS (1 << MAX_HISTORY_BITS)
  49. #define MAX_BIN_BYTES 1280 // for value_lookup, per bin (2k - 512 - 256)
  50. typedef enum {
  51. MODULATION_PCM, // pulse code modulation
  52. MODULATION_DSD // pulse density modulation (aka DSD)
  53. } Modulation;
  54. typedef struct WavpackFrameContext {
  55. AVCodecContext *avctx;
  56. int frame_flags;
  57. int stereo, stereo_in;
  58. int joint;
  59. uint32_t CRC;
  60. GetBitContext gb;
  61. int got_extra_bits;
  62. uint32_t crc_extra_bits;
  63. GetBitContext gb_extra_bits;
  64. int samples;
  65. int terms;
  66. Decorr decorr[MAX_TERMS];
  67. int zero, one, zeroes;
  68. int extra_bits;
  69. int and, or, shift;
  70. int post_shift;
  71. int hybrid, hybrid_bitrate;
  72. int hybrid_maxclip, hybrid_minclip;
  73. int float_flag;
  74. int float_shift;
  75. int float_max_exp;
  76. WvChannel ch[2];
  77. GetByteContext gbyte;
  78. int ptable [PTABLE_BINS];
  79. uint8_t value_lookup_buffer[MAX_HISTORY_BINS*MAX_BIN_BYTES];
  80. uint16_t summed_probabilities[MAX_HISTORY_BINS][256];
  81. uint8_t probabilities[MAX_HISTORY_BINS][256];
  82. uint8_t *value_lookup[MAX_HISTORY_BINS];
  83. } WavpackFrameContext;
  84. #define WV_MAX_FRAME_DECODERS 14
  85. typedef struct WavpackContext {
  86. AVCodecContext *avctx;
  87. WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
  88. int fdec_num;
  89. int block;
  90. int samples;
  91. int ch_offset;
  92. AVFrame *frame;
  93. ThreadFrame curr_frame, prev_frame;
  94. Modulation modulation;
  95. DSDContext *dsdctx;
  96. } WavpackContext;
  97. #define LEVEL_DECAY(a) (((a) + 0x80) >> 8)
  98. static av_always_inline unsigned get_tail(GetBitContext *gb, int k)
  99. {
  100. int p, e, res;
  101. if (k < 1)
  102. return 0;
  103. p = av_log2(k);
  104. e = (1 << (p + 1)) - k - 1;
  105. res = get_bitsz(gb, p);
  106. if (res >= e)
  107. res = (res << 1) - e + get_bits1(gb);
  108. return res;
  109. }
  110. static int update_error_limit(WavpackFrameContext *ctx)
  111. {
  112. int i, br[2], sl[2];
  113. for (i = 0; i <= ctx->stereo_in; i++) {
  114. if (ctx->ch[i].bitrate_acc > UINT_MAX - ctx->ch[i].bitrate_delta)
  115. return AVERROR_INVALIDDATA;
  116. ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
  117. br[i] = ctx->ch[i].bitrate_acc >> 16;
  118. sl[i] = LEVEL_DECAY(ctx->ch[i].slow_level);
  119. }
  120. if (ctx->stereo_in && ctx->hybrid_bitrate) {
  121. int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
  122. if (balance > br[0]) {
  123. br[1] = br[0] * 2;
  124. br[0] = 0;
  125. } else if (-balance > br[0]) {
  126. br[0] *= 2;
  127. br[1] = 0;
  128. } else {
  129. br[1] = br[0] + balance;
  130. br[0] = br[0] - balance;
  131. }
  132. }
  133. for (i = 0; i <= ctx->stereo_in; i++) {
  134. if (ctx->hybrid_bitrate) {
  135. if (sl[i] - br[i] > -0x100)
  136. ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
  137. else
  138. ctx->ch[i].error_limit = 0;
  139. } else {
  140. ctx->ch[i].error_limit = wp_exp2(br[i]);
  141. }
  142. }
  143. return 0;
  144. }
  145. static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
  146. int channel, int *last)
  147. {
  148. int t, t2;
  149. int sign, base, add, ret;
  150. WvChannel *c = &ctx->ch[channel];
  151. *last = 0;
  152. if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
  153. !ctx->zero && !ctx->one) {
  154. if (ctx->zeroes) {
  155. ctx->zeroes--;
  156. if (ctx->zeroes) {
  157. c->slow_level -= LEVEL_DECAY(c->slow_level);
  158. return 0;
  159. }
  160. } else {
  161. t = get_unary_0_33(gb);
  162. if (t >= 2) {
  163. if (t >= 32 || get_bits_left(gb) < t - 1)
  164. goto error;
  165. t = get_bits_long(gb, t - 1) | (1 << (t - 1));
  166. } else {
  167. if (get_bits_left(gb) < 0)
  168. goto error;
  169. }
  170. ctx->zeroes = t;
  171. if (ctx->zeroes) {
  172. memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
  173. memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
  174. c->slow_level -= LEVEL_DECAY(c->slow_level);
  175. return 0;
  176. }
  177. }
  178. }
  179. if (ctx->zero) {
  180. t = 0;
  181. ctx->zero = 0;
  182. } else {
  183. t = get_unary_0_33(gb);
  184. if (get_bits_left(gb) < 0)
  185. goto error;
  186. if (t == 16) {
  187. t2 = get_unary_0_33(gb);
  188. if (t2 < 2) {
  189. if (get_bits_left(gb) < 0)
  190. goto error;
  191. t += t2;
  192. } else {
  193. if (t2 >= 32 || get_bits_left(gb) < t2 - 1)
  194. goto error;
  195. t += get_bits_long(gb, t2 - 1) | (1 << (t2 - 1));
  196. }
  197. }
  198. if (ctx->one) {
  199. ctx->one = t & 1;
  200. t = (t >> 1) + 1;
  201. } else {
  202. ctx->one = t & 1;
  203. t >>= 1;
  204. }
  205. ctx->zero = !ctx->one;
  206. }
  207. if (ctx->hybrid && !channel) {
  208. if (update_error_limit(ctx) < 0)
  209. goto error;
  210. }
  211. if (!t) {
  212. base = 0;
  213. add = GET_MED(0) - 1;
  214. DEC_MED(0);
  215. } else if (t == 1) {
  216. base = GET_MED(0);
  217. add = GET_MED(1) - 1;
  218. INC_MED(0);
  219. DEC_MED(1);
  220. } else if (t == 2) {
  221. base = GET_MED(0) + GET_MED(1);
  222. add = GET_MED(2) - 1;
  223. INC_MED(0);
  224. INC_MED(1);
  225. DEC_MED(2);
  226. } else {
  227. base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2U);
  228. add = GET_MED(2) - 1;
  229. INC_MED(0);
  230. INC_MED(1);
  231. INC_MED(2);
  232. }
  233. if (!c->error_limit) {
  234. if (add >= 0x2000000U) {
  235. av_log(ctx->avctx, AV_LOG_ERROR, "k %d is too large\n", add);
  236. goto error;
  237. }
  238. ret = base + get_tail(gb, add);
  239. if (get_bits_left(gb) <= 0)
  240. goto error;
  241. } else {
  242. int mid = (base * 2U + add + 1) >> 1;
  243. while (add > c->error_limit) {
  244. if (get_bits_left(gb) <= 0)
  245. goto error;
  246. if (get_bits1(gb)) {
  247. add -= (mid - (unsigned)base);
  248. base = mid;
  249. } else
  250. add = mid - (unsigned)base - 1;
  251. mid = (base * 2U + add + 1) >> 1;
  252. }
  253. ret = mid;
  254. }
  255. sign = get_bits1(gb);
  256. if (ctx->hybrid_bitrate)
  257. c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
  258. return sign ? ~ret : ret;
  259. error:
  260. ret = get_bits_left(gb);
  261. if (ret <= 0) {
  262. av_log(ctx->avctx, AV_LOG_ERROR, "Too few bits (%d) left\n", ret);
  263. }
  264. *last = 1;
  265. return 0;
  266. }
  267. static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
  268. unsigned S)
  269. {
  270. unsigned bit;
  271. if (s->extra_bits) {
  272. S *= 1 << s->extra_bits;
  273. if (s->got_extra_bits &&
  274. get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
  275. S |= get_bits_long(&s->gb_extra_bits, s->extra_bits);
  276. *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
  277. }
  278. }
  279. bit = (S & s->and) | s->or;
  280. bit = ((S + bit) << s->shift) - bit;
  281. if (s->hybrid)
  282. bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);
  283. return bit << s->post_shift;
  284. }
  285. static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
  286. {
  287. union {
  288. float f;
  289. uint32_t u;
  290. } value;
  291. unsigned int sign;
  292. int exp = s->float_max_exp;
  293. if (s->got_extra_bits) {
  294. const int max_bits = 1 + 23 + 8 + 1;
  295. const int left_bits = get_bits_left(&s->gb_extra_bits);
  296. if (left_bits + 8 * AV_INPUT_BUFFER_PADDING_SIZE < max_bits)
  297. return 0.0;
  298. }
  299. if (S) {
  300. S *= 1U << s->float_shift;
  301. sign = S < 0;
  302. if (sign)
  303. S = -(unsigned)S;
  304. if (S >= 0x1000000U) {
  305. if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
  306. S = get_bits(&s->gb_extra_bits, 23);
  307. else
  308. S = 0;
  309. exp = 255;
  310. } else if (exp) {
  311. int shift = 23 - av_log2(S);
  312. exp = s->float_max_exp;
  313. if (exp <= shift)
  314. shift = --exp;
  315. exp -= shift;
  316. if (shift) {
  317. S <<= shift;
  318. if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
  319. (s->got_extra_bits &&
  320. (s->float_flag & WV_FLT_SHIFT_SAME) &&
  321. get_bits1(&s->gb_extra_bits))) {
  322. S |= (1 << shift) - 1;
  323. } else if (s->got_extra_bits &&
  324. (s->float_flag & WV_FLT_SHIFT_SENT)) {
  325. S |= get_bits(&s->gb_extra_bits, shift);
  326. }
  327. }
  328. } else {
  329. exp = s->float_max_exp;
  330. }
  331. S &= 0x7fffff;
  332. } else {
  333. sign = 0;
  334. exp = 0;
  335. if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
  336. if (get_bits1(&s->gb_extra_bits)) {
  337. S = get_bits(&s->gb_extra_bits, 23);
  338. if (s->float_max_exp >= 25)
  339. exp = get_bits(&s->gb_extra_bits, 8);
  340. sign = get_bits1(&s->gb_extra_bits);
  341. } else {
  342. if (s->float_flag & WV_FLT_ZERO_SIGN)
  343. sign = get_bits1(&s->gb_extra_bits);
  344. }
  345. }
  346. }
  347. *crc = *crc * 27 + S * 9 + exp * 3 + sign;
  348. value.u = (sign << 31) | (exp << 23) | S;
  349. return value.f;
  350. }
  351. static inline int wv_check_crc(WavpackFrameContext *s, uint32_t crc,
  352. uint32_t crc_extra_bits)
  353. {
  354. if (crc != s->CRC) {
  355. av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
  356. return AVERROR_INVALIDDATA;
  357. }
  358. if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
  359. av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
  360. return AVERROR_INVALIDDATA;
  361. }
  362. return 0;
  363. }
  364. static void init_ptable(int *table, int rate_i, int rate_s)
  365. {
  366. int value = 0x808000, rate = rate_i << 8;
  367. for (int c = (rate + 128) >> 8; c--;)
  368. value += (DOWN - value) >> DECAY;
  369. for (int i = 0; i < PTABLE_BINS/2; i++) {
  370. table[i] = value;
  371. table[PTABLE_BINS-1-i] = 0x100ffff - value;
  372. if (value > 0x010000) {
  373. rate += (rate * rate_s + 128) >> 8;
  374. for (int c = (rate + 64) >> 7; c--;)
  375. value += (DOWN - value) >> DECAY;
  376. }
  377. }
  378. }
  379. typedef struct {
  380. int32_t value, fltr0, fltr1, fltr2, fltr3, fltr4, fltr5, fltr6, factor;
  381. unsigned int byte;
  382. } DSDfilters;
  383. static int wv_unpack_dsd_high(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
  384. {
  385. uint32_t checksum = 0xFFFFFFFF;
  386. uint8_t *dst_l = dst_left, *dst_r = dst_right;
  387. int total_samples = s->samples, stereo = dst_r ? 1 : 0;
  388. DSDfilters filters[2], *sp = filters;
  389. int rate_i, rate_s;
  390. uint32_t low, high, value;
  391. if (bytestream2_get_bytes_left(&s->gbyte) < (stereo ? 20 : 13))
  392. return AVERROR_INVALIDDATA;
  393. rate_i = bytestream2_get_byte(&s->gbyte);
  394. rate_s = bytestream2_get_byte(&s->gbyte);
  395. if (rate_s != RATE_S)
  396. return AVERROR_INVALIDDATA;
  397. init_ptable(s->ptable, rate_i, rate_s);
  398. for (int channel = 0; channel < stereo + 1; channel++) {
  399. DSDfilters *sp = filters + channel;
  400. sp->fltr1 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
  401. sp->fltr2 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
  402. sp->fltr3 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
  403. sp->fltr4 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
  404. sp->fltr5 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
  405. sp->fltr6 = 0;
  406. sp->factor = bytestream2_get_byte(&s->gbyte) & 0xff;
  407. sp->factor |= (bytestream2_get_byte(&s->gbyte) << 8) & 0xff00;
  408. sp->factor = (int32_t)((uint32_t)sp->factor << 16) >> 16;
  409. }
  410. value = bytestream2_get_be32(&s->gbyte);
  411. high = 0xffffffff;
  412. low = 0x0;
  413. while (total_samples--) {
  414. int bitcount = 8;
  415. sp[0].value = sp[0].fltr1 - sp[0].fltr5 + ((sp[0].fltr6 * sp[0].factor) >> 2);
  416. if (stereo)
  417. sp[1].value = sp[1].fltr1 - sp[1].fltr5 + ((sp[1].fltr6 * sp[1].factor) >> 2);
  418. while (bitcount--) {
  419. int32_t *pp = s->ptable + ((sp[0].value >> (PRECISION - PRECISION_USE)) & PTABLE_MASK);
  420. uint32_t split = low + ((high - low) >> 8) * (*pp >> 16);
  421. if (value <= split) {
  422. high = split;
  423. *pp += (UP - *pp) >> DECAY;
  424. sp[0].fltr0 = -1;
  425. } else {
  426. low = split + 1;
  427. *pp += (DOWN - *pp) >> DECAY;
  428. sp[0].fltr0 = 0;
  429. }
  430. while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
  431. value = (value << 8) | bytestream2_get_byte(&s->gbyte);
  432. high = (high << 8) | 0xff;
  433. low <<= 8;
  434. }
  435. sp[0].value += sp[0].fltr6 * 8;
  436. sp[0].byte = (sp[0].byte << 1) | (sp[0].fltr0 & 1);
  437. sp[0].factor += (((sp[0].value ^ sp[0].fltr0) >> 31) | 1) &
  438. ((sp[0].value ^ (sp[0].value - (sp[0].fltr6 * 16))) >> 31);
  439. sp[0].fltr1 += ((sp[0].fltr0 & VALUE_ONE) - sp[0].fltr1) >> 6;
  440. sp[0].fltr2 += ((sp[0].fltr0 & VALUE_ONE) - sp[0].fltr2) >> 4;
  441. sp[0].fltr3 += (sp[0].fltr2 - sp[0].fltr3) >> 4;
  442. sp[0].fltr4 += (sp[0].fltr3 - sp[0].fltr4) >> 4;
  443. sp[0].value = (sp[0].fltr4 - sp[0].fltr5) >> 4;
  444. sp[0].fltr5 += sp[0].value;
  445. sp[0].fltr6 += (sp[0].value - sp[0].fltr6) >> 3;
  446. sp[0].value = sp[0].fltr1 - sp[0].fltr5 + ((sp[0].fltr6 * sp[0].factor) >> 2);
  447. if (!stereo)
  448. continue;
  449. pp = s->ptable + ((sp[1].value >> (PRECISION - PRECISION_USE)) & PTABLE_MASK);
  450. split = low + ((high - low) >> 8) * (*pp >> 16);
  451. if (value <= split) {
  452. high = split;
  453. *pp += (UP - *pp) >> DECAY;
  454. sp[1].fltr0 = -1;
  455. } else {
  456. low = split + 1;
  457. *pp += (DOWN - *pp) >> DECAY;
  458. sp[1].fltr0 = 0;
  459. }
  460. while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
  461. value = (value << 8) | bytestream2_get_byte(&s->gbyte);
  462. high = (high << 8) | 0xff;
  463. low <<= 8;
  464. }
  465. sp[1].value += sp[1].fltr6 * 8;
  466. sp[1].byte = (sp[1].byte << 1) | (sp[1].fltr0 & 1);
  467. sp[1].factor += (((sp[1].value ^ sp[1].fltr0) >> 31) | 1) &
  468. ((sp[1].value ^ (sp[1].value - (sp[1].fltr6 * 16))) >> 31);
  469. sp[1].fltr1 += ((sp[1].fltr0 & VALUE_ONE) - sp[1].fltr1) >> 6;
  470. sp[1].fltr2 += ((sp[1].fltr0 & VALUE_ONE) - sp[1].fltr2) >> 4;
  471. sp[1].fltr3 += (sp[1].fltr2 - sp[1].fltr3) >> 4;
  472. sp[1].fltr4 += (sp[1].fltr3 - sp[1].fltr4) >> 4;
  473. sp[1].value = (sp[1].fltr4 - sp[1].fltr5) >> 4;
  474. sp[1].fltr5 += sp[1].value;
  475. sp[1].fltr6 += (sp[1].value - sp[1].fltr6) >> 3;
  476. sp[1].value = sp[1].fltr1 - sp[1].fltr5 + ((sp[1].fltr6 * sp[1].factor) >> 2);
  477. }
  478. checksum += (checksum << 1) + (*dst_l = sp[0].byte & 0xff);
  479. sp[0].factor -= (sp[0].factor + 512) >> 10;
  480. dst_l += 4;
  481. if (stereo) {
  482. checksum += (checksum << 1) + (*dst_r = filters[1].byte & 0xff);
  483. filters[1].factor -= (filters[1].factor + 512) >> 10;
  484. dst_r += 4;
  485. }
  486. }
  487. if (wv_check_crc(s, checksum, 0)) {
  488. if (s->avctx->err_recognition & AV_EF_CRCCHECK)
  489. return AVERROR_INVALIDDATA;
  490. memset(dst_left, 0x69, s->samples * 4);
  491. if (dst_r)
  492. memset(dst_right, 0x69, s->samples * 4);
  493. }
  494. return 0;
  495. }
  496. static int wv_unpack_dsd_fast(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
  497. {
  498. uint8_t *dst_l = dst_left, *dst_r = dst_right;
  499. uint8_t history_bits, max_probability;
  500. int total_summed_probabilities = 0;
  501. int total_samples = s->samples;
  502. uint8_t *vlb = s->value_lookup_buffer;
  503. int history_bins, p0, p1, chan;
  504. uint32_t checksum = 0xFFFFFFFF;
  505. uint32_t low, high, value;
  506. if (!bytestream2_get_bytes_left(&s->gbyte))
  507. return AVERROR_INVALIDDATA;
  508. history_bits = bytestream2_get_byte(&s->gbyte);
  509. if (!bytestream2_get_bytes_left(&s->gbyte) || history_bits > MAX_HISTORY_BITS)
  510. return AVERROR_INVALIDDATA;
  511. history_bins = 1 << history_bits;
  512. max_probability = bytestream2_get_byte(&s->gbyte);
  513. if (max_probability < 0xff) {
  514. uint8_t *outptr = (uint8_t *) s->probabilities;
  515. uint8_t *outend = outptr + sizeof (*s->probabilities) * history_bins;
  516. while (outptr < outend && bytestream2_get_bytes_left(&s->gbyte)) {
  517. int code = bytestream2_get_byte(&s->gbyte);
  518. if (code > max_probability) {
  519. int zcount = code - max_probability;
  520. while (outptr < outend && zcount--)
  521. *outptr++ = 0;
  522. } else if (code) {
  523. *outptr++ = code;
  524. }
  525. else {
  526. break;
  527. }
  528. }
  529. if (outptr < outend ||
  530. (bytestream2_get_bytes_left(&s->gbyte) && bytestream2_get_byte(&s->gbyte)))
  531. return AVERROR_INVALIDDATA;
  532. } else if (bytestream2_get_bytes_left(&s->gbyte) > (int) sizeof (*s->probabilities) * history_bins) {
  533. bytestream2_get_buffer(&s->gbyte, (uint8_t *) s->probabilities,
  534. sizeof (*s->probabilities) * history_bins);
  535. } else {
  536. return AVERROR_INVALIDDATA;
  537. }
  538. for (p0 = 0; p0 < history_bins; p0++) {
  539. int32_t sum_values = 0;
  540. for (int i = 0; i < 256; i++)
  541. s->summed_probabilities[p0][i] = sum_values += s->probabilities[p0][i];
  542. if (sum_values) {
  543. total_summed_probabilities += sum_values;
  544. if (total_summed_probabilities > history_bins * MAX_BIN_BYTES)
  545. return AVERROR_INVALIDDATA;
  546. s->value_lookup[p0] = vlb;
  547. for (int i = 0; i < 256; i++) {
  548. int c = s->probabilities[p0][i];
  549. while (c--)
  550. *vlb++ = i;
  551. }
  552. }
  553. }
  554. if (bytestream2_get_bytes_left(&s->gbyte) < 4)
  555. return AVERROR_INVALIDDATA;
  556. chan = p0 = p1 = 0;
  557. low = 0; high = 0xffffffff;
  558. value = bytestream2_get_be32(&s->gbyte);
  559. if (dst_r)
  560. total_samples *= 2;
  561. while (total_samples--) {
  562. unsigned int mult, index, code;
  563. if (!s->summed_probabilities[p0][255])
  564. return AVERROR_INVALIDDATA;
  565. mult = (high - low) / s->summed_probabilities[p0][255];
  566. if (!mult) {
  567. if (bytestream2_get_bytes_left(&s->gbyte) >= 4)
  568. value = bytestream2_get_be32(&s->gbyte);
  569. low = 0;
  570. high = 0xffffffff;
  571. mult = high / s->summed_probabilities[p0][255];
  572. if (!mult)
  573. return AVERROR_INVALIDDATA;
  574. }
  575. index = (value - low) / mult;
  576. if (index >= s->summed_probabilities[p0][255])
  577. return AVERROR_INVALIDDATA;
  578. if (!dst_r) {
  579. if ((*dst_l = code = s->value_lookup[p0][index]))
  580. low += s->summed_probabilities[p0][code-1] * mult;
  581. dst_l += 4;
  582. } else {
  583. if ((code = s->value_lookup[p0][index]))
  584. low += s->summed_probabilities[p0][code-1] * mult;
  585. if (chan) {
  586. *dst_r = code;
  587. dst_r += 4;
  588. }
  589. else {
  590. *dst_l = code;
  591. dst_l += 4;
  592. }
  593. chan ^= 1;
  594. }
  595. high = low + s->probabilities[p0][code] * mult - 1;
  596. checksum += (checksum << 1) + code;
  597. if (!dst_r) {
  598. p0 = code & (history_bins-1);
  599. } else {
  600. p0 = p1;
  601. p1 = code & (history_bins-1);
  602. }
  603. while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
  604. value = (value << 8) | bytestream2_get_byte(&s->gbyte);
  605. high = (high << 8) | 0xff;
  606. low <<= 8;
  607. }
  608. }
  609. if (wv_check_crc(s, checksum, 0)) {
  610. if (s->avctx->err_recognition & AV_EF_CRCCHECK)
  611. return AVERROR_INVALIDDATA;
  612. memset(dst_left, 0x69, s->samples * 4);
  613. if (dst_r)
  614. memset(dst_right, 0x69, s->samples * 4);
  615. }
  616. return 0;
  617. }
  618. static int wv_unpack_dsd_copy(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
  619. {
  620. uint8_t *dst_l = dst_left, *dst_r = dst_right;
  621. int total_samples = s->samples;
  622. uint32_t checksum = 0xFFFFFFFF;
  623. if (bytestream2_get_bytes_left(&s->gbyte) != total_samples * (dst_r ? 2 : 1))
  624. return AVERROR_INVALIDDATA;
  625. while (total_samples--) {
  626. checksum += (checksum << 1) + (*dst_l = bytestream2_get_byte(&s->gbyte));
  627. dst_l += 4;
  628. if (dst_r) {
  629. checksum += (checksum << 1) + (*dst_r = bytestream2_get_byte(&s->gbyte));
  630. dst_r += 4;
  631. }
  632. }
  633. if (wv_check_crc(s, checksum, 0)) {
  634. if (s->avctx->err_recognition & AV_EF_CRCCHECK)
  635. return AVERROR_INVALIDDATA;
  636. memset(dst_left, 0x69, s->samples * 4);
  637. if (dst_r)
  638. memset(dst_right, 0x69, s->samples * 4);
  639. }
  640. return 0;
  641. }
  642. static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
  643. void *dst_l, void *dst_r, const int type)
  644. {
  645. int i, j, count = 0;
  646. int last, t;
  647. int A, B, L, L2, R, R2;
  648. int pos = 0;
  649. uint32_t crc = 0xFFFFFFFF;
  650. uint32_t crc_extra_bits = 0xFFFFFFFF;
  651. int16_t *dst16_l = dst_l;
  652. int16_t *dst16_r = dst_r;
  653. int32_t *dst32_l = dst_l;
  654. int32_t *dst32_r = dst_r;
  655. float *dstfl_l = dst_l;
  656. float *dstfl_r = dst_r;
  657. s->one = s->zero = s->zeroes = 0;
  658. do {
  659. L = wv_get_value(s, gb, 0, &last);
  660. if (last)
  661. break;
  662. R = wv_get_value(s, gb, 1, &last);
  663. if (last)
  664. break;
  665. for (i = 0; i < s->terms; i++) {
  666. t = s->decorr[i].value;
  667. if (t > 0) {
  668. if (t > 8) {
  669. if (t & 1) {
  670. A = 2U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
  671. B = 2U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
  672. } else {
  673. A = (int)(3U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
  674. B = (int)(3U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
  675. }
  676. s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
  677. s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
  678. j = 0;
  679. } else {
  680. A = s->decorr[i].samplesA[pos];
  681. B = s->decorr[i].samplesB[pos];
  682. j = (pos + t) & 7;
  683. }
  684. if (type != AV_SAMPLE_FMT_S16P) {
  685. L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
  686. R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
  687. } else {
  688. L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10);
  689. R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)B + 512) >> 10);
  690. }
  691. if (A && L)
  692. s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
  693. if (B && R)
  694. s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
  695. s->decorr[i].samplesA[j] = L = L2;
  696. s->decorr[i].samplesB[j] = R = R2;
  697. } else if (t == -1) {
  698. if (type != AV_SAMPLE_FMT_S16P)
  699. L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
  700. else
  701. L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)s->decorr[i].samplesA[0] + 512) >> 10);
  702. UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
  703. L = L2;
  704. if (type != AV_SAMPLE_FMT_S16P)
  705. R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
  706. else
  707. R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)L2 + 512) >> 10);
  708. UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
  709. R = R2;
  710. s->decorr[i].samplesA[0] = R;
  711. } else {
  712. if (type != AV_SAMPLE_FMT_S16P)
  713. R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
  714. else
  715. R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)s->decorr[i].samplesB[0] + 512) >> 10);
  716. UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
  717. R = R2;
  718. if (t == -3) {
  719. R2 = s->decorr[i].samplesA[0];
  720. s->decorr[i].samplesA[0] = R;
  721. }
  722. if (type != AV_SAMPLE_FMT_S16P)
  723. L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
  724. else
  725. L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)R2 + 512) >> 10);
  726. UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
  727. L = L2;
  728. s->decorr[i].samplesB[0] = L;
  729. }
  730. }
  731. if (type == AV_SAMPLE_FMT_S16P) {
  732. if (FFABS((int64_t)L) + FFABS((int64_t)R) > (1<<19)) {
  733. av_log(s->avctx, AV_LOG_ERROR, "sample %d %d too large\n", L, R);
  734. return AVERROR_INVALIDDATA;
  735. }
  736. }
  737. pos = (pos + 1) & 7;
  738. if (s->joint)
  739. L += (unsigned)(R -= (unsigned)(L >> 1));
  740. crc = (crc * 3 + L) * 3 + R;
  741. if (type == AV_SAMPLE_FMT_FLTP) {
  742. *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);
  743. *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);
  744. } else if (type == AV_SAMPLE_FMT_S32P) {
  745. *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
  746. *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
  747. } else {
  748. *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
  749. *dst16_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
  750. }
  751. count++;
  752. } while (!last && count < s->samples);
  753. if (last && count < s->samples) {
  754. int size = av_get_bytes_per_sample(type);
  755. memset((uint8_t*)dst_l + count*size, 0, (s->samples-count)*size);
  756. memset((uint8_t*)dst_r + count*size, 0, (s->samples-count)*size);
  757. }
  758. if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
  759. wv_check_crc(s, crc, crc_extra_bits))
  760. return AVERROR_INVALIDDATA;
  761. return 0;
  762. }
  763. static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
  764. void *dst, const int type)
  765. {
  766. int i, j, count = 0;
  767. int last, t;
  768. int A, S, T;
  769. int pos = 0;
  770. uint32_t crc = 0xFFFFFFFF;
  771. uint32_t crc_extra_bits = 0xFFFFFFFF;
  772. int16_t *dst16 = dst;
  773. int32_t *dst32 = dst;
  774. float *dstfl = dst;
  775. s->one = s->zero = s->zeroes = 0;
  776. do {
  777. T = wv_get_value(s, gb, 0, &last);
  778. S = 0;
  779. if (last)
  780. break;
  781. for (i = 0; i < s->terms; i++) {
  782. t = s->decorr[i].value;
  783. if (t > 8) {
  784. if (t & 1)
  785. A = 2U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
  786. else
  787. A = (int)(3U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
  788. s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
  789. j = 0;
  790. } else {
  791. A = s->decorr[i].samplesA[pos];
  792. j = (pos + t) & 7;
  793. }
  794. if (type != AV_SAMPLE_FMT_S16P)
  795. S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
  796. else
  797. S = T + (unsigned)((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10);
  798. if (A && T)
  799. s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
  800. s->decorr[i].samplesA[j] = T = S;
  801. }
  802. pos = (pos + 1) & 7;
  803. crc = crc * 3 + S;
  804. if (type == AV_SAMPLE_FMT_FLTP) {
  805. *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
  806. } else if (type == AV_SAMPLE_FMT_S32P) {
  807. *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
  808. } else {
  809. *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
  810. }
  811. count++;
  812. } while (!last && count < s->samples);
  813. if (last && count < s->samples) {
  814. int size = av_get_bytes_per_sample(type);
  815. memset((uint8_t*)dst + count*size, 0, (s->samples-count)*size);
  816. }
  817. if (s->avctx->err_recognition & AV_EF_CRCCHECK) {
  818. int ret = wv_check_crc(s, crc, crc_extra_bits);
  819. if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)
  820. return ret;
  821. }
  822. return 0;
  823. }
  824. static av_cold int wv_alloc_frame_context(WavpackContext *c)
  825. {
  826. if (c->fdec_num == WV_MAX_FRAME_DECODERS)
  827. return -1;
  828. c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
  829. if (!c->fdec[c->fdec_num])
  830. return -1;
  831. c->fdec_num++;
  832. c->fdec[c->fdec_num - 1]->avctx = c->avctx;
  833. return 0;
  834. }
  835. #if HAVE_THREADS
  836. static int init_thread_copy(AVCodecContext *avctx)
  837. {
  838. WavpackContext *s = avctx->priv_data;
  839. s->avctx = avctx;
  840. s->curr_frame.f = av_frame_alloc();
  841. s->prev_frame.f = av_frame_alloc();
  842. return 0;
  843. }
  844. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  845. {
  846. WavpackContext *fsrc = src->priv_data;
  847. WavpackContext *fdst = dst->priv_data;
  848. int ret;
  849. if (dst == src)
  850. return 0;
  851. ff_thread_release_buffer(dst, &fdst->curr_frame);
  852. if (fsrc->curr_frame.f->data[0]) {
  853. if ((ret = ff_thread_ref_frame(&fdst->curr_frame, &fsrc->curr_frame)) < 0)
  854. return ret;
  855. }
  856. return 0;
  857. }
  858. #endif
  859. static av_cold int wavpack_decode_init(AVCodecContext *avctx)
  860. {
  861. WavpackContext *s = avctx->priv_data;
  862. s->avctx = avctx;
  863. s->fdec_num = 0;
  864. avctx->internal->allocate_progress = 1;
  865. s->curr_frame.f = av_frame_alloc();
  866. s->prev_frame.f = av_frame_alloc();
  867. // the DSD to PCM context is shared (and used serially) between all decoding threads
  868. s->dsdctx = av_calloc(avctx->channels, sizeof (DSDContext));
  869. if (!s->curr_frame.f || !s->prev_frame.f || !s->dsdctx)
  870. return AVERROR(ENOMEM);
  871. for (int i = 0; i < avctx->channels; i++)
  872. memset(s->dsdctx[i].buf, 0x69, sizeof(s->dsdctx[i].buf));
  873. ff_init_dsd_data();
  874. return 0;
  875. }
  876. static av_cold int wavpack_decode_end(AVCodecContext *avctx)
  877. {
  878. WavpackContext *s = avctx->priv_data;
  879. for (int i = 0; i < s->fdec_num; i++)
  880. av_freep(&s->fdec[i]);
  881. s->fdec_num = 0;
  882. ff_thread_release_buffer(avctx, &s->curr_frame);
  883. av_frame_free(&s->curr_frame.f);
  884. ff_thread_release_buffer(avctx, &s->prev_frame);
  885. av_frame_free(&s->prev_frame.f);
  886. if (!avctx->internal->is_copy)
  887. av_freep(&s->dsdctx);
  888. return 0;
  889. }
  890. static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
  891. const uint8_t *buf, int buf_size)
  892. {
  893. WavpackContext *wc = avctx->priv_data;
  894. WavpackFrameContext *s;
  895. GetByteContext gb;
  896. void *samples_l = NULL, *samples_r = NULL;
  897. int ret;
  898. int got_terms = 0, got_weights = 0, got_samples = 0,
  899. got_entropy = 0, got_pcm = 0, got_float = 0, got_hybrid = 0;
  900. int got_dsd = 0;
  901. int i, j, id, size, ssize, weights, t;
  902. int bpp, chan = 0, orig_bpp, sample_rate = 0, rate_x = 1, dsd_mode = 0;
  903. int multiblock;
  904. uint64_t chmask = 0;
  905. if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
  906. av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
  907. return AVERROR_INVALIDDATA;
  908. }
  909. s = wc->fdec[block_no];
  910. if (!s) {
  911. av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
  912. block_no);
  913. return AVERROR_INVALIDDATA;
  914. }
  915. memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
  916. memset(s->ch, 0, sizeof(s->ch));
  917. s->extra_bits = 0;
  918. s->and = s->or = s->shift = 0;
  919. s->got_extra_bits = 0;
  920. bytestream2_init(&gb, buf, buf_size);
  921. s->samples = bytestream2_get_le32(&gb);
  922. if (s->samples != wc->samples) {
  923. av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
  924. "a sequence: %d and %d\n", wc->samples, s->samples);
  925. return AVERROR_INVALIDDATA;
  926. }
  927. s->frame_flags = bytestream2_get_le32(&gb);
  928. bpp = av_get_bytes_per_sample(avctx->sample_fmt);
  929. orig_bpp = ((s->frame_flags & 0x03) + 1) << 3;
  930. multiblock = (s->frame_flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK;
  931. s->stereo = !(s->frame_flags & WV_MONO);
  932. s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
  933. s->joint = s->frame_flags & WV_JOINT_STEREO;
  934. s->hybrid = s->frame_flags & WV_HYBRID_MODE;
  935. s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
  936. s->post_shift = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
  937. if (s->post_shift < 0 || s->post_shift > 31) {
  938. return AVERROR_INVALIDDATA;
  939. }
  940. s->hybrid_maxclip = ((1LL << (orig_bpp - 1)) - 1);
  941. s->hybrid_minclip = ((-1UL << (orig_bpp - 1)));
  942. s->CRC = bytestream2_get_le32(&gb);
  943. // parse metadata blocks
  944. while (bytestream2_get_bytes_left(&gb)) {
  945. id = bytestream2_get_byte(&gb);
  946. size = bytestream2_get_byte(&gb);
  947. if (id & WP_IDF_LONG)
  948. size |= (bytestream2_get_le16u(&gb)) << 8;
  949. size <<= 1; // size is specified in words
  950. ssize = size;
  951. if (id & WP_IDF_ODD)
  952. size--;
  953. if (size < 0) {
  954. av_log(avctx, AV_LOG_ERROR,
  955. "Got incorrect block %02X with size %i\n", id, size);
  956. break;
  957. }
  958. if (bytestream2_get_bytes_left(&gb) < ssize) {
  959. av_log(avctx, AV_LOG_ERROR,
  960. "Block size %i is out of bounds\n", size);
  961. break;
  962. }
  963. switch (id & WP_IDF_MASK) {
  964. case WP_ID_DECTERMS:
  965. if (size > MAX_TERMS) {
  966. av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
  967. s->terms = 0;
  968. bytestream2_skip(&gb, ssize);
  969. continue;
  970. }
  971. s->terms = size;
  972. for (i = 0; i < s->terms; i++) {
  973. uint8_t val = bytestream2_get_byte(&gb);
  974. s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
  975. s->decorr[s->terms - i - 1].delta = val >> 5;
  976. }
  977. got_terms = 1;
  978. break;
  979. case WP_ID_DECWEIGHTS:
  980. if (!got_terms) {
  981. av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
  982. continue;
  983. }
  984. weights = size >> s->stereo_in;
  985. if (weights > MAX_TERMS || weights > s->terms) {
  986. av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
  987. bytestream2_skip(&gb, ssize);
  988. continue;
  989. }
  990. for (i = 0; i < weights; i++) {
  991. t = (int8_t)bytestream2_get_byte(&gb);
  992. s->decorr[s->terms - i - 1].weightA = t * (1 << 3);
  993. if (s->decorr[s->terms - i - 1].weightA > 0)
  994. s->decorr[s->terms - i - 1].weightA +=
  995. (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
  996. if (s->stereo_in) {
  997. t = (int8_t)bytestream2_get_byte(&gb);
  998. s->decorr[s->terms - i - 1].weightB = t * (1 << 3);
  999. if (s->decorr[s->terms - i - 1].weightB > 0)
  1000. s->decorr[s->terms - i - 1].weightB +=
  1001. (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
  1002. }
  1003. }
  1004. got_weights = 1;
  1005. break;
  1006. case WP_ID_DECSAMPLES:
  1007. if (!got_terms) {
  1008. av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
  1009. continue;
  1010. }
  1011. t = 0;
  1012. for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
  1013. if (s->decorr[i].value > 8) {
  1014. s->decorr[i].samplesA[0] =
  1015. wp_exp2(bytestream2_get_le16(&gb));
  1016. s->decorr[i].samplesA[1] =
  1017. wp_exp2(bytestream2_get_le16(&gb));
  1018. if (s->stereo_in) {
  1019. s->decorr[i].samplesB[0] =
  1020. wp_exp2(bytestream2_get_le16(&gb));
  1021. s->decorr[i].samplesB[1] =
  1022. wp_exp2(bytestream2_get_le16(&gb));
  1023. t += 4;
  1024. }
  1025. t += 4;
  1026. } else if (s->decorr[i].value < 0) {
  1027. s->decorr[i].samplesA[0] =
  1028. wp_exp2(bytestream2_get_le16(&gb));
  1029. s->decorr[i].samplesB[0] =
  1030. wp_exp2(bytestream2_get_le16(&gb));
  1031. t += 4;
  1032. } else {
  1033. for (j = 0; j < s->decorr[i].value; j++) {
  1034. s->decorr[i].samplesA[j] =
  1035. wp_exp2(bytestream2_get_le16(&gb));
  1036. if (s->stereo_in) {
  1037. s->decorr[i].samplesB[j] =
  1038. wp_exp2(bytestream2_get_le16(&gb));
  1039. }
  1040. }
  1041. t += s->decorr[i].value * 2 * (s->stereo_in + 1);
  1042. }
  1043. }
  1044. got_samples = 1;
  1045. break;
  1046. case WP_ID_ENTROPY:
  1047. if (size != 6 * (s->stereo_in + 1)) {
  1048. av_log(avctx, AV_LOG_ERROR,
  1049. "Entropy vars size should be %i, got %i.\n",
  1050. 6 * (s->stereo_in + 1), size);
  1051. bytestream2_skip(&gb, ssize);
  1052. continue;
  1053. }
  1054. for (j = 0; j <= s->stereo_in; j++)
  1055. for (i = 0; i < 3; i++) {
  1056. s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
  1057. }
  1058. got_entropy = 1;
  1059. break;
  1060. case WP_ID_HYBRID:
  1061. if (s->hybrid_bitrate) {
  1062. for (i = 0; i <= s->stereo_in; i++) {
  1063. s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
  1064. size -= 2;
  1065. }
  1066. }
  1067. for (i = 0; i < (s->stereo_in + 1); i++) {
  1068. s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
  1069. size -= 2;
  1070. }
  1071. if (size > 0) {
  1072. for (i = 0; i < (s->stereo_in + 1); i++) {
  1073. s->ch[i].bitrate_delta =
  1074. wp_exp2((int16_t)bytestream2_get_le16(&gb));
  1075. }
  1076. } else {
  1077. for (i = 0; i < (s->stereo_in + 1); i++)
  1078. s->ch[i].bitrate_delta = 0;
  1079. }
  1080. got_hybrid = 1;
  1081. break;
  1082. case WP_ID_INT32INFO: {
  1083. uint8_t val[4];
  1084. if (size != 4) {
  1085. av_log(avctx, AV_LOG_ERROR,
  1086. "Invalid INT32INFO, size = %i\n",
  1087. size);
  1088. bytestream2_skip(&gb, ssize - 4);
  1089. continue;
  1090. }
  1091. bytestream2_get_buffer(&gb, val, 4);
  1092. if (val[0] > 30) {
  1093. av_log(avctx, AV_LOG_ERROR,
  1094. "Invalid INT32INFO, extra_bits = %d (> 30)\n", val[0]);
  1095. continue;
  1096. } else if (val[0]) {
  1097. s->extra_bits = val[0];
  1098. } else if (val[1]) {
  1099. s->shift = val[1];
  1100. } else if (val[2]) {
  1101. s->and = s->or = 1;
  1102. s->shift = val[2];
  1103. } else if (val[3]) {
  1104. s->and = 1;
  1105. s->shift = val[3];
  1106. }
  1107. if (s->shift > 31) {
  1108. av_log(avctx, AV_LOG_ERROR,
  1109. "Invalid INT32INFO, shift = %d (> 31)\n", s->shift);
  1110. s->and = s->or = s->shift = 0;
  1111. continue;
  1112. }
  1113. /* original WavPack decoder forces 32-bit lossy sound to be treated
  1114. * as 24-bit one in order to have proper clipping */
  1115. if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
  1116. s->post_shift += 8;
  1117. s->shift -= 8;
  1118. s->hybrid_maxclip >>= 8;
  1119. s->hybrid_minclip >>= 8;
  1120. }
  1121. break;
  1122. }
  1123. case WP_ID_FLOATINFO:
  1124. if (size != 4) {
  1125. av_log(avctx, AV_LOG_ERROR,
  1126. "Invalid FLOATINFO, size = %i\n", size);
  1127. bytestream2_skip(&gb, ssize);
  1128. continue;
  1129. }
  1130. s->float_flag = bytestream2_get_byte(&gb);
  1131. s->float_shift = bytestream2_get_byte(&gb);
  1132. s->float_max_exp = bytestream2_get_byte(&gb);
  1133. if (s->float_shift > 31) {
  1134. av_log(avctx, AV_LOG_ERROR,
  1135. "Invalid FLOATINFO, shift = %d (> 31)\n", s->float_shift);
  1136. s->float_shift = 0;
  1137. continue;
  1138. }
  1139. got_float = 1;
  1140. bytestream2_skip(&gb, 1);
  1141. break;
  1142. case WP_ID_DATA:
  1143. if ((ret = init_get_bits8(&s->gb, gb.buffer, size)) < 0)
  1144. return ret;
  1145. bytestream2_skip(&gb, size);
  1146. got_pcm = 1;
  1147. break;
  1148. case WP_ID_DSD_DATA:
  1149. if (size < 2) {
  1150. av_log(avctx, AV_LOG_ERROR, "Invalid DSD_DATA, size = %i\n",
  1151. size);
  1152. bytestream2_skip(&gb, ssize);
  1153. continue;
  1154. }
  1155. rate_x = 1 << bytestream2_get_byte(&gb);
  1156. dsd_mode = bytestream2_get_byte(&gb);
  1157. if (dsd_mode && dsd_mode != 1 && dsd_mode != 3) {
  1158. av_log(avctx, AV_LOG_ERROR, "Invalid DSD encoding mode: %d\n",
  1159. dsd_mode);
  1160. return AVERROR_INVALIDDATA;
  1161. }
  1162. bytestream2_init(&s->gbyte, gb.buffer, size-2);
  1163. bytestream2_skip(&gb, size-2);
  1164. got_dsd = 1;
  1165. break;
  1166. case WP_ID_EXTRABITS:
  1167. if (size <= 4) {
  1168. av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
  1169. size);
  1170. bytestream2_skip(&gb, size);
  1171. continue;
  1172. }
  1173. if ((ret = init_get_bits8(&s->gb_extra_bits, gb.buffer, size)) < 0)
  1174. return ret;
  1175. s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);
  1176. bytestream2_skip(&gb, size);
  1177. s->got_extra_bits = 1;
  1178. break;
  1179. case WP_ID_CHANINFO:
  1180. if (size <= 1) {
  1181. av_log(avctx, AV_LOG_ERROR,
  1182. "Insufficient channel information\n");
  1183. return AVERROR_INVALIDDATA;
  1184. }
  1185. chan = bytestream2_get_byte(&gb);
  1186. switch (size - 2) {
  1187. case 0:
  1188. chmask = bytestream2_get_byte(&gb);
  1189. break;
  1190. case 1:
  1191. chmask = bytestream2_get_le16(&gb);
  1192. break;
  1193. case 2:
  1194. chmask = bytestream2_get_le24(&gb);
  1195. break;
  1196. case 3:
  1197. chmask = bytestream2_get_le32(&gb);
  1198. break;
  1199. case 4:
  1200. size = bytestream2_get_byte(&gb);
  1201. chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
  1202. chan += 1;
  1203. if (avctx->channels != chan)
  1204. av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
  1205. " instead of %i.\n", chan, avctx->channels);
  1206. chmask = bytestream2_get_le24(&gb);
  1207. break;
  1208. case 5:
  1209. size = bytestream2_get_byte(&gb);
  1210. chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
  1211. chan += 1;
  1212. if (avctx->channels != chan)
  1213. av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
  1214. " instead of %i.\n", chan, avctx->channels);
  1215. chmask = bytestream2_get_le32(&gb);
  1216. break;
  1217. default:
  1218. av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
  1219. size);
  1220. chan = avctx->channels;
  1221. chmask = avctx->channel_layout;
  1222. }
  1223. break;
  1224. case WP_ID_SAMPLE_RATE:
  1225. if (size != 3) {
  1226. av_log(avctx, AV_LOG_ERROR, "Invalid custom sample rate.\n");
  1227. return AVERROR_INVALIDDATA;
  1228. }
  1229. sample_rate = bytestream2_get_le24(&gb);
  1230. break;
  1231. default:
  1232. bytestream2_skip(&gb, size);
  1233. }
  1234. if (id & WP_IDF_ODD)
  1235. bytestream2_skip(&gb, 1);
  1236. }
  1237. if (got_pcm) {
  1238. if (!got_terms) {
  1239. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
  1240. return AVERROR_INVALIDDATA;
  1241. }
  1242. if (!got_weights) {
  1243. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
  1244. return AVERROR_INVALIDDATA;
  1245. }
  1246. if (!got_samples) {
  1247. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
  1248. return AVERROR_INVALIDDATA;
  1249. }
  1250. if (!got_entropy) {
  1251. av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
  1252. return AVERROR_INVALIDDATA;
  1253. }
  1254. if (s->hybrid && !got_hybrid) {
  1255. av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
  1256. return AVERROR_INVALIDDATA;
  1257. }
  1258. if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
  1259. av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
  1260. return AVERROR_INVALIDDATA;
  1261. }
  1262. if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLTP) {
  1263. const int size = get_bits_left(&s->gb_extra_bits);
  1264. const int wanted = s->samples * s->extra_bits << s->stereo_in;
  1265. if (size < wanted) {
  1266. av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
  1267. s->got_extra_bits = 0;
  1268. }
  1269. }
  1270. }
  1271. if (!got_pcm && !got_dsd) {
  1272. av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
  1273. return AVERROR_INVALIDDATA;
  1274. }
  1275. if ((got_pcm && wc->modulation != MODULATION_PCM) ||
  1276. (got_dsd && wc->modulation != MODULATION_DSD)) {
  1277. av_log(avctx, AV_LOG_ERROR, "Invalid PCM/DSD mix encountered\n");
  1278. return AVERROR_INVALIDDATA;
  1279. }
  1280. if (!wc->ch_offset) {
  1281. int sr = (s->frame_flags >> 23) & 0xf;
  1282. if (sr == 0xf) {
  1283. if (!sample_rate) {
  1284. av_log(avctx, AV_LOG_ERROR, "Custom sample rate missing.\n");
  1285. return AVERROR_INVALIDDATA;
  1286. }
  1287. avctx->sample_rate = sample_rate * rate_x;
  1288. } else
  1289. avctx->sample_rate = wv_rates[sr] * rate_x;
  1290. if (multiblock) {
  1291. if (chan)
  1292. avctx->channels = chan;
  1293. if (chmask)
  1294. avctx->channel_layout = chmask;
  1295. } else {
  1296. avctx->channels = s->stereo ? 2 : 1;
  1297. avctx->channel_layout = s->stereo ? AV_CH_LAYOUT_STEREO :
  1298. AV_CH_LAYOUT_MONO;
  1299. }
  1300. ff_thread_release_buffer(avctx, &wc->prev_frame);
  1301. FFSWAP(ThreadFrame, wc->curr_frame, wc->prev_frame);
  1302. /* get output buffer */
  1303. wc->curr_frame.f->nb_samples = s->samples;
  1304. if ((ret = ff_thread_get_buffer(avctx, &wc->curr_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
  1305. return ret;
  1306. wc->frame = wc->curr_frame.f;
  1307. ff_thread_finish_setup(avctx);
  1308. }
  1309. if (wc->ch_offset + s->stereo >= avctx->channels) {
  1310. av_log(avctx, AV_LOG_WARNING, "Too many channels coded in a packet.\n");
  1311. return ((avctx->err_recognition & AV_EF_EXPLODE) || !wc->ch_offset) ? AVERROR_INVALIDDATA : 0;
  1312. }
  1313. samples_l = wc->frame->extended_data[wc->ch_offset];
  1314. if (s->stereo)
  1315. samples_r = wc->frame->extended_data[wc->ch_offset + 1];
  1316. wc->ch_offset += 1 + s->stereo;
  1317. if (s->stereo_in) {
  1318. if (got_dsd) {
  1319. if (dsd_mode == 3)
  1320. ret = wv_unpack_dsd_high(s, samples_l, samples_r);
  1321. else if (dsd_mode == 1)
  1322. ret = wv_unpack_dsd_fast(s, samples_l, samples_r);
  1323. else
  1324. ret = wv_unpack_dsd_copy(s, samples_l, samples_r);
  1325. }
  1326. else
  1327. ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
  1328. if (ret < 0)
  1329. return ret;
  1330. } else {
  1331. if (got_dsd) {
  1332. if (dsd_mode == 3)
  1333. ret = wv_unpack_dsd_high(s, samples_l, NULL);
  1334. else if (dsd_mode == 1)
  1335. ret = wv_unpack_dsd_fast(s, samples_l, NULL);
  1336. else
  1337. ret = wv_unpack_dsd_copy(s, samples_l, NULL);
  1338. }
  1339. else
  1340. ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
  1341. if (ret < 0)
  1342. return ret;
  1343. if (s->stereo)
  1344. memcpy(samples_r, samples_l, bpp * s->samples);
  1345. }
  1346. return 0;
  1347. }
  1348. static void wavpack_decode_flush(AVCodecContext *avctx)
  1349. {
  1350. WavpackContext *s = avctx->priv_data;
  1351. if (!avctx->internal->is_copy) {
  1352. for (int i = 0; i < avctx->channels; i++)
  1353. memset(s->dsdctx[i].buf, 0x69, sizeof(s->dsdctx[i].buf));
  1354. }
  1355. }
  1356. static int dsd_channel(AVCodecContext *avctx, void *frmptr, int jobnr, int threadnr)
  1357. {
  1358. WavpackContext *s = avctx->priv_data;
  1359. AVFrame *frame = frmptr;
  1360. ff_dsd2pcm_translate (&s->dsdctx [jobnr], s->samples, 0,
  1361. (uint8_t *) frame->extended_data[jobnr], 4,
  1362. (float *) frame->extended_data[jobnr], 1);
  1363. return 0;
  1364. }
  1365. static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
  1366. int *got_frame_ptr, AVPacket *avpkt)
  1367. {
  1368. WavpackContext *s = avctx->priv_data;
  1369. const uint8_t *buf = avpkt->data;
  1370. int buf_size = avpkt->size;
  1371. int frame_size, ret, frame_flags;
  1372. if (avpkt->size <= WV_HEADER_SIZE)
  1373. return AVERROR_INVALIDDATA;
  1374. s->frame = NULL;
  1375. s->block = 0;
  1376. s->ch_offset = 0;
  1377. /* determine number of samples */
  1378. s->samples = AV_RL32(buf + 20);
  1379. frame_flags = AV_RL32(buf + 24);
  1380. if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
  1381. av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
  1382. s->samples);
  1383. return AVERROR_INVALIDDATA;
  1384. }
  1385. s->modulation = (frame_flags & WV_DSD_DATA) ? MODULATION_DSD : MODULATION_PCM;
  1386. if (frame_flags & (WV_FLOAT_DATA | WV_DSD_DATA)) {
  1387. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  1388. } else if ((frame_flags & 0x03) <= 1) {
  1389. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  1390. } else {
  1391. avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  1392. avctx->bits_per_raw_sample = ((frame_flags & 0x03) + 1) << 3;
  1393. }
  1394. while (buf_size > WV_HEADER_SIZE) {
  1395. frame_size = AV_RL32(buf + 4) - 12;
  1396. buf += 20;
  1397. buf_size -= 20;
  1398. if (frame_size <= 0 || frame_size > buf_size) {
  1399. av_log(avctx, AV_LOG_ERROR,
  1400. "Block %d has invalid size (size %d vs. %d bytes left)\n",
  1401. s->block, frame_size, buf_size);
  1402. ret = AVERROR_INVALIDDATA;
  1403. goto error;
  1404. }
  1405. if ((ret = wavpack_decode_block(avctx, s->block, buf, frame_size)) < 0)
  1406. goto error;
  1407. s->block++;
  1408. buf += frame_size;
  1409. buf_size -= frame_size;
  1410. }
  1411. if (s->ch_offset != avctx->channels) {
  1412. av_log(avctx, AV_LOG_ERROR, "Not enough channels coded in a packet.\n");
  1413. ret = AVERROR_INVALIDDATA;
  1414. goto error;
  1415. }
  1416. ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
  1417. ff_thread_release_buffer(avctx, &s->prev_frame);
  1418. if (s->modulation == MODULATION_DSD)
  1419. avctx->execute2(avctx, dsd_channel, s->frame, NULL, avctx->channels);
  1420. ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
  1421. if ((ret = av_frame_ref(data, s->frame)) < 0)
  1422. return ret;
  1423. *got_frame_ptr = 1;
  1424. return avpkt->size;
  1425. error:
  1426. if (s->frame) {
  1427. ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
  1428. ff_thread_release_buffer(avctx, &s->prev_frame);
  1429. ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
  1430. }
  1431. return ret;
  1432. }
  1433. AVCodec ff_wavpack_decoder = {
  1434. .name = "wavpack",
  1435. .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
  1436. .type = AVMEDIA_TYPE_AUDIO,
  1437. .id = AV_CODEC_ID_WAVPACK,
  1438. .priv_data_size = sizeof(WavpackContext),
  1439. .init = wavpack_decode_init,
  1440. .close = wavpack_decode_end,
  1441. .decode = wavpack_decode_frame,
  1442. .flush = wavpack_decode_flush,
  1443. .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
  1444. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1445. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
  1446. AV_CODEC_CAP_SLICE_THREADS
  1447. };