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.

1302 lines
36KB

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