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.

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