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.

1350 lines
40KB

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