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.

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