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.

1379 lines
44KB

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