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.

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