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.

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