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.

1715 lines
56KB

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