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.

1353 lines
41KB

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