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.

1383 lines
44KB

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