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.

1496 lines
43KB

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