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