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.

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