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.

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