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.

1268 lines
35KB

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