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.

1360 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_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 (s->options.lpc_type == FF_LPC_TYPE_NONE) {
  306. s->options.max_prediction_order = 0;
  307. } else if (avctx->max_prediction_order >= 0) {
  308. if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
  309. if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
  310. av_log(avctx, AV_LOG_WARNING,
  311. "invalid max prediction order %d, clamped to %d\n",
  312. avctx->max_prediction_order, MAX_FIXED_ORDER);
  313. avctx->max_prediction_order = MAX_FIXED_ORDER;
  314. }
  315. } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
  316. avctx->max_prediction_order > MAX_LPC_ORDER) {
  317. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
  318. avctx->max_prediction_order);
  319. return -1;
  320. }
  321. s->options.max_prediction_order = avctx->max_prediction_order;
  322. }
  323. if (s->options.max_prediction_order < s->options.min_prediction_order) {
  324. av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
  325. s->options.min_prediction_order, s->options.max_prediction_order);
  326. return -1;
  327. }
  328. if (avctx->frame_size > 0) {
  329. if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
  330. avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
  331. av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
  332. avctx->frame_size);
  333. return -1;
  334. }
  335. } else {
  336. s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
  337. }
  338. s->max_blocksize = s->avctx->frame_size;
  339. /* set maximum encoded frame size in verbatim mode */
  340. s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
  341. s->channels,
  342. s->avctx->bits_per_raw_sample);
  343. /* initialize MD5 context */
  344. s->md5ctx = av_md5_alloc();
  345. if (!s->md5ctx)
  346. return AVERROR(ENOMEM);
  347. av_md5_init(s->md5ctx);
  348. streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
  349. if (!streaminfo)
  350. return AVERROR(ENOMEM);
  351. write_streaminfo(s, streaminfo);
  352. avctx->extradata = streaminfo;
  353. avctx->extradata_size = FLAC_STREAMINFO_SIZE;
  354. s->frame_count = 0;
  355. s->min_framesize = s->max_framesize;
  356. ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
  357. s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
  358. ff_bswapdsp_init(&s->bdsp);
  359. ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
  360. avctx->bits_per_raw_sample);
  361. dprint_compression_options(s);
  362. return ret;
  363. }
  364. static void init_frame(FlacEncodeContext *s, int nb_samples)
  365. {
  366. int i, ch;
  367. FlacFrame *frame;
  368. frame = &s->frame;
  369. for (i = 0; i < 16; i++) {
  370. if (nb_samples == ff_flac_blocksize_table[i]) {
  371. frame->blocksize = ff_flac_blocksize_table[i];
  372. frame->bs_code[0] = i;
  373. frame->bs_code[1] = 0;
  374. break;
  375. }
  376. }
  377. if (i == 16) {
  378. frame->blocksize = nb_samples;
  379. if (frame->blocksize <= 256) {
  380. frame->bs_code[0] = 6;
  381. frame->bs_code[1] = frame->blocksize-1;
  382. } else {
  383. frame->bs_code[0] = 7;
  384. frame->bs_code[1] = frame->blocksize-1;
  385. }
  386. }
  387. for (ch = 0; ch < s->channels; ch++) {
  388. FlacSubframe *sub = &frame->subframes[ch];
  389. sub->wasted = 0;
  390. sub->obits = s->avctx->bits_per_raw_sample;
  391. if (sub->obits > 16)
  392. sub->rc.coding_mode = CODING_MODE_RICE2;
  393. else
  394. sub->rc.coding_mode = CODING_MODE_RICE;
  395. }
  396. frame->verbatim_only = 0;
  397. }
  398. /**
  399. * Copy channel-interleaved input samples into separate subframes.
  400. */
  401. static void copy_samples(FlacEncodeContext *s, const void *samples)
  402. {
  403. int i, j, ch;
  404. FlacFrame *frame;
  405. int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
  406. s->avctx->bits_per_raw_sample;
  407. #define COPY_SAMPLES(bits) do { \
  408. const int ## bits ## _t *samples0 = samples; \
  409. frame = &s->frame; \
  410. for (i = 0, j = 0; i < frame->blocksize; i++) \
  411. for (ch = 0; ch < s->channels; ch++, j++) \
  412. frame->subframes[ch].samples[i] = samples0[j] >> shift; \
  413. } while (0)
  414. if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
  415. COPY_SAMPLES(16);
  416. else
  417. COPY_SAMPLES(32);
  418. }
  419. static uint64_t rice_count_exact(int32_t *res, int n, int k)
  420. {
  421. int i;
  422. uint64_t count = 0;
  423. for (i = 0; i < n; i++) {
  424. int32_t v = -2 * res[i] - 1;
  425. v ^= v >> 31;
  426. count += (v >> k) + 1 + k;
  427. }
  428. return count;
  429. }
  430. static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
  431. int pred_order)
  432. {
  433. int p, porder, psize;
  434. int i, part_end;
  435. uint64_t count = 0;
  436. /* subframe header */
  437. count += 8;
  438. /* subframe */
  439. if (sub->type == FLAC_SUBFRAME_CONSTANT) {
  440. count += sub->obits;
  441. } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
  442. count += s->frame.blocksize * sub->obits;
  443. } else {
  444. /* warm-up samples */
  445. count += pred_order * sub->obits;
  446. /* LPC coefficients */
  447. if (sub->type == FLAC_SUBFRAME_LPC)
  448. count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
  449. /* rice-encoded block */
  450. count += 2;
  451. /* partition order */
  452. porder = sub->rc.porder;
  453. psize = s->frame.blocksize >> porder;
  454. count += 4;
  455. /* residual */
  456. i = pred_order;
  457. part_end = psize;
  458. for (p = 0; p < 1 << porder; p++) {
  459. int k = sub->rc.params[p];
  460. count += sub->rc.coding_mode;
  461. count += rice_count_exact(&sub->residual[i], part_end - i, k);
  462. i = part_end;
  463. part_end = FFMIN(s->frame.blocksize, part_end + psize);
  464. }
  465. }
  466. return count;
  467. }
  468. #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
  469. /**
  470. * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
  471. */
  472. static int find_optimal_param(uint64_t sum, int n, int max_param)
  473. {
  474. int k;
  475. uint64_t sum2;
  476. if (sum <= n >> 1)
  477. return 0;
  478. sum2 = sum - (n >> 1);
  479. k = av_log2(av_clipl_int32(sum2 / n));
  480. return FFMIN(k, max_param);
  481. }
  482. static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
  483. uint64_t *sums, int n, int pred_order)
  484. {
  485. int i;
  486. int k, cnt, part, max_param;
  487. uint64_t all_bits;
  488. max_param = (1 << rc->coding_mode) - 2;
  489. part = (1 << porder);
  490. all_bits = 4 * part;
  491. cnt = (n >> porder) - pred_order;
  492. for (i = 0; i < part; i++) {
  493. k = find_optimal_param(sums[i], cnt, max_param);
  494. rc->params[i] = k;
  495. all_bits += rice_encode_count(sums[i], cnt, k);
  496. cnt = n >> porder;
  497. }
  498. rc->porder = porder;
  499. return all_bits;
  500. }
  501. static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
  502. uint64_t sums[][MAX_PARTITIONS])
  503. {
  504. int i, j;
  505. int parts;
  506. uint32_t *res, *res_end;
  507. /* sums for highest level */
  508. parts = (1 << pmax);
  509. res = &data[pred_order];
  510. res_end = &data[n >> pmax];
  511. for (i = 0; i < parts; i++) {
  512. uint64_t sum = 0;
  513. while (res < res_end)
  514. sum += *(res++);
  515. sums[pmax][i] = sum;
  516. res_end += n >> pmax;
  517. }
  518. /* sums for lower levels */
  519. for (i = pmax - 1; i >= pmin; i--) {
  520. parts = (1 << i);
  521. for (j = 0; j < parts; j++)
  522. sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
  523. }
  524. }
  525. static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
  526. int32_t *data, int n, int pred_order)
  527. {
  528. int i;
  529. uint64_t bits[MAX_PARTITION_ORDER+1];
  530. int opt_porder;
  531. RiceContext tmp_rc;
  532. uint64_t sums[MAX_PARTITION_ORDER + 1][MAX_PARTITIONS] = { { 0 } };
  533. assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
  534. assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
  535. assert(pmin <= pmax);
  536. tmp_rc.coding_mode = rc->coding_mode;
  537. for (i = 0; i < n; i++)
  538. rc->udata[i] = (2 * data[i]) ^ (data[i] >> 31);
  539. calc_sums(pmin, pmax, rc->udata, n, pred_order, sums);
  540. opt_porder = pmin;
  541. bits[pmin] = UINT32_MAX;
  542. for (i = pmin; i <= pmax; i++) {
  543. bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
  544. if (bits[i] <= bits[opt_porder]) {
  545. opt_porder = i;
  546. *rc = tmp_rc;
  547. }
  548. }
  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 FF_API_SIDEDATA_ONLY_PKT
  1031. FF_DISABLE_DEPRECATION_WARNINGS
  1032. if (avctx->side_data_only_packets && !s->flushed) {
  1033. FF_ENABLE_DEPRECATION_WARNINGS
  1034. #else
  1035. if (!s->flushed) {
  1036. #endif
  1037. uint8_t *side_data = av_packet_new_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
  1038. avctx->extradata_size);
  1039. if (!side_data)
  1040. return AVERROR(ENOMEM);
  1041. memcpy(side_data, avctx->extradata, avctx->extradata_size);
  1042. avpkt->pts = s->next_pts;
  1043. *got_packet_ptr = 1;
  1044. s->flushed = 1;
  1045. }
  1046. return 0;
  1047. }
  1048. /* change max_framesize for small final frame */
  1049. if (frame->nb_samples < s->frame.blocksize) {
  1050. s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
  1051. s->channels,
  1052. avctx->bits_per_raw_sample);
  1053. }
  1054. init_frame(s, frame->nb_samples);
  1055. copy_samples(s, frame->data[0]);
  1056. channel_decorrelation(s);
  1057. remove_wasted_bits(s);
  1058. frame_bytes = encode_frame(s);
  1059. /* Fall back on verbatim mode if the compressed frame is larger than it
  1060. would be if encoded uncompressed. */
  1061. if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
  1062. s->frame.verbatim_only = 1;
  1063. frame_bytes = encode_frame(s);
  1064. if (frame_bytes < 0) {
  1065. av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
  1066. return frame_bytes;
  1067. }
  1068. }
  1069. if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
  1070. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  1071. return ret;
  1072. }
  1073. out_bytes = write_frame(s, avpkt);
  1074. s->frame_count++;
  1075. s->sample_count += frame->nb_samples;
  1076. if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
  1077. av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
  1078. return ret;
  1079. }
  1080. if (out_bytes > s->max_encoded_framesize)
  1081. s->max_encoded_framesize = out_bytes;
  1082. if (out_bytes < s->min_framesize)
  1083. s->min_framesize = out_bytes;
  1084. avpkt->pts = frame->pts;
  1085. avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
  1086. avpkt->size = out_bytes;
  1087. s->next_pts = avpkt->pts + avpkt->duration;
  1088. *got_packet_ptr = 1;
  1089. return 0;
  1090. }
  1091. static av_cold int flac_encode_close(AVCodecContext *avctx)
  1092. {
  1093. if (avctx->priv_data) {
  1094. FlacEncodeContext *s = avctx->priv_data;
  1095. av_freep(&s->md5ctx);
  1096. av_freep(&s->md5_buffer);
  1097. ff_lpc_end(&s->lpc_ctx);
  1098. }
  1099. av_freep(&avctx->extradata);
  1100. avctx->extradata_size = 0;
  1101. return 0;
  1102. }
  1103. #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  1104. static const AVOption options[] = {
  1105. { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
  1106. { "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" },
  1107. { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1108. { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1109. { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1110. { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
  1111. { "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 },
  1112. { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
  1113. { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
  1114. { "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" },
  1115. { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1116. { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1117. { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1118. { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1119. { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1120. { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
  1121. { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
  1122. { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1123. { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1124. { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1125. { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1126. { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
  1127. { NULL },
  1128. };
  1129. static const AVClass flac_encoder_class = {
  1130. "FLAC encoder",
  1131. av_default_item_name,
  1132. options,
  1133. LIBAVUTIL_VERSION_INT,
  1134. };
  1135. AVCodec ff_flac_encoder = {
  1136. .name = "flac",
  1137. .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
  1138. .type = AVMEDIA_TYPE_AUDIO,
  1139. .id = AV_CODEC_ID_FLAC,
  1140. .priv_data_size = sizeof(FlacEncodeContext),
  1141. .init = flac_encode_init,
  1142. .encode2 = flac_encode_frame,
  1143. .close = flac_encode_close,
  1144. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
  1145. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  1146. AV_SAMPLE_FMT_S32,
  1147. AV_SAMPLE_FMT_NONE },
  1148. .priv_class = &flac_encoder_class,
  1149. };