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.

1666 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. if (!s->curr_frame.f || !s->prev_frame.f)
  843. return AVERROR(ENOMEM);
  844. return 0;
  845. }
  846. static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  847. {
  848. WavpackContext *fsrc = src->priv_data;
  849. WavpackContext *fdst = dst->priv_data;
  850. int ret;
  851. if (dst == src)
  852. return 0;
  853. ff_thread_release_buffer(dst, &fdst->curr_frame);
  854. if (fsrc->curr_frame.f->data[0]) {
  855. if ((ret = ff_thread_ref_frame(&fdst->curr_frame, &fsrc->curr_frame)) < 0)
  856. return ret;
  857. }
  858. return 0;
  859. }
  860. #endif
  861. static av_cold int wavpack_decode_init(AVCodecContext *avctx)
  862. {
  863. WavpackContext *s = avctx->priv_data;
  864. s->avctx = avctx;
  865. s->fdec_num = 0;
  866. avctx->internal->allocate_progress = 1;
  867. s->curr_frame.f = av_frame_alloc();
  868. s->prev_frame.f = av_frame_alloc();
  869. // the DSD to PCM context is shared (and used serially) between all decoding threads
  870. s->dsdctx = av_calloc(avctx->channels, sizeof(DSDContext));
  871. if (!s->curr_frame.f || !s->prev_frame.f || !s->dsdctx)
  872. return AVERROR(ENOMEM);
  873. for (int i = 0; i < avctx->channels; i++)
  874. memset(s->dsdctx[i].buf, 0x69, sizeof(s->dsdctx[i].buf));
  875. ff_init_dsd_data();
  876. return 0;
  877. }
  878. static av_cold int wavpack_decode_end(AVCodecContext *avctx)
  879. {
  880. WavpackContext *s = avctx->priv_data;
  881. for (int i = 0; i < s->fdec_num; i++)
  882. av_freep(&s->fdec[i]);
  883. s->fdec_num = 0;
  884. ff_thread_release_buffer(avctx, &s->curr_frame);
  885. av_frame_free(&s->curr_frame.f);
  886. ff_thread_release_buffer(avctx, &s->prev_frame);
  887. av_frame_free(&s->prev_frame.f);
  888. if (!avctx->internal->is_copy)
  889. av_freep(&s->dsdctx);
  890. return 0;
  891. }
  892. static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
  893. const uint8_t *buf, int buf_size)
  894. {
  895. WavpackContext *wc = avctx->priv_data;
  896. WavpackFrameContext *s;
  897. GetByteContext gb;
  898. void *samples_l = NULL, *samples_r = NULL;
  899. int ret;
  900. int got_terms = 0, got_weights = 0, got_samples = 0,
  901. got_entropy = 0, got_pcm = 0, got_float = 0, got_hybrid = 0;
  902. int got_dsd = 0;
  903. int i, j, id, size, ssize, weights, t;
  904. int bpp, chan = 0, orig_bpp, sample_rate = 0, rate_x = 1, dsd_mode = 0;
  905. int multiblock;
  906. uint64_t chmask = 0;
  907. if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
  908. av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
  909. return AVERROR_INVALIDDATA;
  910. }
  911. s = wc->fdec[block_no];
  912. if (!s) {
  913. av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
  914. block_no);
  915. return AVERROR_INVALIDDATA;
  916. }
  917. memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
  918. memset(s->ch, 0, sizeof(s->ch));
  919. s->extra_bits = 0;
  920. s->and = s->or = s->shift = 0;
  921. s->got_extra_bits = 0;
  922. bytestream2_init(&gb, buf, buf_size);
  923. s->samples = bytestream2_get_le32(&gb);
  924. if (s->samples != wc->samples) {
  925. av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
  926. "a sequence: %d and %d\n", wc->samples, s->samples);
  927. return AVERROR_INVALIDDATA;
  928. }
  929. s->frame_flags = bytestream2_get_le32(&gb);
  930. bpp = av_get_bytes_per_sample(avctx->sample_fmt);
  931. orig_bpp = ((s->frame_flags & 0x03) + 1) << 3;
  932. multiblock = (s->frame_flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK;
  933. s->stereo = !(s->frame_flags & WV_MONO);
  934. s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
  935. s->joint = s->frame_flags & WV_JOINT_STEREO;
  936. s->hybrid = s->frame_flags & WV_HYBRID_MODE;
  937. s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
  938. s->post_shift = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
  939. if (s->post_shift < 0 || s->post_shift > 31) {
  940. return AVERROR_INVALIDDATA;
  941. }
  942. s->hybrid_maxclip = ((1LL << (orig_bpp - 1)) - 1);
  943. s->hybrid_minclip = ((-1UL << (orig_bpp - 1)));
  944. s->CRC = bytestream2_get_le32(&gb);
  945. // parse metadata blocks
  946. while (bytestream2_get_bytes_left(&gb)) {
  947. id = bytestream2_get_byte(&gb);
  948. size = bytestream2_get_byte(&gb);
  949. if (id & WP_IDF_LONG)
  950. size |= (bytestream2_get_le16u(&gb)) << 8;
  951. size <<= 1; // size is specified in words
  952. ssize = size;
  953. if (id & WP_IDF_ODD)
  954. size--;
  955. if (size < 0) {
  956. av_log(avctx, AV_LOG_ERROR,
  957. "Got incorrect block %02X with size %i\n", id, size);
  958. break;
  959. }
  960. if (bytestream2_get_bytes_left(&gb) < ssize) {
  961. av_log(avctx, AV_LOG_ERROR,
  962. "Block size %i is out of bounds\n", size);
  963. break;
  964. }
  965. switch (id & WP_IDF_MASK) {
  966. case WP_ID_DECTERMS:
  967. if (size > MAX_TERMS) {
  968. av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
  969. s->terms = 0;
  970. bytestream2_skip(&gb, ssize);
  971. continue;
  972. }
  973. s->terms = size;
  974. for (i = 0; i < s->terms; i++) {
  975. uint8_t val = bytestream2_get_byte(&gb);
  976. s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
  977. s->decorr[s->terms - i - 1].delta = val >> 5;
  978. }
  979. got_terms = 1;
  980. break;
  981. case WP_ID_DECWEIGHTS:
  982. if (!got_terms) {
  983. av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
  984. continue;
  985. }
  986. weights = size >> s->stereo_in;
  987. if (weights > MAX_TERMS || weights > s->terms) {
  988. av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
  989. bytestream2_skip(&gb, ssize);
  990. continue;
  991. }
  992. for (i = 0; i < weights; i++) {
  993. t = (int8_t)bytestream2_get_byte(&gb);
  994. s->decorr[s->terms - i - 1].weightA = t * (1 << 3);
  995. if (s->decorr[s->terms - i - 1].weightA > 0)
  996. s->decorr[s->terms - i - 1].weightA +=
  997. (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
  998. if (s->stereo_in) {
  999. t = (int8_t)bytestream2_get_byte(&gb);
  1000. s->decorr[s->terms - i - 1].weightB = t * (1 << 3);
  1001. if (s->decorr[s->terms - i - 1].weightB > 0)
  1002. s->decorr[s->terms - i - 1].weightB +=
  1003. (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
  1004. }
  1005. }
  1006. got_weights = 1;
  1007. break;
  1008. case WP_ID_DECSAMPLES:
  1009. if (!got_terms) {
  1010. av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
  1011. continue;
  1012. }
  1013. t = 0;
  1014. for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
  1015. if (s->decorr[i].value > 8) {
  1016. s->decorr[i].samplesA[0] =
  1017. wp_exp2(bytestream2_get_le16(&gb));
  1018. s->decorr[i].samplesA[1] =
  1019. wp_exp2(bytestream2_get_le16(&gb));
  1020. if (s->stereo_in) {
  1021. s->decorr[i].samplesB[0] =
  1022. wp_exp2(bytestream2_get_le16(&gb));
  1023. s->decorr[i].samplesB[1] =
  1024. wp_exp2(bytestream2_get_le16(&gb));
  1025. t += 4;
  1026. }
  1027. t += 4;
  1028. } else if (s->decorr[i].value < 0) {
  1029. s->decorr[i].samplesA[0] =
  1030. wp_exp2(bytestream2_get_le16(&gb));
  1031. s->decorr[i].samplesB[0] =
  1032. wp_exp2(bytestream2_get_le16(&gb));
  1033. t += 4;
  1034. } else {
  1035. for (j = 0; j < s->decorr[i].value; j++) {
  1036. s->decorr[i].samplesA[j] =
  1037. wp_exp2(bytestream2_get_le16(&gb));
  1038. if (s->stereo_in) {
  1039. s->decorr[i].samplesB[j] =
  1040. wp_exp2(bytestream2_get_le16(&gb));
  1041. }
  1042. }
  1043. t += s->decorr[i].value * 2 * (s->stereo_in + 1);
  1044. }
  1045. }
  1046. got_samples = 1;
  1047. break;
  1048. case WP_ID_ENTROPY:
  1049. if (size != 6 * (s->stereo_in + 1)) {
  1050. av_log(avctx, AV_LOG_ERROR,
  1051. "Entropy vars size should be %i, got %i.\n",
  1052. 6 * (s->stereo_in + 1), size);
  1053. bytestream2_skip(&gb, ssize);
  1054. continue;
  1055. }
  1056. for (j = 0; j <= s->stereo_in; j++)
  1057. for (i = 0; i < 3; i++) {
  1058. s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
  1059. }
  1060. got_entropy = 1;
  1061. break;
  1062. case WP_ID_HYBRID:
  1063. if (s->hybrid_bitrate) {
  1064. for (i = 0; i <= s->stereo_in; i++) {
  1065. s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
  1066. size -= 2;
  1067. }
  1068. }
  1069. for (i = 0; i < (s->stereo_in + 1); i++) {
  1070. s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
  1071. size -= 2;
  1072. }
  1073. if (size > 0) {
  1074. for (i = 0; i < (s->stereo_in + 1); i++) {
  1075. s->ch[i].bitrate_delta =
  1076. wp_exp2((int16_t)bytestream2_get_le16(&gb));
  1077. }
  1078. } else {
  1079. for (i = 0; i < (s->stereo_in + 1); i++)
  1080. s->ch[i].bitrate_delta = 0;
  1081. }
  1082. got_hybrid = 1;
  1083. break;
  1084. case WP_ID_INT32INFO: {
  1085. uint8_t val[4];
  1086. if (size != 4) {
  1087. av_log(avctx, AV_LOG_ERROR,
  1088. "Invalid INT32INFO, size = %i\n",
  1089. size);
  1090. bytestream2_skip(&gb, ssize - 4);
  1091. continue;
  1092. }
  1093. bytestream2_get_buffer(&gb, val, 4);
  1094. if (val[0] > 30) {
  1095. av_log(avctx, AV_LOG_ERROR,
  1096. "Invalid INT32INFO, extra_bits = %d (> 30)\n", val[0]);
  1097. continue;
  1098. } else if (val[0]) {
  1099. s->extra_bits = val[0];
  1100. } else if (val[1]) {
  1101. s->shift = val[1];
  1102. } else if (val[2]) {
  1103. s->and = s->or = 1;
  1104. s->shift = val[2];
  1105. } else if (val[3]) {
  1106. s->and = 1;
  1107. s->shift = val[3];
  1108. }
  1109. if (s->shift > 31) {
  1110. av_log(avctx, AV_LOG_ERROR,
  1111. "Invalid INT32INFO, shift = %d (> 31)\n", s->shift);
  1112. s->and = s->or = s->shift = 0;
  1113. continue;
  1114. }
  1115. /* original WavPack decoder forces 32-bit lossy sound to be treated
  1116. * as 24-bit one in order to have proper clipping */
  1117. if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
  1118. s->post_shift += 8;
  1119. s->shift -= 8;
  1120. s->hybrid_maxclip >>= 8;
  1121. s->hybrid_minclip >>= 8;
  1122. }
  1123. break;
  1124. }
  1125. case WP_ID_FLOATINFO:
  1126. if (size != 4) {
  1127. av_log(avctx, AV_LOG_ERROR,
  1128. "Invalid FLOATINFO, size = %i\n", size);
  1129. bytestream2_skip(&gb, ssize);
  1130. continue;
  1131. }
  1132. s->float_flag = bytestream2_get_byte(&gb);
  1133. s->float_shift = bytestream2_get_byte(&gb);
  1134. s->float_max_exp = bytestream2_get_byte(&gb);
  1135. if (s->float_shift > 31) {
  1136. av_log(avctx, AV_LOG_ERROR,
  1137. "Invalid FLOATINFO, shift = %d (> 31)\n", s->float_shift);
  1138. s->float_shift = 0;
  1139. continue;
  1140. }
  1141. got_float = 1;
  1142. bytestream2_skip(&gb, 1);
  1143. break;
  1144. case WP_ID_DATA:
  1145. if ((ret = init_get_bits8(&s->gb, gb.buffer, size)) < 0)
  1146. return ret;
  1147. bytestream2_skip(&gb, size);
  1148. got_pcm = 1;
  1149. break;
  1150. case WP_ID_DSD_DATA:
  1151. if (size < 2) {
  1152. av_log(avctx, AV_LOG_ERROR, "Invalid DSD_DATA, size = %i\n",
  1153. size);
  1154. bytestream2_skip(&gb, ssize);
  1155. continue;
  1156. }
  1157. rate_x = 1 << bytestream2_get_byte(&gb);
  1158. dsd_mode = bytestream2_get_byte(&gb);
  1159. if (dsd_mode && dsd_mode != 1 && dsd_mode != 3) {
  1160. av_log(avctx, AV_LOG_ERROR, "Invalid DSD encoding mode: %d\n",
  1161. dsd_mode);
  1162. return AVERROR_INVALIDDATA;
  1163. }
  1164. bytestream2_init(&s->gbyte, gb.buffer, size-2);
  1165. bytestream2_skip(&gb, size-2);
  1166. got_dsd = 1;
  1167. break;
  1168. case WP_ID_EXTRABITS:
  1169. if (size <= 4) {
  1170. av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
  1171. size);
  1172. bytestream2_skip(&gb, size);
  1173. continue;
  1174. }
  1175. if ((ret = init_get_bits8(&s->gb_extra_bits, gb.buffer, size)) < 0)
  1176. return ret;
  1177. s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);
  1178. bytestream2_skip(&gb, size);
  1179. s->got_extra_bits = 1;
  1180. break;
  1181. case WP_ID_CHANINFO:
  1182. if (size <= 1) {
  1183. av_log(avctx, AV_LOG_ERROR,
  1184. "Insufficient channel information\n");
  1185. return AVERROR_INVALIDDATA;
  1186. }
  1187. chan = bytestream2_get_byte(&gb);
  1188. switch (size - 2) {
  1189. case 0:
  1190. chmask = bytestream2_get_byte(&gb);
  1191. break;
  1192. case 1:
  1193. chmask = bytestream2_get_le16(&gb);
  1194. break;
  1195. case 2:
  1196. chmask = bytestream2_get_le24(&gb);
  1197. break;
  1198. case 3:
  1199. chmask = bytestream2_get_le32(&gb);
  1200. break;
  1201. case 4:
  1202. size = bytestream2_get_byte(&gb);
  1203. chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
  1204. chan += 1;
  1205. if (avctx->channels != chan)
  1206. av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
  1207. " instead of %i.\n", chan, avctx->channels);
  1208. chmask = bytestream2_get_le24(&gb);
  1209. break;
  1210. case 5:
  1211. size = bytestream2_get_byte(&gb);
  1212. chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
  1213. chan += 1;
  1214. if (avctx->channels != chan)
  1215. av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
  1216. " instead of %i.\n", chan, avctx->channels);
  1217. chmask = bytestream2_get_le32(&gb);
  1218. break;
  1219. default:
  1220. av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
  1221. size);
  1222. chan = avctx->channels;
  1223. chmask = avctx->channel_layout;
  1224. }
  1225. break;
  1226. case WP_ID_SAMPLE_RATE:
  1227. if (size != 3) {
  1228. av_log(avctx, AV_LOG_ERROR, "Invalid custom sample rate.\n");
  1229. return AVERROR_INVALIDDATA;
  1230. }
  1231. sample_rate = bytestream2_get_le24(&gb);
  1232. break;
  1233. default:
  1234. bytestream2_skip(&gb, size);
  1235. }
  1236. if (id & WP_IDF_ODD)
  1237. bytestream2_skip(&gb, 1);
  1238. }
  1239. if (got_pcm) {
  1240. if (!got_terms) {
  1241. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
  1242. return AVERROR_INVALIDDATA;
  1243. }
  1244. if (!got_weights) {
  1245. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
  1246. return AVERROR_INVALIDDATA;
  1247. }
  1248. if (!got_samples) {
  1249. av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
  1250. return AVERROR_INVALIDDATA;
  1251. }
  1252. if (!got_entropy) {
  1253. av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
  1254. return AVERROR_INVALIDDATA;
  1255. }
  1256. if (s->hybrid && !got_hybrid) {
  1257. av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
  1258. return AVERROR_INVALIDDATA;
  1259. }
  1260. if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
  1261. av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
  1262. return AVERROR_INVALIDDATA;
  1263. }
  1264. if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLTP) {
  1265. const int size = get_bits_left(&s->gb_extra_bits);
  1266. const int wanted = s->samples * s->extra_bits << s->stereo_in;
  1267. if (size < wanted) {
  1268. av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
  1269. s->got_extra_bits = 0;
  1270. }
  1271. }
  1272. }
  1273. if (!got_pcm && !got_dsd) {
  1274. av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
  1275. return AVERROR_INVALIDDATA;
  1276. }
  1277. if ((got_pcm && wc->modulation != MODULATION_PCM) ||
  1278. (got_dsd && wc->modulation != MODULATION_DSD)) {
  1279. av_log(avctx, AV_LOG_ERROR, "Invalid PCM/DSD mix encountered\n");
  1280. return AVERROR_INVALIDDATA;
  1281. }
  1282. if (!wc->ch_offset) {
  1283. int sr = (s->frame_flags >> 23) & 0xf;
  1284. if (sr == 0xf) {
  1285. if (!sample_rate) {
  1286. av_log(avctx, AV_LOG_ERROR, "Custom sample rate missing.\n");
  1287. return AVERROR_INVALIDDATA;
  1288. }
  1289. avctx->sample_rate = sample_rate * rate_x;
  1290. } else
  1291. avctx->sample_rate = wv_rates[sr] * rate_x;
  1292. if (multiblock) {
  1293. if (chan)
  1294. avctx->channels = chan;
  1295. if (chmask)
  1296. avctx->channel_layout = chmask;
  1297. } else {
  1298. avctx->channels = s->stereo ? 2 : 1;
  1299. avctx->channel_layout = s->stereo ? AV_CH_LAYOUT_STEREO :
  1300. AV_CH_LAYOUT_MONO;
  1301. }
  1302. ff_thread_release_buffer(avctx, &wc->prev_frame);
  1303. FFSWAP(ThreadFrame, wc->curr_frame, wc->prev_frame);
  1304. /* get output buffer */
  1305. wc->curr_frame.f->nb_samples = s->samples;
  1306. if ((ret = ff_thread_get_buffer(avctx, &wc->curr_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
  1307. return ret;
  1308. wc->frame = wc->curr_frame.f;
  1309. ff_thread_finish_setup(avctx);
  1310. }
  1311. if (wc->ch_offset + s->stereo >= avctx->channels) {
  1312. av_log(avctx, AV_LOG_WARNING, "Too many channels coded in a packet.\n");
  1313. return ((avctx->err_recognition & AV_EF_EXPLODE) || !wc->ch_offset) ? AVERROR_INVALIDDATA : 0;
  1314. }
  1315. samples_l = wc->frame->extended_data[wc->ch_offset];
  1316. if (s->stereo)
  1317. samples_r = wc->frame->extended_data[wc->ch_offset + 1];
  1318. wc->ch_offset += 1 + s->stereo;
  1319. if (s->stereo_in) {
  1320. if (got_dsd) {
  1321. if (dsd_mode == 3) {
  1322. ret = wv_unpack_dsd_high(s, samples_l, samples_r);
  1323. } else if (dsd_mode == 1) {
  1324. ret = wv_unpack_dsd_fast(s, samples_l, samples_r);
  1325. } else {
  1326. ret = wv_unpack_dsd_copy(s, samples_l, samples_r);
  1327. }
  1328. } else {
  1329. ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
  1330. }
  1331. if (ret < 0)
  1332. return ret;
  1333. } else {
  1334. if (got_dsd) {
  1335. if (dsd_mode == 3) {
  1336. ret = wv_unpack_dsd_high(s, samples_l, NULL);
  1337. } else if (dsd_mode == 1) {
  1338. ret = wv_unpack_dsd_fast(s, samples_l, NULL);
  1339. } else {
  1340. ret = wv_unpack_dsd_copy(s, samples_l, NULL);
  1341. }
  1342. } else {
  1343. ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
  1344. }
  1345. if (ret < 0)
  1346. return ret;
  1347. if (s->stereo)
  1348. memcpy(samples_r, samples_l, bpp * s->samples);
  1349. }
  1350. return 0;
  1351. }
  1352. static void wavpack_decode_flush(AVCodecContext *avctx)
  1353. {
  1354. WavpackContext *s = avctx->priv_data;
  1355. if (!avctx->internal->is_copy) {
  1356. for (int i = 0; i < avctx->channels; i++)
  1357. memset(s->dsdctx[i].buf, 0x69, sizeof(s->dsdctx[i].buf));
  1358. }
  1359. }
  1360. static int dsd_channel(AVCodecContext *avctx, void *frmptr, int jobnr, int threadnr)
  1361. {
  1362. WavpackContext *s = avctx->priv_data;
  1363. AVFrame *frame = frmptr;
  1364. ff_dsd2pcm_translate (&s->dsdctx [jobnr], s->samples, 0,
  1365. (uint8_t *)frame->extended_data[jobnr], 4,
  1366. (float *)frame->extended_data[jobnr], 1);
  1367. return 0;
  1368. }
  1369. static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
  1370. int *got_frame_ptr, AVPacket *avpkt)
  1371. {
  1372. WavpackContext *s = avctx->priv_data;
  1373. const uint8_t *buf = avpkt->data;
  1374. int buf_size = avpkt->size;
  1375. int frame_size, ret, frame_flags;
  1376. if (avpkt->size <= WV_HEADER_SIZE)
  1377. return AVERROR_INVALIDDATA;
  1378. s->frame = NULL;
  1379. s->block = 0;
  1380. s->ch_offset = 0;
  1381. /* determine number of samples */
  1382. s->samples = AV_RL32(buf + 20);
  1383. frame_flags = AV_RL32(buf + 24);
  1384. if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
  1385. av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
  1386. s->samples);
  1387. return AVERROR_INVALIDDATA;
  1388. }
  1389. s->modulation = (frame_flags & WV_DSD_DATA) ? MODULATION_DSD : MODULATION_PCM;
  1390. if (frame_flags & (WV_FLOAT_DATA | WV_DSD_DATA)) {
  1391. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  1392. } else if ((frame_flags & 0x03) <= 1) {
  1393. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  1394. } else {
  1395. avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  1396. avctx->bits_per_raw_sample = ((frame_flags & 0x03) + 1) << 3;
  1397. }
  1398. while (buf_size > WV_HEADER_SIZE) {
  1399. frame_size = AV_RL32(buf + 4) - 12;
  1400. buf += 20;
  1401. buf_size -= 20;
  1402. if (frame_size <= 0 || frame_size > buf_size) {
  1403. av_log(avctx, AV_LOG_ERROR,
  1404. "Block %d has invalid size (size %d vs. %d bytes left)\n",
  1405. s->block, frame_size, buf_size);
  1406. ret = AVERROR_INVALIDDATA;
  1407. goto error;
  1408. }
  1409. if ((ret = wavpack_decode_block(avctx, s->block, buf, frame_size)) < 0)
  1410. goto error;
  1411. s->block++;
  1412. buf += frame_size;
  1413. buf_size -= frame_size;
  1414. }
  1415. if (s->ch_offset != avctx->channels) {
  1416. av_log(avctx, AV_LOG_ERROR, "Not enough channels coded in a packet.\n");
  1417. ret = AVERROR_INVALIDDATA;
  1418. goto error;
  1419. }
  1420. ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
  1421. ff_thread_release_buffer(avctx, &s->prev_frame);
  1422. if (s->modulation == MODULATION_DSD)
  1423. avctx->execute2(avctx, dsd_channel, s->frame, NULL, avctx->channels);
  1424. ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
  1425. if ((ret = av_frame_ref(data, s->frame)) < 0)
  1426. return ret;
  1427. *got_frame_ptr = 1;
  1428. return avpkt->size;
  1429. error:
  1430. if (s->frame) {
  1431. ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
  1432. ff_thread_release_buffer(avctx, &s->prev_frame);
  1433. ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
  1434. }
  1435. return ret;
  1436. }
  1437. AVCodec ff_wavpack_decoder = {
  1438. .name = "wavpack",
  1439. .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
  1440. .type = AVMEDIA_TYPE_AUDIO,
  1441. .id = AV_CODEC_ID_WAVPACK,
  1442. .priv_data_size = sizeof(WavpackContext),
  1443. .init = wavpack_decode_init,
  1444. .close = wavpack_decode_end,
  1445. .decode = wavpack_decode_frame,
  1446. .flush = wavpack_decode_flush,
  1447. .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
  1448. .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
  1449. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
  1450. AV_CODEC_CAP_SLICE_THREADS
  1451. };