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.

1484 lines
48KB

  1. /*
  2. * FLAC audio encoder
  3. * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avassert.h"
  22. #include "libavutil/crc.h"
  23. #include "libavutil/intmath.h"
  24. #include "libavutil/md5.h"
  25. #include "libavutil/opt.h"
  26. #include "avcodec.h"
  27. #include "bswapdsp.h"
  28. #include "put_bits.h"
  29. #include "golomb.h"
  30. #include "internal.h"
  31. #include "lpc.h"
  32. #include "flac.h"
  33. #include "flacdata.h"
  34. #include "flacdsp.h"
  35. #define FLAC_SUBFRAME_CONSTANT 0
  36. #define FLAC_SUBFRAME_VERBATIM 1
  37. #define FLAC_SUBFRAME_FIXED 8
  38. #define FLAC_SUBFRAME_LPC 32
  39. #define MAX_FIXED_ORDER 4
  40. #define MAX_PARTITION_ORDER 8
  41. #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
  42. #define MAX_LPC_PRECISION 15
  43. #define MAX_LPC_SHIFT 15
  44. enum CodingMode {
  45. CODING_MODE_RICE = 4,
  46. CODING_MODE_RICE2 = 5,
  47. };
  48. typedef struct CompressionOptions {
  49. int compression_level;
  50. int block_time_ms;
  51. enum FFLPCType lpc_type;
  52. int lpc_passes;
  53. int lpc_coeff_precision;
  54. int min_prediction_order;
  55. int max_prediction_order;
  56. int prediction_order_method;
  57. int min_partition_order;
  58. int max_partition_order;
  59. int ch_mode;
  60. int exact_rice_parameters;
  61. int multi_dim_quant;
  62. } CompressionOptions;
  63. typedef struct RiceContext {
  64. enum CodingMode coding_mode;
  65. int porder;
  66. int params[MAX_PARTITIONS];
  67. } RiceContext;
  68. typedef struct FlacSubframe {
  69. int type;
  70. int type_code;
  71. int obits;
  72. int wasted;
  73. int order;
  74. int32_t coefs[MAX_LPC_ORDER];
  75. int shift;
  76. RiceContext rc;
  77. uint32_t rc_udata[FLAC_MAX_BLOCKSIZE];
  78. uint64_t rc_sums[32][MAX_PARTITIONS];
  79. int32_t samples[FLAC_MAX_BLOCKSIZE];
  80. int32_t residual[FLAC_MAX_BLOCKSIZE+11];
  81. } FlacSubframe;
  82. typedef struct FlacFrame {
  83. FlacSubframe subframes[FLAC_MAX_CHANNELS];
  84. int blocksize;
  85. int bs_code[2];
  86. uint8_t crc8;
  87. int ch_mode;
  88. int verbatim_only;
  89. } FlacFrame;
  90. typedef struct FlacEncodeContext {
  91. AVClass *class;
  92. PutBitContext pb;
  93. int channels;
  94. int samplerate;
  95. int sr_code[2];
  96. int bps_code;
  97. int max_blocksize;
  98. int min_framesize;
  99. int max_framesize;
  100. int max_encoded_framesize;
  101. uint32_t frame_count;
  102. uint64_t sample_count;
  103. uint8_t md5sum[16];
  104. FlacFrame frame;
  105. CompressionOptions options;
  106. AVCodecContext *avctx;
  107. LPCContext lpc_ctx;
  108. struct AVMD5 *md5ctx;
  109. uint8_t *md5_buffer;
  110. unsigned int md5_buffer_size;
  111. BswapDSPContext bdsp;
  112. FLACDSPContext flac_dsp;
  113. int flushed;
  114. int64_t next_pts;
  115. } FlacEncodeContext;
  116. /**
  117. * Write streaminfo metadata block to byte array.
  118. */
  119. static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
  120. {
  121. PutBitContext pb;
  122. memset(header, 0, FLAC_STREAMINFO_SIZE);
  123. init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
  124. /* streaminfo metadata block */
  125. put_bits(&pb, 16, s->max_blocksize);
  126. put_bits(&pb, 16, s->max_blocksize);
  127. put_bits(&pb, 24, s->min_framesize);
  128. put_bits(&pb, 24, s->max_framesize);
  129. put_bits(&pb, 20, s->samplerate);
  130. put_bits(&pb, 3, s->channels-1);
  131. put_bits(&pb, 5, s->avctx->bits_per_raw_sample - 1);
  132. /* write 36-bit sample count in 2 put_bits() calls */
  133. put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
  134. put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
  135. flush_put_bits(&pb);
  136. memcpy(&header[18], s->md5sum, 16);
  137. }
  138. /**
  139. * Set blocksize based on samplerate.
  140. * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
  141. */
  142. static int select_blocksize(int samplerate, int block_time_ms)
  143. {
  144. int i;
  145. int target;
  146. int blocksize;
  147. av_assert0(samplerate > 0);
  148. blocksize = ff_flac_blocksize_table[1];
  149. target = (samplerate * block_time_ms) / 1000;
  150. for (i = 0; i < 16; i++) {
  151. if (target >= ff_flac_blocksize_table[i] &&
  152. ff_flac_blocksize_table[i] > blocksize) {
  153. blocksize = ff_flac_blocksize_table[i];
  154. }
  155. }
  156. return blocksize;
  157. }
  158. static av_cold void dprint_compression_options(FlacEncodeContext *s)
  159. {
  160. AVCodecContext *avctx = s->avctx;
  161. CompressionOptions *opt = &s->options;
  162. av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
  163. switch (opt->lpc_type) {
  164. case FF_LPC_TYPE_NONE:
  165. av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
  166. break;
  167. case FF_LPC_TYPE_FIXED:
  168. av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
  169. break;
  170. case FF_LPC_TYPE_LEVINSON:
  171. av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
  172. break;
  173. case FF_LPC_TYPE_CHOLESKY:
  174. av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
  175. opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
  176. break;
  177. }
  178. av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
  179. opt->min_prediction_order, opt->max_prediction_order);
  180. switch (opt->prediction_order_method) {
  181. case ORDER_METHOD_EST:
  182. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
  183. break;
  184. case ORDER_METHOD_2LEVEL:
  185. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
  186. break;
  187. case ORDER_METHOD_4LEVEL:
  188. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
  189. break;
  190. case ORDER_METHOD_8LEVEL:
  191. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
  192. break;
  193. case ORDER_METHOD_SEARCH:
  194. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
  195. break;
  196. case ORDER_METHOD_LOG:
  197. av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
  198. break;
  199. }
  200. av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
  201. opt->min_partition_order, opt->max_partition_order);
  202. av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
  203. av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
  204. opt->lpc_coeff_precision);
  205. }
  206. static av_cold int flac_encode_init(AVCodecContext *avctx)
  207. {
  208. int freq = avctx->sample_rate;
  209. int channels = avctx->channels;
  210. FlacEncodeContext *s = avctx->priv_data;
  211. int i, level, ret;
  212. uint8_t *streaminfo;
  213. s->avctx = avctx;
  214. switch (avctx->sample_fmt) {
  215. case AV_SAMPLE_FMT_S16:
  216. avctx->bits_per_raw_sample = 16;
  217. s->bps_code = 4;
  218. break;
  219. case AV_SAMPLE_FMT_S32:
  220. if (avctx->bits_per_raw_sample != 24)
  221. av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
  222. avctx->bits_per_raw_sample = 24;
  223. s->bps_code = 6;
  224. break;
  225. }
  226. if (channels < 1 || channels > FLAC_MAX_CHANNELS) {
  227. av_log(avctx, AV_LOG_ERROR, "%d channels not supported (max %d)\n",
  228. channels, FLAC_MAX_CHANNELS);
  229. return AVERROR(EINVAL);
  230. }
  231. s->channels = channels;
  232. /* find samplerate in table */
  233. if (freq < 1)
  234. return -1;
  235. for (i = 4; i < 12; i++) {
  236. if (freq == ff_flac_sample_rate_table[i]) {
  237. s->samplerate = ff_flac_sample_rate_table[i];
  238. s->sr_code[0] = i;
  239. s->sr_code[1] = 0;
  240. break;
  241. }
  242. }
  243. /* if not in table, samplerate is non-standard */
  244. if (i == 12) {
  245. if (freq % 1000 == 0 && freq < 255000) {
  246. s->sr_code[0] = 12;
  247. s->sr_code[1] = freq / 1000;
  248. } else if (freq % 10 == 0 && freq < 655350) {
  249. s->sr_code[0] = 14;
  250. s->sr_code[1] = freq / 10;
  251. } else if (freq < 65535) {
  252. s->sr_code[0] = 13;
  253. s->sr_code[1] = freq;
  254. } else {
  255. av_log(avctx, AV_LOG_ERROR, "%d Hz not supported\n", freq);
  256. return AVERROR(EINVAL);
  257. }
  258. s->samplerate = freq;
  259. }
  260. /* set compression option defaults based on avctx->compression_level */
  261. if (avctx->compression_level < 0)
  262. s->options.compression_level = 5;
  263. else
  264. s->options.compression_level = avctx->compression_level;
  265. level = s->options.compression_level;
  266. if (level > 12) {
  267. av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
  268. s->options.compression_level);
  269. return AVERROR(EINVAL);
  270. }
  271. s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
  272. if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
  273. s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
  274. FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
  275. FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
  276. FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
  277. FF_LPC_TYPE_LEVINSON})[level];
  278. s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
  279. s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
  280. if (s->options.prediction_order_method < 0)
  281. s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
  282. ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
  283. ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
  284. ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
  285. ORDER_METHOD_SEARCH})[level];
  286. if (s->options.min_partition_order > s->options.max_partition_order) {
  287. av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
  288. s->options.min_partition_order, s->options.max_partition_order);
  289. return AVERROR(EINVAL);
  290. }
  291. if (s->options.min_partition_order < 0)
  292. s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
  293. if (s->options.max_partition_order < 0)
  294. s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
  295. if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
  296. s->options.min_prediction_order = 0;
  297. } else if (avctx->min_prediction_order >= 0) {
  298. if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
  299. if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
  300. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
  301. avctx->min_prediction_order);
  302. return AVERROR(EINVAL);
  303. }
  304. } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
  305. avctx->min_prediction_order > MAX_LPC_ORDER) {
  306. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
  307. avctx->min_prediction_order);
  308. return AVERROR(EINVAL);
  309. }
  310. s->options.min_prediction_order = avctx->min_prediction_order;
  311. }
  312. if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
  313. s->options.max_prediction_order = 0;
  314. } else if (avctx->max_prediction_order >= 0) {
  315. if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
  316. if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
  317. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
  318. avctx->max_prediction_order);
  319. return AVERROR(EINVAL);
  320. }
  321. } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
  322. avctx->max_prediction_order > MAX_LPC_ORDER) {
  323. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
  324. avctx->max_prediction_order);
  325. return AVERROR(EINVAL);
  326. }
  327. s->options.max_prediction_order = avctx->max_prediction_order;
  328. }
  329. if (s->options.max_prediction_order < s->options.min_prediction_order) {
  330. av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
  331. s->options.min_prediction_order, s->options.max_prediction_order);
  332. return AVERROR(EINVAL);
  333. }
  334. if (avctx->frame_size > 0) {
  335. if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
  336. avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
  337. av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
  338. avctx->frame_size);
  339. return AVERROR(EINVAL);
  340. }
  341. } else {
  342. s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
  343. }
  344. s->max_blocksize = s->avctx->frame_size;
  345. /* set maximum encoded frame size in verbatim mode */
  346. s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
  347. s->channels,
  348. s->avctx->bits_per_raw_sample);
  349. /* initialize MD5 context */
  350. s->md5ctx = av_md5_alloc();
  351. if (!s->md5ctx)
  352. return AVERROR(ENOMEM);
  353. av_md5_init(s->md5ctx);
  354. streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
  355. if (!streaminfo)
  356. return AVERROR(ENOMEM);
  357. write_streaminfo(s, streaminfo);
  358. avctx->extradata = streaminfo;
  359. avctx->extradata_size = FLAC_STREAMINFO_SIZE;
  360. s->frame_count = 0;
  361. s->min_framesize = s->max_framesize;
  362. if (channels == 3 &&
  363. avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
  364. channels == 4 &&
  365. avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
  366. avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
  367. channels == 5 &&
  368. avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
  369. avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
  370. channels == 6 &&
  371. avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
  372. avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK) {
  373. if (avctx->channel_layout) {
  374. av_log(avctx, AV_LOG_ERROR, "Channel layout not supported by Flac, "
  375. "output stream will have incorrect "
  376. "channel layout.\n");
  377. } else {
  378. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
  379. "will use Flac channel layout for "
  380. "%d channels.\n", channels);
  381. }
  382. }
  383. ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
  384. s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
  385. ff_bswapdsp_init(&s->bdsp);
  386. ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt, channels,
  387. avctx->bits_per_raw_sample);
  388. dprint_compression_options(s);
  389. return ret;
  390. }
  391. static void init_frame(FlacEncodeContext *s, int nb_samples)
  392. {
  393. int i, ch;
  394. FlacFrame *frame;
  395. frame = &s->frame;
  396. for (i = 0; i < 16; i++) {
  397. if (nb_samples == ff_flac_blocksize_table[i]) {
  398. frame->blocksize = ff_flac_blocksize_table[i];
  399. frame->bs_code[0] = i;
  400. frame->bs_code[1] = 0;
  401. break;
  402. }
  403. }
  404. if (i == 16) {
  405. frame->blocksize = nb_samples;
  406. if (frame->blocksize <= 256) {
  407. frame->bs_code[0] = 6;
  408. frame->bs_code[1] = frame->blocksize-1;
  409. } else {
  410. frame->bs_code[0] = 7;
  411. frame->bs_code[1] = frame->blocksize-1;
  412. }
  413. }
  414. for (ch = 0; ch < s->channels; ch++) {
  415. FlacSubframe *sub = &frame->subframes[ch];
  416. sub->wasted = 0;
  417. sub->obits = s->avctx->bits_per_raw_sample;
  418. if (sub->obits > 16)
  419. sub->rc.coding_mode = CODING_MODE_RICE2;
  420. else
  421. sub->rc.coding_mode = CODING_MODE_RICE;
  422. }
  423. frame->verbatim_only = 0;
  424. }
  425. /**
  426. * Copy channel-interleaved input samples into separate subframes.
  427. */
  428. static void copy_samples(FlacEncodeContext *s, const void *samples)
  429. {
  430. int i, j, ch;
  431. FlacFrame *frame;
  432. int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
  433. s->avctx->bits_per_raw_sample;
  434. #define COPY_SAMPLES(bits) do { \
  435. const int ## bits ## _t *samples0 = samples; \
  436. frame = &s->frame; \
  437. for (i = 0, j = 0; i < frame->blocksize; i++) \
  438. for (ch = 0; ch < s->channels; ch++, j++) \
  439. frame->subframes[ch].samples[i] = samples0[j] >> shift; \
  440. } while (0)
  441. if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
  442. COPY_SAMPLES(16);
  443. else
  444. COPY_SAMPLES(32);
  445. }
  446. static uint64_t rice_count_exact(const int32_t *res, int n, int k)
  447. {
  448. int i;
  449. uint64_t count = 0;
  450. for (i = 0; i < n; i++) {
  451. int32_t v = -2 * res[i] - 1;
  452. v ^= v >> 31;
  453. count += (v >> k) + 1 + k;
  454. }
  455. return count;
  456. }
  457. static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
  458. int pred_order)
  459. {
  460. int p, porder, psize;
  461. int i, part_end;
  462. uint64_t count = 0;
  463. /* subframe header */
  464. count += 8;
  465. if (sub->wasted)
  466. count += sub->wasted;
  467. /* subframe */
  468. if (sub->type == FLAC_SUBFRAME_CONSTANT) {
  469. count += sub->obits;
  470. } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
  471. count += s->frame.blocksize * sub->obits;
  472. } else {
  473. /* warm-up samples */
  474. count += pred_order * sub->obits;
  475. /* LPC coefficients */
  476. if (sub->type == FLAC_SUBFRAME_LPC)
  477. count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
  478. /* rice-encoded block */
  479. count += 2;
  480. /* partition order */
  481. porder = sub->rc.porder;
  482. psize = s->frame.blocksize >> porder;
  483. count += 4;
  484. /* residual */
  485. i = pred_order;
  486. part_end = psize;
  487. for (p = 0; p < 1 << porder; p++) {
  488. int k = sub->rc.params[p];
  489. count += sub->rc.coding_mode;
  490. count += rice_count_exact(&sub->residual[i], part_end - i, k);
  491. i = part_end;
  492. part_end = FFMIN(s->frame.blocksize, part_end + psize);
  493. }
  494. }
  495. return count;
  496. }
  497. #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
  498. /**
  499. * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
  500. */
  501. static int find_optimal_param(uint64_t sum, int n, int max_param)
  502. {
  503. int k;
  504. uint64_t sum2;
  505. if (sum <= n >> 1)
  506. return 0;
  507. sum2 = sum - (n >> 1);
  508. k = av_log2(av_clipl_int32(sum2 / n));
  509. return FFMIN(k, max_param);
  510. }
  511. static int find_optimal_param_exact(uint64_t sums[32][MAX_PARTITIONS], int i, int max_param)
  512. {
  513. int bestk = 0;
  514. int64_t bestbits = INT64_MAX;
  515. int k;
  516. for (k = 0; k <= max_param; k++) {
  517. int64_t bits = sums[k][i];
  518. if (bits < bestbits) {
  519. bestbits = bits;
  520. bestk = k;
  521. }
  522. }
  523. return bestk;
  524. }
  525. static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
  526. uint64_t sums[32][MAX_PARTITIONS],
  527. int n, int pred_order, int max_param, int exact)
  528. {
  529. int i;
  530. int k, cnt, part;
  531. uint64_t all_bits;
  532. part = (1 << porder);
  533. all_bits = 4 * part;
  534. cnt = (n >> porder) - pred_order;
  535. for (i = 0; i < part; i++) {
  536. if (exact) {
  537. k = find_optimal_param_exact(sums, i, max_param);
  538. all_bits += sums[k][i];
  539. } else {
  540. k = find_optimal_param(sums[0][i], cnt, max_param);
  541. all_bits += rice_encode_count(sums[0][i], cnt, k);
  542. }
  543. rc->params[i] = k;
  544. cnt = n >> porder;
  545. }
  546. rc->porder = porder;
  547. return all_bits;
  548. }
  549. static void calc_sum_top(int pmax, int kmax, const uint32_t *data, int n, int pred_order,
  550. uint64_t sums[32][MAX_PARTITIONS])
  551. {
  552. int i, k;
  553. int parts;
  554. const uint32_t *res, *res_end;
  555. /* sums for highest level */
  556. parts = (1 << pmax);
  557. for (k = 0; k <= kmax; k++) {
  558. res = &data[pred_order];
  559. res_end = &data[n >> pmax];
  560. for (i = 0; i < parts; i++) {
  561. if (kmax) {
  562. uint64_t sum = (1LL + k) * (res_end - res);
  563. while (res < res_end)
  564. sum += *(res++) >> k;
  565. sums[k][i] = sum;
  566. } else {
  567. uint64_t sum = 0;
  568. while (res < res_end)
  569. sum += *(res++);
  570. sums[k][i] = sum;
  571. }
  572. res_end += n >> pmax;
  573. }
  574. }
  575. }
  576. static void calc_sum_next(int level, uint64_t sums[32][MAX_PARTITIONS], int kmax)
  577. {
  578. int i, k;
  579. int parts = (1 << level);
  580. for (i = 0; i < parts; i++) {
  581. for (k=0; k<=kmax; k++)
  582. sums[k][i] = sums[k][2*i] + sums[k][2*i+1];
  583. }
  584. }
  585. static uint64_t calc_rice_params(RiceContext *rc,
  586. uint32_t udata[FLAC_MAX_BLOCKSIZE],
  587. uint64_t sums[32][MAX_PARTITIONS],
  588. int pmin, int pmax,
  589. const int32_t *data, int n, int pred_order, int exact)
  590. {
  591. int i;
  592. uint64_t bits[MAX_PARTITION_ORDER+1];
  593. int opt_porder;
  594. RiceContext tmp_rc;
  595. int kmax = (1 << rc->coding_mode) - 2;
  596. av_assert1(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
  597. av_assert1(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
  598. av_assert1(pmin <= pmax);
  599. tmp_rc.coding_mode = rc->coding_mode;
  600. for (i = 0; i < n; i++)
  601. udata[i] = (2 * data[i]) ^ (data[i] >> 31);
  602. calc_sum_top(pmax, exact ? kmax : 0, udata, n, pred_order, sums);
  603. opt_porder = pmin;
  604. bits[pmin] = UINT32_MAX;
  605. for (i = pmax; ; ) {
  606. bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums, n, pred_order, kmax, exact);
  607. if (bits[i] < bits[opt_porder]) {
  608. opt_porder = i;
  609. *rc = tmp_rc;
  610. }
  611. if (i == pmin)
  612. break;
  613. calc_sum_next(--i, sums, exact ? kmax : 0);
  614. }
  615. return bits[opt_porder];
  616. }
  617. static int get_max_p_order(int max_porder, int n, int order)
  618. {
  619. int porder = FFMIN(max_porder, av_log2(n^(n-1)));
  620. if (order > 0)
  621. porder = FFMIN(porder, av_log2(n/order));
  622. return porder;
  623. }
  624. static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
  625. FlacSubframe *sub, int pred_order)
  626. {
  627. int pmin = get_max_p_order(s->options.min_partition_order,
  628. s->frame.blocksize, pred_order);
  629. int pmax = get_max_p_order(s->options.max_partition_order,
  630. s->frame.blocksize, pred_order);
  631. uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
  632. if (sub->type == FLAC_SUBFRAME_LPC)
  633. bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
  634. bits += calc_rice_params(&sub->rc, sub->rc_udata, sub->rc_sums, pmin, pmax, sub->residual,
  635. s->frame.blocksize, pred_order, s->options.exact_rice_parameters);
  636. return bits;
  637. }
  638. static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
  639. int order)
  640. {
  641. int i;
  642. for (i = 0; i < order; i++)
  643. res[i] = smp[i];
  644. if (order == 0) {
  645. for (i = order; i < n; i++)
  646. res[i] = smp[i];
  647. } else if (order == 1) {
  648. for (i = order; i < n; i++)
  649. res[i] = smp[i] - smp[i-1];
  650. } else if (order == 2) {
  651. int a = smp[order-1] - smp[order-2];
  652. for (i = order; i < n; i += 2) {
  653. int b = smp[i ] - smp[i-1];
  654. res[i] = b - a;
  655. a = smp[i+1] - smp[i ];
  656. res[i+1] = a - b;
  657. }
  658. } else if (order == 3) {
  659. int a = smp[order-1] - smp[order-2];
  660. int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
  661. for (i = order; i < n; i += 2) {
  662. int b = smp[i ] - smp[i-1];
  663. int d = b - a;
  664. res[i] = d - c;
  665. a = smp[i+1] - smp[i ];
  666. c = a - b;
  667. res[i+1] = c - d;
  668. }
  669. } else {
  670. int a = smp[order-1] - smp[order-2];
  671. int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
  672. int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
  673. for (i = order; i < n; i += 2) {
  674. int b = smp[i ] - smp[i-1];
  675. int d = b - a;
  676. int f = d - c;
  677. res[i ] = f - e;
  678. a = smp[i+1] - smp[i ];
  679. c = a - b;
  680. e = c - d;
  681. res[i+1] = e - f;
  682. }
  683. }
  684. }
  685. static int encode_residual_ch(FlacEncodeContext *s, int ch)
  686. {
  687. int i, n;
  688. int min_order, max_order, opt_order, omethod;
  689. FlacFrame *frame;
  690. FlacSubframe *sub;
  691. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  692. int shift[MAX_LPC_ORDER];
  693. int32_t *res, *smp;
  694. frame = &s->frame;
  695. sub = &frame->subframes[ch];
  696. res = sub->residual;
  697. smp = sub->samples;
  698. n = frame->blocksize;
  699. /* CONSTANT */
  700. for (i = 1; i < n; i++)
  701. if(smp[i] != smp[0])
  702. break;
  703. if (i == n) {
  704. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  705. res[0] = smp[0];
  706. return subframe_count_exact(s, sub, 0);
  707. }
  708. /* VERBATIM */
  709. if (frame->verbatim_only || n < 5) {
  710. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  711. memcpy(res, smp, n * sizeof(int32_t));
  712. return subframe_count_exact(s, sub, 0);
  713. }
  714. min_order = s->options.min_prediction_order;
  715. max_order = s->options.max_prediction_order;
  716. omethod = s->options.prediction_order_method;
  717. /* FIXED */
  718. sub->type = FLAC_SUBFRAME_FIXED;
  719. if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
  720. s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
  721. uint64_t bits[MAX_FIXED_ORDER+1];
  722. if (max_order > MAX_FIXED_ORDER)
  723. max_order = MAX_FIXED_ORDER;
  724. opt_order = 0;
  725. bits[0] = UINT32_MAX;
  726. for (i = min_order; i <= max_order; i++) {
  727. encode_residual_fixed(res, smp, n, i);
  728. bits[i] = find_subframe_rice_params(s, sub, i);
  729. if (bits[i] < bits[opt_order])
  730. opt_order = i;
  731. }
  732. sub->order = opt_order;
  733. sub->type_code = sub->type | sub->order;
  734. if (sub->order != max_order) {
  735. encode_residual_fixed(res, smp, n, sub->order);
  736. find_subframe_rice_params(s, sub, sub->order);
  737. }
  738. return subframe_count_exact(s, sub, sub->order);
  739. }
  740. /* LPC */
  741. sub->type = FLAC_SUBFRAME_LPC;
  742. opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
  743. s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
  744. s->options.lpc_passes, omethod,
  745. MAX_LPC_SHIFT, 0);
  746. if (omethod == ORDER_METHOD_2LEVEL ||
  747. omethod == ORDER_METHOD_4LEVEL ||
  748. omethod == ORDER_METHOD_8LEVEL) {
  749. int levels = 1 << omethod;
  750. uint64_t bits[1 << ORDER_METHOD_8LEVEL];
  751. int order = -1;
  752. int opt_index = levels-1;
  753. opt_order = max_order-1;
  754. bits[opt_index] = UINT32_MAX;
  755. for (i = levels-1; i >= 0; i--) {
  756. int last_order = order;
  757. order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
  758. order = av_clip(order, min_order - 1, max_order - 1);
  759. if (order == last_order)
  760. continue;
  761. if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(order) <= 32) {
  762. s->flac_dsp.lpc16_encode(res, smp, n, order+1, coefs[order],
  763. shift[order]);
  764. } else {
  765. s->flac_dsp.lpc32_encode(res, smp, n, order+1, coefs[order],
  766. shift[order]);
  767. }
  768. bits[i] = find_subframe_rice_params(s, sub, order+1);
  769. if (bits[i] < bits[opt_index]) {
  770. opt_index = i;
  771. opt_order = order;
  772. }
  773. }
  774. opt_order++;
  775. } else if (omethod == ORDER_METHOD_SEARCH) {
  776. // brute-force optimal order search
  777. uint64_t bits[MAX_LPC_ORDER];
  778. opt_order = 0;
  779. bits[0] = UINT32_MAX;
  780. for (i = min_order-1; i < max_order; i++) {
  781. if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
  782. s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
  783. } else {
  784. s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
  785. }
  786. bits[i] = find_subframe_rice_params(s, sub, i+1);
  787. if (bits[i] < bits[opt_order])
  788. opt_order = i;
  789. }
  790. opt_order++;
  791. } else if (omethod == ORDER_METHOD_LOG) {
  792. uint64_t bits[MAX_LPC_ORDER];
  793. int step;
  794. opt_order = min_order - 1 + (max_order-min_order)/3;
  795. memset(bits, -1, sizeof(bits));
  796. for (step = 16; step; step >>= 1) {
  797. int last = opt_order;
  798. for (i = last-step; i <= last+step; i += step) {
  799. if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
  800. continue;
  801. if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
  802. s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
  803. } else {
  804. s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
  805. }
  806. bits[i] = find_subframe_rice_params(s, sub, i+1);
  807. if (bits[i] < bits[opt_order])
  808. opt_order = i;
  809. }
  810. }
  811. opt_order++;
  812. }
  813. if (s->options.multi_dim_quant) {
  814. int allsteps = 1;
  815. int i, step, improved;
  816. int64_t best_score = INT64_MAX;
  817. int32_t qmax;
  818. qmax = (1 << (s->options.lpc_coeff_precision - 1)) - 1;
  819. for (i=0; i<opt_order; i++)
  820. allsteps *= 3;
  821. do {
  822. improved = 0;
  823. for (step = 0; step < allsteps; step++) {
  824. int tmp = step;
  825. int32_t lpc_try[MAX_LPC_ORDER];
  826. int64_t score = 0;
  827. int diffsum = 0;
  828. for (i=0; i<opt_order; i++) {
  829. int diff = ((tmp + 1) % 3) - 1;
  830. lpc_try[i] = av_clip(coefs[opt_order - 1][i] + diff, -qmax, qmax);
  831. tmp /= 3;
  832. diffsum += !!diff;
  833. }
  834. if (diffsum >8)
  835. continue;
  836. if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order - 1) <= 32) {
  837. s->flac_dsp.lpc16_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
  838. } else {
  839. s->flac_dsp.lpc32_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
  840. }
  841. score = find_subframe_rice_params(s, sub, opt_order);
  842. if (score < best_score) {
  843. best_score = score;
  844. memcpy(coefs[opt_order-1], lpc_try, sizeof(*coefs));
  845. improved=1;
  846. }
  847. }
  848. } while(improved);
  849. }
  850. sub->order = opt_order;
  851. sub->type_code = sub->type | (sub->order-1);
  852. sub->shift = shift[sub->order-1];
  853. for (i = 0; i < sub->order; i++)
  854. sub->coefs[i] = coefs[sub->order-1][i];
  855. if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order) <= 32) {
  856. s->flac_dsp.lpc16_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
  857. } else {
  858. s->flac_dsp.lpc32_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
  859. }
  860. find_subframe_rice_params(s, sub, sub->order);
  861. return subframe_count_exact(s, sub, sub->order);
  862. }
  863. static int count_frame_header(FlacEncodeContext *s)
  864. {
  865. uint8_t av_unused tmp;
  866. int count;
  867. /*
  868. <14> Sync code
  869. <1> Reserved
  870. <1> Blocking strategy
  871. <4> Block size in inter-channel samples
  872. <4> Sample rate
  873. <4> Channel assignment
  874. <3> Sample size in bits
  875. <1> Reserved
  876. */
  877. count = 32;
  878. /* coded frame number */
  879. PUT_UTF8(s->frame_count, tmp, count += 8;)
  880. /* explicit block size */
  881. if (s->frame.bs_code[0] == 6)
  882. count += 8;
  883. else if (s->frame.bs_code[0] == 7)
  884. count += 16;
  885. /* explicit sample rate */
  886. count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
  887. /* frame header CRC-8 */
  888. count += 8;
  889. return count;
  890. }
  891. static int encode_frame(FlacEncodeContext *s)
  892. {
  893. int ch;
  894. uint64_t count;
  895. count = count_frame_header(s);
  896. for (ch = 0; ch < s->channels; ch++)
  897. count += encode_residual_ch(s, ch);
  898. count += (8 - (count & 7)) & 7; // byte alignment
  899. count += 16; // CRC-16
  900. count >>= 3;
  901. if (count > INT_MAX)
  902. return AVERROR_BUG;
  903. return count;
  904. }
  905. static void remove_wasted_bits(FlacEncodeContext *s)
  906. {
  907. int ch, i;
  908. for (ch = 0; ch < s->channels; ch++) {
  909. FlacSubframe *sub = &s->frame.subframes[ch];
  910. int32_t v = 0;
  911. for (i = 0; i < s->frame.blocksize; i++) {
  912. v |= sub->samples[i];
  913. if (v & 1)
  914. break;
  915. }
  916. if (v && !(v & 1)) {
  917. v = av_ctz(v);
  918. for (i = 0; i < s->frame.blocksize; i++)
  919. sub->samples[i] >>= v;
  920. sub->wasted = v;
  921. sub->obits -= v;
  922. /* for 24-bit, check if removing wasted bits makes the range better
  923. suited for using RICE instead of RICE2 for entropy coding */
  924. if (sub->obits <= 17)
  925. sub->rc.coding_mode = CODING_MODE_RICE;
  926. }
  927. }
  928. }
  929. static int estimate_stereo_mode(const int32_t *left_ch, const int32_t *right_ch, int n,
  930. int max_rice_param)
  931. {
  932. int i, best;
  933. int32_t lt, rt;
  934. uint64_t sum[4];
  935. uint64_t score[4];
  936. int k;
  937. /* calculate sum of 2nd order residual for each channel */
  938. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  939. for (i = 2; i < n; i++) {
  940. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  941. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  942. sum[2] += FFABS((lt + rt) >> 1);
  943. sum[3] += FFABS(lt - rt);
  944. sum[0] += FFABS(lt);
  945. sum[1] += FFABS(rt);
  946. }
  947. /* estimate bit counts */
  948. for (i = 0; i < 4; i++) {
  949. k = find_optimal_param(2 * sum[i], n, max_rice_param);
  950. sum[i] = rice_encode_count( 2 * sum[i], n, k);
  951. }
  952. /* calculate score for each mode */
  953. score[0] = sum[0] + sum[1];
  954. score[1] = sum[0] + sum[3];
  955. score[2] = sum[1] + sum[3];
  956. score[3] = sum[2] + sum[3];
  957. /* return mode with lowest score */
  958. best = 0;
  959. for (i = 1; i < 4; i++)
  960. if (score[i] < score[best])
  961. best = i;
  962. return best;
  963. }
  964. /**
  965. * Perform stereo channel decorrelation.
  966. */
  967. static void channel_decorrelation(FlacEncodeContext *s)
  968. {
  969. FlacFrame *frame;
  970. int32_t *left, *right;
  971. int i, n;
  972. frame = &s->frame;
  973. n = frame->blocksize;
  974. left = frame->subframes[0].samples;
  975. right = frame->subframes[1].samples;
  976. if (s->channels != 2) {
  977. frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
  978. return;
  979. }
  980. if (s->options.ch_mode < 0) {
  981. int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
  982. frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
  983. } else
  984. frame->ch_mode = s->options.ch_mode;
  985. /* perform decorrelation and adjust bits-per-sample */
  986. if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
  987. return;
  988. if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
  989. int32_t tmp;
  990. for (i = 0; i < n; i++) {
  991. tmp = left[i];
  992. left[i] = (tmp + right[i]) >> 1;
  993. right[i] = tmp - right[i];
  994. }
  995. frame->subframes[1].obits++;
  996. } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
  997. for (i = 0; i < n; i++)
  998. right[i] = left[i] - right[i];
  999. frame->subframes[1].obits++;
  1000. } else {
  1001. for (i = 0; i < n; i++)
  1002. left[i] -= right[i];
  1003. frame->subframes[0].obits++;
  1004. }
  1005. }
  1006. static void write_utf8(PutBitContext *pb, uint32_t val)
  1007. {
  1008. uint8_t tmp;
  1009. PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
  1010. }
  1011. static void write_frame_header(FlacEncodeContext *s)
  1012. {
  1013. FlacFrame *frame;
  1014. int crc;
  1015. frame = &s->frame;
  1016. put_bits(&s->pb, 16, 0xFFF8);
  1017. put_bits(&s->pb, 4, frame->bs_code[0]);
  1018. put_bits(&s->pb, 4, s->sr_code[0]);
  1019. if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
  1020. put_bits(&s->pb, 4, s->channels-1);
  1021. else
  1022. put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
  1023. put_bits(&s->pb, 3, s->bps_code);
  1024. put_bits(&s->pb, 1, 0);
  1025. write_utf8(&s->pb, s->frame_count);
  1026. if (frame->bs_code[0] == 6)
  1027. put_bits(&s->pb, 8, frame->bs_code[1]);
  1028. else if (frame->bs_code[0] == 7)
  1029. put_bits(&s->pb, 16, frame->bs_code[1]);
  1030. if (s->sr_code[0] == 12)
  1031. put_bits(&s->pb, 8, s->sr_code[1]);
  1032. else if (s->sr_code[0] > 12)
  1033. put_bits(&s->pb, 16, s->sr_code[1]);
  1034. flush_put_bits(&s->pb);
  1035. crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
  1036. put_bits_count(&s->pb) >> 3);
  1037. put_bits(&s->pb, 8, crc);
  1038. }
  1039. static void write_subframes(FlacEncodeContext *s)
  1040. {
  1041. int ch;
  1042. for (ch = 0; ch < s->channels; ch++) {
  1043. FlacSubframe *sub = &s->frame.subframes[ch];
  1044. int i, p, porder, psize;
  1045. int32_t *part_end;
  1046. int32_t *res = sub->residual;
  1047. int32_t *frame_end = &sub->residual[s->frame.blocksize];
  1048. /* subframe header */
  1049. put_bits(&s->pb, 1, 0);
  1050. put_bits(&s->pb, 6, sub->type_code);
  1051. put_bits(&s->pb, 1, !!sub->wasted);
  1052. if (sub->wasted)
  1053. put_bits(&s->pb, sub->wasted, 1);
  1054. /* subframe */
  1055. if (sub->type == FLAC_SUBFRAME_CONSTANT) {
  1056. put_sbits(&s->pb, sub->obits, res[0]);
  1057. } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
  1058. while (res < frame_end)
  1059. put_sbits(&s->pb, sub->obits, *res++);
  1060. } else {
  1061. /* warm-up samples */
  1062. for (i = 0; i < sub->order; i++)
  1063. put_sbits(&s->pb, sub->obits, *res++);
  1064. /* LPC coefficients */
  1065. if (sub->type == FLAC_SUBFRAME_LPC) {
  1066. int cbits = s->options.lpc_coeff_precision;
  1067. put_bits( &s->pb, 4, cbits-1);
  1068. put_sbits(&s->pb, 5, sub->shift);
  1069. for (i = 0; i < sub->order; i++)
  1070. put_sbits(&s->pb, cbits, sub->coefs[i]);
  1071. }
  1072. /* rice-encoded block */
  1073. put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
  1074. /* partition order */
  1075. porder = sub->rc.porder;
  1076. psize = s->frame.blocksize >> porder;
  1077. put_bits(&s->pb, 4, porder);
  1078. /* residual */
  1079. part_end = &sub->residual[psize];
  1080. for (p = 0; p < 1 << porder; p++) {
  1081. int k = sub->rc.params[p];
  1082. put_bits(&s->pb, sub->rc.coding_mode, k);
  1083. while (res < part_end)
  1084. set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
  1085. part_end = FFMIN(frame_end, part_end + psize);
  1086. }
  1087. }
  1088. }
  1089. }
  1090. static void write_frame_footer(FlacEncodeContext *s)
  1091. {
  1092. int crc;
  1093. flush_put_bits(&s->pb);
  1094. crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
  1095. put_bits_count(&s->pb)>>3));
  1096. put_bits(&s->pb, 16, crc);
  1097. flush_put_bits(&s->pb);
  1098. }
  1099. static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
  1100. {
  1101. init_put_bits(&s->pb, avpkt->data, avpkt->size);
  1102. write_frame_header(s);
  1103. write_subframes(s);
  1104. write_frame_footer(s);
  1105. return put_bits_count(&s->pb) >> 3;
  1106. }
  1107. static int update_md5_sum(FlacEncodeContext *s, const void *samples)
  1108. {
  1109. const uint8_t *buf;
  1110. int buf_size = s->frame.blocksize * s->channels *
  1111. ((s->avctx->bits_per_raw_sample + 7) / 8);
  1112. if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
  1113. av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
  1114. if (!s->md5_buffer)
  1115. return AVERROR(ENOMEM);
  1116. }
  1117. if (s->avctx->bits_per_raw_sample <= 16) {
  1118. buf = (const uint8_t *)samples;
  1119. #if HAVE_BIGENDIAN
  1120. s->bdsp.bswap16_buf((uint16_t *) s->md5_buffer,
  1121. (const uint16_t *) samples, buf_size / 2);
  1122. buf = s->md5_buffer;
  1123. #endif
  1124. } else {
  1125. int i;
  1126. const int32_t *samples0 = samples;
  1127. uint8_t *tmp = s->md5_buffer;
  1128. for (i = 0; i < s->frame.blocksize * s->channels; i++) {
  1129. int32_t v = samples0[i] >> 8;
  1130. AV_WL24(tmp + 3*i, v);
  1131. }
  1132. buf = s->md5_buffer;
  1133. }
  1134. av_md5_update(s->md5ctx, buf, buf_size);
  1135. return 0;
  1136. }
  1137. static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  1138. const AVFrame *frame, int *got_packet_ptr)
  1139. {
  1140. FlacEncodeContext *s;
  1141. int frame_bytes, out_bytes, ret;
  1142. s = avctx->priv_data;
  1143. /* when the last block is reached, update the header in extradata */
  1144. if (!frame) {
  1145. s->max_framesize = s->max_encoded_framesize;
  1146. av_md5_final(s->md5ctx, s->md5sum);
  1147. write_streaminfo(s, avctx->extradata);
  1148. if (avctx->side_data_only_packets && !s->flushed) {
  1149. uint8_t *side_data = av_packet_new_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
  1150. avctx->extradata_size);
  1151. if (!side_data)
  1152. return AVERROR(ENOMEM);
  1153. memcpy(side_data, avctx->extradata, avctx->extradata_size);
  1154. avpkt->pts = s->next_pts;
  1155. *got_packet_ptr = 1;
  1156. s->flushed = 1;
  1157. }
  1158. return 0;
  1159. }
  1160. /* change max_framesize for small final frame */
  1161. if (frame->nb_samples < s->frame.blocksize) {
  1162. s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
  1163. s->channels,
  1164. avctx->bits_per_raw_sample);
  1165. }
  1166. init_frame(s, frame->nb_samples);
  1167. copy_samples(s, frame->data[0]);
  1168. channel_decorrelation(s);
  1169. remove_wasted_bits(s);
  1170. frame_bytes = encode_frame(s);
  1171. /* Fall back on verbatim mode if the compressed frame is larger than it
  1172. would be if encoded uncompressed. */
  1173. if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
  1174. s->frame.verbatim_only = 1;
  1175. frame_bytes = encode_frame(s);
  1176. if (frame_bytes < 0) {
  1177. av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
  1178. return frame_bytes;
  1179. }
  1180. }
  1181. if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)) < 0)
  1182. return ret;
  1183. out_bytes = write_frame(s, avpkt);
  1184. s->frame_count++;
  1185. s->sample_count += frame->nb_samples;
  1186. if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
  1187. av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
  1188. return ret;
  1189. }
  1190. if (out_bytes > s->max_encoded_framesize)
  1191. s->max_encoded_framesize = out_bytes;
  1192. if (out_bytes < s->min_framesize)
  1193. s->min_framesize = out_bytes;
  1194. avpkt->pts = frame->pts;
  1195. avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
  1196. avpkt->size = out_bytes;
  1197. s->next_pts = avpkt->pts + avpkt->duration;
  1198. *got_packet_ptr = 1;
  1199. return 0;
  1200. }
  1201. static av_cold int flac_encode_close(AVCodecContext *avctx)
  1202. {
  1203. if (avctx->priv_data) {
  1204. FlacEncodeContext *s = avctx->priv_data;
  1205. av_freep(&s->md5ctx);
  1206. av_freep(&s->md5_buffer);
  1207. ff_lpc_end(&s->lpc_ctx);
  1208. }
  1209. av_freep(&avctx->extradata);
  1210. avctx->extradata_size = 0;
  1211. return 0;
  1212. }
  1213. #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  1214. static const AVOption options[] = {
  1215. { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
  1216. { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.i64 = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
  1217. { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1218. { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1219. { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1220. { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1221. { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.i64 = 2 }, 1, INT_MAX, FLAGS },
  1222. { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
  1223. { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
  1224. { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
  1225. { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1226. { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1227. { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1228. { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1229. { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1230. { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1231. { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
  1232. { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1233. { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1234. { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1235. { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1236. { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1237. { "exact_rice_parameters", "Calculate rice parameters exactly", offsetof(FlacEncodeContext, options.exact_rice_parameters), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
  1238. { "multi_dim_quant", "Multi-dimensional quantization", offsetof(FlacEncodeContext, options.multi_dim_quant), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
  1239. { NULL },
  1240. };
  1241. static const AVClass flac_encoder_class = {
  1242. "FLAC encoder",
  1243. av_default_item_name,
  1244. options,
  1245. LIBAVUTIL_VERSION_INT,
  1246. };
  1247. AVCodec ff_flac_encoder = {
  1248. .name = "flac",
  1249. .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
  1250. .type = AVMEDIA_TYPE_AUDIO,
  1251. .id = AV_CODEC_ID_FLAC,
  1252. .priv_data_size = sizeof(FlacEncodeContext),
  1253. .init = flac_encode_init,
  1254. .encode2 = flac_encode_frame,
  1255. .close = flac_encode_close,
  1256. .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_LOSSLESS,
  1257. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  1258. AV_SAMPLE_FMT_S32,
  1259. AV_SAMPLE_FMT_NONE },
  1260. .priv_class = &flac_encoder_class,
  1261. };