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.

1517 lines
50KB

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