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.

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