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.

1354 lines
43KB

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