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.

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