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.

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