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.

1406 lines
44KB

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