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.

1355 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. #include "flac.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 FLAC_CHMODE_NOT_STEREO 0
  35. #define FLAC_CHMODE_LEFT_RIGHT 1
  36. #define FLAC_CHMODE_LEFT_SIDE 8
  37. #define FLAC_CHMODE_RIGHT_SIDE 9
  38. #define FLAC_CHMODE_MID_SIDE 10
  39. #define MAX_FIXED_ORDER 4
  40. #define MAX_PARTITION_ORDER 8
  41. #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
  42. #define MAX_LPC_PRECISION 15
  43. #define MAX_LPC_SHIFT 15
  44. #define MAX_RICE_PARAM 14
  45. typedef struct CompressionOptions {
  46. int compression_level;
  47. int block_time_ms;
  48. int use_lpc;
  49. int lpc_coeff_precision;
  50. int min_prediction_order;
  51. int max_prediction_order;
  52. int prediction_order_method;
  53. int min_partition_order;
  54. int max_partition_order;
  55. } CompressionOptions;
  56. typedef struct RiceContext {
  57. int porder;
  58. int params[MAX_PARTITIONS];
  59. } RiceContext;
  60. typedef struct FlacSubframe {
  61. int type;
  62. int type_code;
  63. int obits;
  64. int order;
  65. int32_t coefs[MAX_LPC_ORDER];
  66. int shift;
  67. RiceContext rc;
  68. int32_t samples[FLAC_MAX_BLOCKSIZE];
  69. int32_t residual[FLAC_MAX_BLOCKSIZE+1];
  70. } FlacSubframe;
  71. typedef struct FlacFrame {
  72. FlacSubframe subframes[FLAC_MAX_CHANNELS];
  73. int blocksize;
  74. int bs_code[2];
  75. uint8_t crc8;
  76. int ch_mode;
  77. } FlacFrame;
  78. typedef struct FlacEncodeContext {
  79. PutBitContext pb;
  80. int channels;
  81. int ch_code;
  82. int samplerate;
  83. int sr_code[2];
  84. int min_framesize;
  85. int min_encoded_framesize;
  86. int max_framesize;
  87. int max_encoded_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, s->min_framesize);
  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_CHANNELS) {
  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. s->min_encoded_framesize = 0xFFFFFF;
  344. /* initialize MD5 context */
  345. s->md5ctx = av_malloc(av_md5_size);
  346. if(!s->md5ctx)
  347. return AVERROR_NOMEM;
  348. av_md5_init(s->md5ctx);
  349. streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
  350. write_streaminfo(s, streaminfo);
  351. avctx->extradata = streaminfo;
  352. avctx->extradata_size = FLAC_STREAMINFO_SIZE;
  353. s->frame_count = 0;
  354. avctx->coded_frame = avcodec_alloc_frame();
  355. avctx->coded_frame->key_frame = 1;
  356. return 0;
  357. }
  358. static void init_frame(FlacEncodeContext *s)
  359. {
  360. int i, ch;
  361. FlacFrame *frame;
  362. frame = &s->frame;
  363. for(i=0; i<16; i++) {
  364. if(s->avctx->frame_size == flac_blocksizes[i]) {
  365. frame->blocksize = flac_blocksizes[i];
  366. frame->bs_code[0] = i;
  367. frame->bs_code[1] = 0;
  368. break;
  369. }
  370. }
  371. if(i == 16) {
  372. frame->blocksize = s->avctx->frame_size;
  373. if(frame->blocksize <= 256) {
  374. frame->bs_code[0] = 6;
  375. frame->bs_code[1] = frame->blocksize-1;
  376. } else {
  377. frame->bs_code[0] = 7;
  378. frame->bs_code[1] = frame->blocksize-1;
  379. }
  380. }
  381. for(ch=0; ch<s->channels; ch++) {
  382. frame->subframes[ch].obits = 16;
  383. }
  384. }
  385. /**
  386. * Copy channel-interleaved input samples into separate subframes
  387. */
  388. static void copy_samples(FlacEncodeContext *s, int16_t *samples)
  389. {
  390. int i, j, ch;
  391. FlacFrame *frame;
  392. frame = &s->frame;
  393. for(i=0,j=0; i<frame->blocksize; i++) {
  394. for(ch=0; ch<s->channels; ch++,j++) {
  395. frame->subframes[ch].samples[i] = samples[j];
  396. }
  397. }
  398. }
  399. #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
  400. /**
  401. * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
  402. */
  403. static int find_optimal_param(uint32_t sum, int n)
  404. {
  405. int k;
  406. uint32_t sum2;
  407. if(sum <= n>>1)
  408. return 0;
  409. sum2 = sum-(n>>1);
  410. k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
  411. return FFMIN(k, MAX_RICE_PARAM);
  412. }
  413. static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
  414. uint32_t *sums, int n, int pred_order)
  415. {
  416. int i;
  417. int k, cnt, part;
  418. uint32_t all_bits;
  419. part = (1 << porder);
  420. all_bits = 4 * part;
  421. cnt = (n >> porder) - pred_order;
  422. for(i=0; i<part; i++) {
  423. k = find_optimal_param(sums[i], cnt);
  424. rc->params[i] = k;
  425. all_bits += rice_encode_count(sums[i], cnt, k);
  426. cnt = n >> porder;
  427. }
  428. rc->porder = porder;
  429. return all_bits;
  430. }
  431. static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
  432. uint32_t sums[][MAX_PARTITIONS])
  433. {
  434. int i, j;
  435. int parts;
  436. uint32_t *res, *res_end;
  437. /* sums for highest level */
  438. parts = (1 << pmax);
  439. res = &data[pred_order];
  440. res_end = &data[n >> pmax];
  441. for(i=0; i<parts; i++) {
  442. uint32_t sum = 0;
  443. while(res < res_end){
  444. sum += *(res++);
  445. }
  446. sums[pmax][i] = sum;
  447. res_end+= n >> pmax;
  448. }
  449. /* sums for lower levels */
  450. for(i=pmax-1; i>=pmin; i--) {
  451. parts = (1 << i);
  452. for(j=0; j<parts; j++) {
  453. sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
  454. }
  455. }
  456. }
  457. static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
  458. int32_t *data, int n, int pred_order)
  459. {
  460. int i;
  461. uint32_t bits[MAX_PARTITION_ORDER+1];
  462. int opt_porder;
  463. RiceContext tmp_rc;
  464. uint32_t *udata;
  465. uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
  466. assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
  467. assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
  468. assert(pmin <= pmax);
  469. udata = av_malloc(n * sizeof(uint32_t));
  470. for(i=0; i<n; i++) {
  471. udata[i] = (2*data[i]) ^ (data[i]>>31);
  472. }
  473. calc_sums(pmin, pmax, udata, n, pred_order, sums);
  474. opt_porder = pmin;
  475. bits[pmin] = UINT32_MAX;
  476. for(i=pmin; i<=pmax; i++) {
  477. bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
  478. if(bits[i] <= bits[opt_porder]) {
  479. opt_porder = i;
  480. *rc= tmp_rc;
  481. }
  482. }
  483. av_freep(&udata);
  484. return bits[opt_porder];
  485. }
  486. static int get_max_p_order(int max_porder, int n, int order)
  487. {
  488. int porder = FFMIN(max_porder, av_log2(n^(n-1)));
  489. if(order > 0)
  490. porder = FFMIN(porder, av_log2(n/order));
  491. return porder;
  492. }
  493. static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
  494. int32_t *data, int n, int pred_order,
  495. int bps)
  496. {
  497. uint32_t bits;
  498. pmin = get_max_p_order(pmin, n, pred_order);
  499. pmax = get_max_p_order(pmax, n, pred_order);
  500. bits = pred_order*bps + 6;
  501. bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
  502. return bits;
  503. }
  504. static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
  505. int32_t *data, int n, int pred_order,
  506. int bps, int precision)
  507. {
  508. uint32_t bits;
  509. pmin = get_max_p_order(pmin, n, pred_order);
  510. pmax = get_max_p_order(pmax, n, pred_order);
  511. bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
  512. bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
  513. return bits;
  514. }
  515. /**
  516. * Apply Welch window function to audio block
  517. */
  518. static void apply_welch_window(const int32_t *data, int len, double *w_data)
  519. {
  520. int i, n2;
  521. double w;
  522. double c;
  523. assert(!(len&1)); //the optimization in r11881 does not support odd len
  524. //if someone wants odd len extend the change in r11881
  525. n2 = (len >> 1);
  526. c = 2.0 / (len - 1.0);
  527. w_data+=n2;
  528. data+=n2;
  529. for(i=0; i<n2; i++) {
  530. w = c - n2 + i;
  531. w = 1.0 - (w * w);
  532. w_data[-i-1] = data[-i-1] * w;
  533. w_data[+i ] = data[+i ] * w;
  534. }
  535. }
  536. /**
  537. * Calculates autocorrelation data from audio samples
  538. * A Welch window function is applied before calculation.
  539. */
  540. void ff_flac_compute_autocorr(const int32_t *data, int len, int lag,
  541. double *autoc)
  542. {
  543. int i, j;
  544. double tmp[len + lag + 1];
  545. double *data1= tmp + lag;
  546. apply_welch_window(data, len, data1);
  547. for(j=0; j<lag; j++)
  548. data1[j-lag]= 0.0;
  549. data1[len] = 0.0;
  550. for(j=0; j<lag; j+=2){
  551. double sum0 = 1.0, sum1 = 1.0;
  552. for(i=0; i<len; i++){
  553. sum0 += data1[i] * data1[i-j];
  554. sum1 += data1[i] * data1[i-j-1];
  555. }
  556. autoc[j ] = sum0;
  557. autoc[j+1] = sum1;
  558. }
  559. if(j==lag){
  560. double sum = 1.0;
  561. for(i=0; i<len; i+=2){
  562. sum += data1[i ] * data1[i-j ]
  563. + data1[i+1] * data1[i-j+1];
  564. }
  565. autoc[j] = sum;
  566. }
  567. }
  568. static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
  569. {
  570. assert(n > 0);
  571. memcpy(res, smp, n * sizeof(int32_t));
  572. }
  573. static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
  574. int order)
  575. {
  576. int i;
  577. for(i=0; i<order; i++) {
  578. res[i] = smp[i];
  579. }
  580. if(order==0){
  581. for(i=order; i<n; i++)
  582. res[i]= smp[i];
  583. }else if(order==1){
  584. for(i=order; i<n; i++)
  585. res[i]= smp[i] - smp[i-1];
  586. }else if(order==2){
  587. int a = smp[order-1] - smp[order-2];
  588. for(i=order; i<n; i+=2) {
  589. int b = smp[i] - smp[i-1];
  590. res[i]= b - a;
  591. a = smp[i+1] - smp[i];
  592. res[i+1]= a - b;
  593. }
  594. }else if(order==3){
  595. int a = smp[order-1] - smp[order-2];
  596. int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
  597. for(i=order; i<n; i+=2) {
  598. int b = smp[i] - smp[i-1];
  599. int d = b - a;
  600. res[i]= d - c;
  601. a = smp[i+1] - smp[i];
  602. c = a - b;
  603. res[i+1]= c - d;
  604. }
  605. }else{
  606. int a = smp[order-1] - smp[order-2];
  607. int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
  608. int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
  609. for(i=order; i<n; i+=2) {
  610. int b = smp[i] - smp[i-1];
  611. int d = b - a;
  612. int f = d - c;
  613. res[i]= f - e;
  614. a = smp[i+1] - smp[i];
  615. c = a - b;
  616. e = c - d;
  617. res[i+1]= e - f;
  618. }
  619. }
  620. }
  621. #define LPC1(x) {\
  622. int c = coefs[(x)-1];\
  623. p0 += c*s;\
  624. s = smp[i-(x)+1];\
  625. p1 += c*s;\
  626. }
  627. static av_always_inline void encode_residual_lpc_unrolled(
  628. int32_t *res, const int32_t *smp, int n,
  629. int order, const int32_t *coefs, int shift, int big)
  630. {
  631. int i;
  632. for(i=order; i<n; i+=2) {
  633. int s = smp[i-order];
  634. int p0 = 0, p1 = 0;
  635. if(big) {
  636. switch(order) {
  637. case 32: LPC1(32)
  638. case 31: LPC1(31)
  639. case 30: LPC1(30)
  640. case 29: LPC1(29)
  641. case 28: LPC1(28)
  642. case 27: LPC1(27)
  643. case 26: LPC1(26)
  644. case 25: LPC1(25)
  645. case 24: LPC1(24)
  646. case 23: LPC1(23)
  647. case 22: LPC1(22)
  648. case 21: LPC1(21)
  649. case 20: LPC1(20)
  650. case 19: LPC1(19)
  651. case 18: LPC1(18)
  652. case 17: LPC1(17)
  653. case 16: LPC1(16)
  654. case 15: LPC1(15)
  655. case 14: LPC1(14)
  656. case 13: LPC1(13)
  657. case 12: LPC1(12)
  658. case 11: LPC1(11)
  659. case 10: LPC1(10)
  660. case 9: LPC1( 9)
  661. LPC1( 8)
  662. LPC1( 7)
  663. LPC1( 6)
  664. LPC1( 5)
  665. LPC1( 4)
  666. LPC1( 3)
  667. LPC1( 2)
  668. LPC1( 1)
  669. }
  670. } else {
  671. switch(order) {
  672. case 8: LPC1( 8)
  673. case 7: LPC1( 7)
  674. case 6: LPC1( 6)
  675. case 5: LPC1( 5)
  676. case 4: LPC1( 4)
  677. case 3: LPC1( 3)
  678. case 2: LPC1( 2)
  679. case 1: LPC1( 1)
  680. }
  681. }
  682. res[i ] = smp[i ] - (p0 >> shift);
  683. res[i+1] = smp[i+1] - (p1 >> shift);
  684. }
  685. }
  686. static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
  687. int order, const int32_t *coefs, int shift)
  688. {
  689. int i;
  690. for(i=0; i<order; i++) {
  691. res[i] = smp[i];
  692. }
  693. #if CONFIG_SMALL
  694. for(i=order; i<n; i+=2) {
  695. int j;
  696. int s = smp[i];
  697. int p0 = 0, p1 = 0;
  698. for(j=0; j<order; j++) {
  699. int c = coefs[j];
  700. p1 += c*s;
  701. s = smp[i-j-1];
  702. p0 += c*s;
  703. }
  704. res[i ] = smp[i ] - (p0 >> shift);
  705. res[i+1] = smp[i+1] - (p1 >> shift);
  706. }
  707. #else
  708. switch(order) {
  709. case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
  710. case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
  711. case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
  712. case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
  713. case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
  714. case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
  715. case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
  716. case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
  717. default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
  718. }
  719. #endif
  720. }
  721. static int encode_residual(FlacEncodeContext *ctx, int ch)
  722. {
  723. int i, n;
  724. int min_order, max_order, opt_order, precision, omethod;
  725. int min_porder, max_porder;
  726. FlacFrame *frame;
  727. FlacSubframe *sub;
  728. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  729. int shift[MAX_LPC_ORDER];
  730. int32_t *res, *smp;
  731. frame = &ctx->frame;
  732. sub = &frame->subframes[ch];
  733. res = sub->residual;
  734. smp = sub->samples;
  735. n = frame->blocksize;
  736. /* CONSTANT */
  737. for(i=1; i<n; i++) {
  738. if(smp[i] != smp[0]) break;
  739. }
  740. if(i == n) {
  741. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  742. res[0] = smp[0];
  743. return sub->obits;
  744. }
  745. /* VERBATIM */
  746. if(n < 5) {
  747. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  748. encode_residual_verbatim(res, smp, n);
  749. return sub->obits * n;
  750. }
  751. min_order = ctx->options.min_prediction_order;
  752. max_order = ctx->options.max_prediction_order;
  753. min_porder = ctx->options.min_partition_order;
  754. max_porder = ctx->options.max_partition_order;
  755. precision = ctx->options.lpc_coeff_precision;
  756. omethod = ctx->options.prediction_order_method;
  757. /* FIXED */
  758. if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
  759. uint32_t bits[MAX_FIXED_ORDER+1];
  760. if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
  761. opt_order = 0;
  762. bits[0] = UINT32_MAX;
  763. for(i=min_order; i<=max_order; i++) {
  764. encode_residual_fixed(res, smp, n, i);
  765. bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
  766. n, i, sub->obits);
  767. if(bits[i] < bits[opt_order]) {
  768. opt_order = i;
  769. }
  770. }
  771. sub->order = opt_order;
  772. sub->type = FLAC_SUBFRAME_FIXED;
  773. sub->type_code = sub->type | sub->order;
  774. if(sub->order != max_order) {
  775. encode_residual_fixed(res, smp, n, sub->order);
  776. return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
  777. sub->order, sub->obits);
  778. }
  779. return bits[sub->order];
  780. }
  781. /* LPC */
  782. opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, min_order, max_order,
  783. precision, coefs, shift, ctx->options.use_lpc,
  784. omethod, MAX_LPC_SHIFT, 0);
  785. if(omethod == ORDER_METHOD_2LEVEL ||
  786. omethod == ORDER_METHOD_4LEVEL ||
  787. omethod == ORDER_METHOD_8LEVEL) {
  788. int levels = 1 << omethod;
  789. uint32_t bits[levels];
  790. int order;
  791. int opt_index = levels-1;
  792. opt_order = max_order-1;
  793. bits[opt_index] = UINT32_MAX;
  794. for(i=levels-1; i>=0; i--) {
  795. order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
  796. if(order < 0) order = 0;
  797. encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
  798. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  799. res, n, order+1, sub->obits, precision);
  800. if(bits[i] < bits[opt_index]) {
  801. opt_index = i;
  802. opt_order = order;
  803. }
  804. }
  805. opt_order++;
  806. } else if(omethod == ORDER_METHOD_SEARCH) {
  807. // brute-force optimal order search
  808. uint32_t bits[MAX_LPC_ORDER];
  809. opt_order = 0;
  810. bits[0] = UINT32_MAX;
  811. for(i=min_order-1; i<max_order; i++) {
  812. encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
  813. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  814. res, n, i+1, sub->obits, precision);
  815. if(bits[i] < bits[opt_order]) {
  816. opt_order = i;
  817. }
  818. }
  819. opt_order++;
  820. } else if(omethod == ORDER_METHOD_LOG) {
  821. uint32_t bits[MAX_LPC_ORDER];
  822. int step;
  823. opt_order= min_order - 1 + (max_order-min_order)/3;
  824. memset(bits, -1, sizeof(bits));
  825. for(step=16 ;step; step>>=1){
  826. int last= opt_order;
  827. for(i=last-step; i<=last+step; i+= step){
  828. if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
  829. continue;
  830. encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
  831. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  832. res, n, i+1, sub->obits, precision);
  833. if(bits[i] < bits[opt_order])
  834. opt_order= i;
  835. }
  836. }
  837. opt_order++;
  838. }
  839. sub->order = opt_order;
  840. sub->type = FLAC_SUBFRAME_LPC;
  841. sub->type_code = sub->type | (sub->order-1);
  842. sub->shift = shift[sub->order-1];
  843. for(i=0; i<sub->order; i++) {
  844. sub->coefs[i] = coefs[sub->order-1][i];
  845. }
  846. encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
  847. return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
  848. sub->obits, precision);
  849. }
  850. static int encode_residual_v(FlacEncodeContext *ctx, int ch)
  851. {
  852. int i, n;
  853. FlacFrame *frame;
  854. FlacSubframe *sub;
  855. int32_t *res, *smp;
  856. frame = &ctx->frame;
  857. sub = &frame->subframes[ch];
  858. res = sub->residual;
  859. smp = sub->samples;
  860. n = frame->blocksize;
  861. /* CONSTANT */
  862. for(i=1; i<n; i++) {
  863. if(smp[i] != smp[0]) break;
  864. }
  865. if(i == n) {
  866. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  867. res[0] = smp[0];
  868. return sub->obits;
  869. }
  870. /* VERBATIM */
  871. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  872. encode_residual_verbatim(res, smp, n);
  873. return sub->obits * n;
  874. }
  875. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  876. {
  877. int i, best;
  878. int32_t lt, rt;
  879. uint64_t sum[4];
  880. uint64_t score[4];
  881. int k;
  882. /* calculate sum of 2nd order residual for each channel */
  883. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  884. for(i=2; i<n; i++) {
  885. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  886. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  887. sum[2] += FFABS((lt + rt) >> 1);
  888. sum[3] += FFABS(lt - rt);
  889. sum[0] += FFABS(lt);
  890. sum[1] += FFABS(rt);
  891. }
  892. /* estimate bit counts */
  893. for(i=0; i<4; i++) {
  894. k = find_optimal_param(2*sum[i], n);
  895. sum[i] = rice_encode_count(2*sum[i], n, k);
  896. }
  897. /* calculate score for each mode */
  898. score[0] = sum[0] + sum[1];
  899. score[1] = sum[0] + sum[3];
  900. score[2] = sum[1] + sum[3];
  901. score[3] = sum[2] + sum[3];
  902. /* return mode with lowest score */
  903. best = 0;
  904. for(i=1; i<4; i++) {
  905. if(score[i] < score[best]) {
  906. best = i;
  907. }
  908. }
  909. if(best == 0) {
  910. return FLAC_CHMODE_LEFT_RIGHT;
  911. } else if(best == 1) {
  912. return FLAC_CHMODE_LEFT_SIDE;
  913. } else if(best == 2) {
  914. return FLAC_CHMODE_RIGHT_SIDE;
  915. } else {
  916. return FLAC_CHMODE_MID_SIDE;
  917. }
  918. }
  919. /**
  920. * Perform stereo channel decorrelation
  921. */
  922. static void channel_decorrelation(FlacEncodeContext *ctx)
  923. {
  924. FlacFrame *frame;
  925. int32_t *left, *right;
  926. int i, n;
  927. frame = &ctx->frame;
  928. n = frame->blocksize;
  929. left = frame->subframes[0].samples;
  930. right = frame->subframes[1].samples;
  931. if(ctx->channels != 2) {
  932. frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
  933. return;
  934. }
  935. frame->ch_mode = estimate_stereo_mode(left, right, n);
  936. /* perform decorrelation and adjust bits-per-sample */
  937. if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
  938. return;
  939. }
  940. if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
  941. int32_t tmp;
  942. for(i=0; i<n; i++) {
  943. tmp = left[i];
  944. left[i] = (tmp + right[i]) >> 1;
  945. right[i] = tmp - right[i];
  946. }
  947. frame->subframes[1].obits++;
  948. } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
  949. for(i=0; i<n; i++) {
  950. right[i] = left[i] - right[i];
  951. }
  952. frame->subframes[1].obits++;
  953. } else {
  954. for(i=0; i<n; i++) {
  955. left[i] -= right[i];
  956. }
  957. frame->subframes[0].obits++;
  958. }
  959. }
  960. static void write_utf8(PutBitContext *pb, uint32_t val)
  961. {
  962. uint8_t tmp;
  963. PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
  964. }
  965. static void output_frame_header(FlacEncodeContext *s)
  966. {
  967. FlacFrame *frame;
  968. int crc;
  969. frame = &s->frame;
  970. put_bits(&s->pb, 16, 0xFFF8);
  971. put_bits(&s->pb, 4, frame->bs_code[0]);
  972. put_bits(&s->pb, 4, s->sr_code[0]);
  973. if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
  974. put_bits(&s->pb, 4, s->ch_code);
  975. } else {
  976. put_bits(&s->pb, 4, frame->ch_mode);
  977. }
  978. put_bits(&s->pb, 3, 4); /* bits-per-sample code */
  979. put_bits(&s->pb, 1, 0);
  980. write_utf8(&s->pb, s->frame_count);
  981. if(frame->bs_code[0] == 6) {
  982. put_bits(&s->pb, 8, frame->bs_code[1]);
  983. } else if(frame->bs_code[0] == 7) {
  984. put_bits(&s->pb, 16, frame->bs_code[1]);
  985. }
  986. if(s->sr_code[0] == 12) {
  987. put_bits(&s->pb, 8, s->sr_code[1]);
  988. } else if(s->sr_code[0] > 12) {
  989. put_bits(&s->pb, 16, s->sr_code[1]);
  990. }
  991. flush_put_bits(&s->pb);
  992. crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
  993. s->pb.buf, put_bits_count(&s->pb)>>3);
  994. put_bits(&s->pb, 8, crc);
  995. }
  996. static void output_subframe_constant(FlacEncodeContext *s, int ch)
  997. {
  998. FlacSubframe *sub;
  999. int32_t res;
  1000. sub = &s->frame.subframes[ch];
  1001. res = sub->residual[0];
  1002. put_sbits(&s->pb, sub->obits, res);
  1003. }
  1004. static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
  1005. {
  1006. int i;
  1007. FlacFrame *frame;
  1008. FlacSubframe *sub;
  1009. int32_t res;
  1010. frame = &s->frame;
  1011. sub = &frame->subframes[ch];
  1012. for(i=0; i<frame->blocksize; i++) {
  1013. res = sub->residual[i];
  1014. put_sbits(&s->pb, sub->obits, res);
  1015. }
  1016. }
  1017. static void output_residual(FlacEncodeContext *ctx, int ch)
  1018. {
  1019. int i, j, p, n, parts;
  1020. int k, porder, psize, res_cnt;
  1021. FlacFrame *frame;
  1022. FlacSubframe *sub;
  1023. int32_t *res;
  1024. frame = &ctx->frame;
  1025. sub = &frame->subframes[ch];
  1026. res = sub->residual;
  1027. n = frame->blocksize;
  1028. /* rice-encoded block */
  1029. put_bits(&ctx->pb, 2, 0);
  1030. /* partition order */
  1031. porder = sub->rc.porder;
  1032. psize = n >> porder;
  1033. parts = (1 << porder);
  1034. put_bits(&ctx->pb, 4, porder);
  1035. res_cnt = psize - sub->order;
  1036. /* residual */
  1037. j = sub->order;
  1038. for(p=0; p<parts; p++) {
  1039. k = sub->rc.params[p];
  1040. put_bits(&ctx->pb, 4, k);
  1041. if(p == 1) res_cnt = psize;
  1042. for(i=0; i<res_cnt && j<n; i++, j++) {
  1043. set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
  1044. }
  1045. }
  1046. }
  1047. static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
  1048. {
  1049. int i;
  1050. FlacFrame *frame;
  1051. FlacSubframe *sub;
  1052. frame = &ctx->frame;
  1053. sub = &frame->subframes[ch];
  1054. /* warm-up samples */
  1055. for(i=0; i<sub->order; i++) {
  1056. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  1057. }
  1058. /* residual */
  1059. output_residual(ctx, ch);
  1060. }
  1061. static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
  1062. {
  1063. int i, cbits;
  1064. FlacFrame *frame;
  1065. FlacSubframe *sub;
  1066. frame = &ctx->frame;
  1067. sub = &frame->subframes[ch];
  1068. /* warm-up samples */
  1069. for(i=0; i<sub->order; i++) {
  1070. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  1071. }
  1072. /* LPC coefficients */
  1073. cbits = ctx->options.lpc_coeff_precision;
  1074. put_bits(&ctx->pb, 4, cbits-1);
  1075. put_sbits(&ctx->pb, 5, sub->shift);
  1076. for(i=0; i<sub->order; i++) {
  1077. put_sbits(&ctx->pb, cbits, sub->coefs[i]);
  1078. }
  1079. /* residual */
  1080. output_residual(ctx, ch);
  1081. }
  1082. static void output_subframes(FlacEncodeContext *s)
  1083. {
  1084. FlacFrame *frame;
  1085. FlacSubframe *sub;
  1086. int ch;
  1087. frame = &s->frame;
  1088. for(ch=0; ch<s->channels; ch++) {
  1089. sub = &frame->subframes[ch];
  1090. /* subframe header */
  1091. put_bits(&s->pb, 1, 0);
  1092. put_bits(&s->pb, 6, sub->type_code);
  1093. put_bits(&s->pb, 1, 0); /* no wasted bits */
  1094. /* subframe */
  1095. if(sub->type == FLAC_SUBFRAME_CONSTANT) {
  1096. output_subframe_constant(s, ch);
  1097. } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
  1098. output_subframe_verbatim(s, ch);
  1099. } else if(sub->type == FLAC_SUBFRAME_FIXED) {
  1100. output_subframe_fixed(s, ch);
  1101. } else if(sub->type == FLAC_SUBFRAME_LPC) {
  1102. output_subframe_lpc(s, ch);
  1103. }
  1104. }
  1105. }
  1106. static void output_frame_footer(FlacEncodeContext *s)
  1107. {
  1108. int crc;
  1109. flush_put_bits(&s->pb);
  1110. crc = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
  1111. s->pb.buf, put_bits_count(&s->pb)>>3));
  1112. put_bits(&s->pb, 16, crc);
  1113. flush_put_bits(&s->pb);
  1114. }
  1115. static void update_md5_sum(FlacEncodeContext *s, int16_t *samples)
  1116. {
  1117. #ifdef WORDS_BIGENDIAN
  1118. int i;
  1119. for(i = 0; i < s->frame.blocksize*s->channels; i++) {
  1120. int16_t smp = le2me_16(samples[i]);
  1121. av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
  1122. }
  1123. #else
  1124. av_md5_update(s->md5ctx, (uint8_t *)samples, s->frame.blocksize*s->channels*2);
  1125. #endif
  1126. }
  1127. static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  1128. int buf_size, void *data)
  1129. {
  1130. int ch;
  1131. FlacEncodeContext *s;
  1132. int16_t *samples = data;
  1133. int out_bytes;
  1134. int reencoded=0;
  1135. s = avctx->priv_data;
  1136. if(buf_size < s->max_framesize*2) {
  1137. av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
  1138. return 0;
  1139. }
  1140. /* when the last block is reached, update the header in extradata */
  1141. if (!data) {
  1142. s->min_framesize = s->min_encoded_framesize;
  1143. s->max_framesize = s->max_encoded_framesize;
  1144. av_md5_final(s->md5ctx, s->md5sum);
  1145. write_streaminfo(s, avctx->extradata);
  1146. return 0;
  1147. }
  1148. init_frame(s);
  1149. copy_samples(s, samples);
  1150. channel_decorrelation(s);
  1151. for(ch=0; ch<s->channels; ch++) {
  1152. encode_residual(s, ch);
  1153. }
  1154. write_frame:
  1155. init_put_bits(&s->pb, frame, buf_size);
  1156. output_frame_header(s);
  1157. output_subframes(s);
  1158. output_frame_footer(s);
  1159. out_bytes = put_bits_count(&s->pb) >> 3;
  1160. if(out_bytes > s->max_framesize) {
  1161. if(reencoded) {
  1162. /* still too large. must be an error. */
  1163. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  1164. return -1;
  1165. }
  1166. /* frame too large. use verbatim mode */
  1167. for(ch=0; ch<s->channels; ch++) {
  1168. encode_residual_v(s, ch);
  1169. }
  1170. reencoded = 1;
  1171. goto write_frame;
  1172. }
  1173. s->frame_count++;
  1174. s->sample_count += avctx->frame_size;
  1175. update_md5_sum(s, samples);
  1176. if (out_bytes > s->max_encoded_framesize)
  1177. s->max_encoded_framesize = out_bytes;
  1178. if (out_bytes < s->min_encoded_framesize)
  1179. s->min_encoded_framesize = out_bytes;
  1180. return out_bytes;
  1181. }
  1182. static av_cold int flac_encode_close(AVCodecContext *avctx)
  1183. {
  1184. if (avctx->priv_data) {
  1185. FlacEncodeContext *s = avctx->priv_data;
  1186. av_freep(&s->md5ctx);
  1187. }
  1188. av_freep(&avctx->extradata);
  1189. avctx->extradata_size = 0;
  1190. av_freep(&avctx->coded_frame);
  1191. return 0;
  1192. }
  1193. AVCodec flac_encoder = {
  1194. "flac",
  1195. CODEC_TYPE_AUDIO,
  1196. CODEC_ID_FLAC,
  1197. sizeof(FlacEncodeContext),
  1198. flac_encode_init,
  1199. flac_encode_frame,
  1200. flac_encode_close,
  1201. NULL,
  1202. .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
  1203. .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
  1204. .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
  1205. };