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.

1274 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_MIN_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 uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
  479. int32_t *data, int n, int pred_order,
  480. int bps)
  481. {
  482. uint32_t bits;
  483. bits = pred_order*bps + 6;
  484. bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
  485. return bits;
  486. }
  487. static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
  488. int32_t *data, int n, int pred_order,
  489. int bps, int precision)
  490. {
  491. uint32_t bits;
  492. bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
  493. bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
  494. return bits;
  495. }
  496. /**
  497. * Apply Welch window function to audio block
  498. */
  499. static void apply_welch_window(const int32_t *data, int len, double *w_data)
  500. {
  501. int i, n2;
  502. double w;
  503. double c;
  504. n2 = (len >> 1);
  505. c = 2.0 / (len - 1.0);
  506. for(i=0; i<n2; i++) {
  507. w = c - i - 1.0;
  508. w = 1.0 - (w * w);
  509. w_data[i] = data[i] * w;
  510. w_data[len-1-i] = data[len-1-i] * w;
  511. }
  512. }
  513. /**
  514. * Calculates autocorrelation data from audio samples
  515. * A Welch window function is applied before calculation.
  516. */
  517. static void compute_autocorr(const int32_t *data, int len, int lag,
  518. double *autoc)
  519. {
  520. int i, lag_ptr;
  521. double tmp[len + lag];
  522. double *data1= tmp + lag;
  523. apply_welch_window(data, len, data1);
  524. for(i=0; i<lag; i++){
  525. autoc[i] = 1.0;
  526. data1[i-lag]= 0.0;
  527. }
  528. for(i=0; i<len; i++){
  529. for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
  530. autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
  531. }
  532. }
  533. }
  534. /**
  535. * Levinson-Durbin recursion.
  536. * Produces LPC coefficients from autocorrelation data.
  537. */
  538. static void compute_lpc_coefs(const double *autoc, int max_order,
  539. double lpc[][MAX_LPC_ORDER], double *ref)
  540. {
  541. int i, j, i2;
  542. double r, err, tmp;
  543. double lpc_tmp[MAX_LPC_ORDER];
  544. for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
  545. err = autoc[0];
  546. for(i=0; i<max_order; i++) {
  547. r = -autoc[i+1];
  548. for(j=0; j<i; j++) {
  549. r -= lpc_tmp[j] * autoc[i-j];
  550. }
  551. r /= err;
  552. ref[i] = fabs(r);
  553. err *= 1.0 - (r * r);
  554. i2 = (i >> 1);
  555. lpc_tmp[i] = r;
  556. for(j=0; j<i2; j++) {
  557. tmp = lpc_tmp[j];
  558. lpc_tmp[j] += r * lpc_tmp[i-1-j];
  559. lpc_tmp[i-1-j] += r * tmp;
  560. }
  561. if(i & 1) {
  562. lpc_tmp[j] += lpc_tmp[j] * r;
  563. }
  564. for(j=0; j<=i; j++) {
  565. lpc[i][j] = -lpc_tmp[j];
  566. }
  567. }
  568. }
  569. /**
  570. * Quantize LPC coefficients
  571. */
  572. static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
  573. int32_t *lpc_out, int *shift)
  574. {
  575. int i;
  576. double cmax;
  577. int32_t qmax;
  578. int sh;
  579. /* define maximum levels */
  580. qmax = (1 << (precision - 1)) - 1;
  581. /* find maximum coefficient value */
  582. cmax = 0.0;
  583. for(i=0; i<order; i++) {
  584. cmax= FFMAX(cmax, fabs(lpc_in[i]));
  585. }
  586. /* if maximum value quantizes to zero, return all zeros */
  587. if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
  588. *shift = 0;
  589. memset(lpc_out, 0, sizeof(int32_t) * order);
  590. return;
  591. }
  592. /* calculate level shift which scales max coeff to available bits */
  593. sh = MAX_LPC_SHIFT;
  594. while((cmax * (1 << sh) > qmax) && (sh > 0)) {
  595. sh--;
  596. }
  597. /* since negative shift values are unsupported in decoder, scale down
  598. coefficients instead */
  599. if(sh == 0 && cmax > qmax) {
  600. double scale = ((double)qmax) / cmax;
  601. for(i=0; i<order; i++) {
  602. lpc_in[i] *= scale;
  603. }
  604. }
  605. /* output quantized coefficients and level shift */
  606. for(i=0; i<order; i++) {
  607. lpc_out[i] = (int32_t)(lpc_in[i] * (1 << sh));
  608. }
  609. *shift = sh;
  610. }
  611. static int estimate_best_order(double *ref, int max_order)
  612. {
  613. int i, est;
  614. est = 1;
  615. for(i=max_order-1; i>=0; i--) {
  616. if(ref[i] > 0.10) {
  617. est = i+1;
  618. break;
  619. }
  620. }
  621. return est;
  622. }
  623. /**
  624. * Calculate LPC coefficients for multiple orders
  625. */
  626. static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
  627. int precision, int32_t coefs[][MAX_LPC_ORDER],
  628. int *shift)
  629. {
  630. double autoc[MAX_LPC_ORDER+1];
  631. double ref[MAX_LPC_ORDER];
  632. double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
  633. int i;
  634. int opt_order;
  635. assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
  636. compute_autocorr(samples, blocksize, max_order+1, autoc);
  637. compute_lpc_coefs(autoc, max_order, lpc, ref);
  638. opt_order = estimate_best_order(ref, max_order);
  639. i = opt_order-1;
  640. quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
  641. return opt_order;
  642. }
  643. static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
  644. {
  645. assert(n > 0);
  646. memcpy(res, smp, n * sizeof(int32_t));
  647. }
  648. static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
  649. int order)
  650. {
  651. int i;
  652. for(i=0; i<order; i++) {
  653. res[i] = smp[i];
  654. }
  655. if(order==0){
  656. for(i=order; i<n; i++)
  657. res[i]= smp[i];
  658. }else if(order==1){
  659. for(i=order; i<n; i++)
  660. res[i]= smp[i] - smp[i-1];
  661. }else if(order==2){
  662. for(i=order; i<n; i++)
  663. res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
  664. }else if(order==3){
  665. for(i=order; i<n; i++)
  666. res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
  667. }else{
  668. for(i=order; i<n; i++)
  669. res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
  670. }
  671. }
  672. static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
  673. int order, const int32_t *coefs, int shift)
  674. {
  675. int i, j;
  676. int32_t pred;
  677. for(i=0; i<order; i++) {
  678. res[i] = smp[i];
  679. }
  680. for(i=order; i<n; i++) {
  681. pred = 0;
  682. for(j=0; j<order; j++) {
  683. pred += coefs[j] * smp[i-j-1];
  684. }
  685. res[i] = smp[i] - (pred >> shift);
  686. }
  687. }
  688. static int get_max_p_order(int max_porder, int n, int order)
  689. {
  690. int porder, max_parts;
  691. porder = max_porder;
  692. while(porder > 0) {
  693. max_parts = (1 << porder);
  694. if(!(n % max_parts) && (n > max_parts*order)) {
  695. break;
  696. }
  697. porder--;
  698. }
  699. return porder;
  700. }
  701. static int encode_residual(FlacEncodeContext *ctx, int ch)
  702. {
  703. int i, n;
  704. int min_order, max_order, opt_order, precision;
  705. int porder, min_porder, max_porder;
  706. FlacFrame *frame;
  707. FlacSubframe *sub;
  708. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  709. int shift[MAX_LPC_ORDER];
  710. int32_t *res, *smp;
  711. frame = &ctx->frame;
  712. sub = &frame->subframes[ch];
  713. res = sub->residual;
  714. smp = sub->samples;
  715. n = frame->blocksize;
  716. /* CONSTANT */
  717. for(i=1; i<n; i++) {
  718. if(smp[i] != smp[0]) break;
  719. }
  720. if(i == n) {
  721. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  722. res[0] = smp[0];
  723. return sub->obits;
  724. }
  725. /* VERBATIM */
  726. if(n < 5) {
  727. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  728. encode_residual_verbatim(res, smp, n);
  729. return sub->obits * n;
  730. }
  731. min_order = ctx->options.min_prediction_order;
  732. max_order = ctx->options.max_prediction_order;
  733. min_porder = ctx->options.min_partition_order;
  734. max_porder = ctx->options.max_partition_order;
  735. precision = ctx->options.lpc_coeff_precision;
  736. /* FIXED */
  737. if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
  738. uint32_t bits[MAX_FIXED_ORDER+1];
  739. if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
  740. opt_order = 0;
  741. bits[0] = UINT32_MAX;
  742. for(i=min_order; i<=max_order; i++) {
  743. encode_residual_fixed(res, smp, n, i);
  744. porder = get_max_p_order(max_porder, n, i);
  745. bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, porder, res,
  746. n, i, sub->obits);
  747. if(bits[i] < bits[opt_order]) {
  748. opt_order = i;
  749. }
  750. }
  751. sub->order = opt_order;
  752. sub->type = FLAC_SUBFRAME_FIXED;
  753. sub->type_code = sub->type | sub->order;
  754. if(sub->order != max_order) {
  755. encode_residual_fixed(res, smp, n, sub->order);
  756. porder = get_max_p_order(max_porder, n, sub->order);
  757. return calc_rice_params_fixed(&sub->rc, min_porder, porder, res, n,
  758. sub->order, sub->obits);
  759. }
  760. return bits[sub->order];
  761. }
  762. /* LPC */
  763. sub->order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift);
  764. sub->type = FLAC_SUBFRAME_LPC;
  765. sub->type_code = sub->type | (sub->order-1);
  766. sub->shift = shift[sub->order-1];
  767. for(i=0; i<sub->order; i++) {
  768. sub->coefs[i] = coefs[sub->order-1][i];
  769. }
  770. porder = get_max_p_order(max_porder, n, sub->order);
  771. encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
  772. return calc_rice_params_lpc(&sub->rc, 0, porder, res, n, sub->order,
  773. sub->obits, precision);
  774. }
  775. static int encode_residual_v(FlacEncodeContext *ctx, int ch)
  776. {
  777. int i, n;
  778. FlacFrame *frame;
  779. FlacSubframe *sub;
  780. int32_t *res, *smp;
  781. frame = &ctx->frame;
  782. sub = &frame->subframes[ch];
  783. res = sub->residual;
  784. smp = sub->samples;
  785. n = frame->blocksize;
  786. /* CONSTANT */
  787. for(i=1; i<n; i++) {
  788. if(smp[i] != smp[0]) break;
  789. }
  790. if(i == n) {
  791. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  792. res[0] = smp[0];
  793. return sub->obits;
  794. }
  795. /* VERBATIM */
  796. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  797. encode_residual_verbatim(res, smp, n);
  798. return sub->obits * n;
  799. }
  800. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  801. {
  802. int i, best;
  803. int32_t lt, rt;
  804. uint64_t sum[4];
  805. uint64_t score[4];
  806. int k;
  807. /* calculate sum of 2nd order residual for each channel */
  808. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  809. for(i=2; i<n; i++) {
  810. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  811. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  812. sum[2] += ABS((lt + rt) >> 1);
  813. sum[3] += ABS(lt - rt);
  814. sum[0] += ABS(lt);
  815. sum[1] += ABS(rt);
  816. }
  817. /* estimate bit counts */
  818. for(i=0; i<4; i++) {
  819. k = find_optimal_param(2*sum[i], n);
  820. sum[i] = rice_encode_count(2*sum[i], n, k);
  821. }
  822. /* calculate score for each mode */
  823. score[0] = sum[0] + sum[1];
  824. score[1] = sum[0] + sum[3];
  825. score[2] = sum[1] + sum[3];
  826. score[3] = sum[2] + sum[3];
  827. /* return mode with lowest score */
  828. best = 0;
  829. for(i=1; i<4; i++) {
  830. if(score[i] < score[best]) {
  831. best = i;
  832. }
  833. }
  834. if(best == 0) {
  835. return FLAC_CHMODE_LEFT_RIGHT;
  836. } else if(best == 1) {
  837. return FLAC_CHMODE_LEFT_SIDE;
  838. } else if(best == 2) {
  839. return FLAC_CHMODE_RIGHT_SIDE;
  840. } else {
  841. return FLAC_CHMODE_MID_SIDE;
  842. }
  843. }
  844. /**
  845. * Perform stereo channel decorrelation
  846. */
  847. static void channel_decorrelation(FlacEncodeContext *ctx)
  848. {
  849. FlacFrame *frame;
  850. int32_t *left, *right;
  851. int i, n;
  852. frame = &ctx->frame;
  853. n = frame->blocksize;
  854. left = frame->subframes[0].samples;
  855. right = frame->subframes[1].samples;
  856. if(ctx->channels != 2) {
  857. frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
  858. return;
  859. }
  860. frame->ch_mode = estimate_stereo_mode(left, right, n);
  861. /* perform decorrelation and adjust bits-per-sample */
  862. if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
  863. return;
  864. }
  865. if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
  866. int32_t tmp;
  867. for(i=0; i<n; i++) {
  868. tmp = left[i];
  869. left[i] = (tmp + right[i]) >> 1;
  870. right[i] = tmp - right[i];
  871. }
  872. frame->subframes[1].obits++;
  873. } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
  874. for(i=0; i<n; i++) {
  875. right[i] = left[i] - right[i];
  876. }
  877. frame->subframes[1].obits++;
  878. } else {
  879. for(i=0; i<n; i++) {
  880. left[i] -= right[i];
  881. }
  882. frame->subframes[0].obits++;
  883. }
  884. }
  885. static void put_sbits(PutBitContext *pb, int bits, int32_t val)
  886. {
  887. assert(bits >= 0 && bits <= 31);
  888. put_bits(pb, bits, val & ((1<<bits)-1));
  889. }
  890. static void write_utf8(PutBitContext *pb, uint32_t val)
  891. {
  892. int bytes, shift;
  893. if(val < 0x80){
  894. put_bits(pb, 8, val);
  895. return;
  896. }
  897. bytes= (av_log2(val)+4) / 5;
  898. shift = (bytes - 1) * 6;
  899. put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
  900. while(shift >= 6){
  901. shift -= 6;
  902. put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
  903. }
  904. }
  905. static void output_frame_header(FlacEncodeContext *s)
  906. {
  907. FlacFrame *frame;
  908. int crc;
  909. frame = &s->frame;
  910. put_bits(&s->pb, 16, 0xFFF8);
  911. put_bits(&s->pb, 4, frame->bs_code[0]);
  912. put_bits(&s->pb, 4, s->sr_code[0]);
  913. if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
  914. put_bits(&s->pb, 4, s->ch_code);
  915. } else {
  916. put_bits(&s->pb, 4, frame->ch_mode);
  917. }
  918. put_bits(&s->pb, 3, 4); /* bits-per-sample code */
  919. put_bits(&s->pb, 1, 0);
  920. write_utf8(&s->pb, s->frame_count);
  921. if(frame->bs_code[0] == 6) {
  922. put_bits(&s->pb, 8, frame->bs_code[1]);
  923. } else if(frame->bs_code[0] == 7) {
  924. put_bits(&s->pb, 16, frame->bs_code[1]);
  925. }
  926. if(s->sr_code[0] == 12) {
  927. put_bits(&s->pb, 8, s->sr_code[1]);
  928. } else if(s->sr_code[0] > 12) {
  929. put_bits(&s->pb, 16, s->sr_code[1]);
  930. }
  931. flush_put_bits(&s->pb);
  932. crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
  933. put_bits(&s->pb, 8, crc);
  934. }
  935. static void output_subframe_constant(FlacEncodeContext *s, int ch)
  936. {
  937. FlacSubframe *sub;
  938. int32_t res;
  939. sub = &s->frame.subframes[ch];
  940. res = sub->residual[0];
  941. put_sbits(&s->pb, sub->obits, res);
  942. }
  943. static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
  944. {
  945. int i;
  946. FlacFrame *frame;
  947. FlacSubframe *sub;
  948. int32_t res;
  949. frame = &s->frame;
  950. sub = &frame->subframes[ch];
  951. for(i=0; i<frame->blocksize; i++) {
  952. res = sub->residual[i];
  953. put_sbits(&s->pb, sub->obits, res);
  954. }
  955. }
  956. static void output_residual(FlacEncodeContext *ctx, int ch)
  957. {
  958. int i, j, p, n, parts;
  959. int k, porder, psize, res_cnt;
  960. FlacFrame *frame;
  961. FlacSubframe *sub;
  962. int32_t *res;
  963. frame = &ctx->frame;
  964. sub = &frame->subframes[ch];
  965. res = sub->residual;
  966. n = frame->blocksize;
  967. /* rice-encoded block */
  968. put_bits(&ctx->pb, 2, 0);
  969. /* partition order */
  970. porder = sub->rc.porder;
  971. psize = n >> porder;
  972. parts = (1 << porder);
  973. put_bits(&ctx->pb, 4, porder);
  974. res_cnt = psize - sub->order;
  975. /* residual */
  976. j = sub->order;
  977. for(p=0; p<parts; p++) {
  978. k = sub->rc.params[p];
  979. put_bits(&ctx->pb, 4, k);
  980. if(p == 1) res_cnt = psize;
  981. for(i=0; i<res_cnt && j<n; i++, j++) {
  982. set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
  983. }
  984. }
  985. }
  986. static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
  987. {
  988. int i;
  989. FlacFrame *frame;
  990. FlacSubframe *sub;
  991. frame = &ctx->frame;
  992. sub = &frame->subframes[ch];
  993. /* warm-up samples */
  994. for(i=0; i<sub->order; i++) {
  995. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  996. }
  997. /* residual */
  998. output_residual(ctx, ch);
  999. }
  1000. static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
  1001. {
  1002. int i, cbits;
  1003. FlacFrame *frame;
  1004. FlacSubframe *sub;
  1005. frame = &ctx->frame;
  1006. sub = &frame->subframes[ch];
  1007. /* warm-up samples */
  1008. for(i=0; i<sub->order; i++) {
  1009. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  1010. }
  1011. /* LPC coefficients */
  1012. cbits = ctx->options.lpc_coeff_precision;
  1013. put_bits(&ctx->pb, 4, cbits-1);
  1014. put_sbits(&ctx->pb, 5, sub->shift);
  1015. for(i=0; i<sub->order; i++) {
  1016. put_sbits(&ctx->pb, cbits, sub->coefs[i]);
  1017. }
  1018. /* residual */
  1019. output_residual(ctx, ch);
  1020. }
  1021. static void output_subframes(FlacEncodeContext *s)
  1022. {
  1023. FlacFrame *frame;
  1024. FlacSubframe *sub;
  1025. int ch;
  1026. frame = &s->frame;
  1027. for(ch=0; ch<s->channels; ch++) {
  1028. sub = &frame->subframes[ch];
  1029. /* subframe header */
  1030. put_bits(&s->pb, 1, 0);
  1031. put_bits(&s->pb, 6, sub->type_code);
  1032. put_bits(&s->pb, 1, 0); /* no wasted bits */
  1033. /* subframe */
  1034. if(sub->type == FLAC_SUBFRAME_CONSTANT) {
  1035. output_subframe_constant(s, ch);
  1036. } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
  1037. output_subframe_verbatim(s, ch);
  1038. } else if(sub->type == FLAC_SUBFRAME_FIXED) {
  1039. output_subframe_fixed(s, ch);
  1040. } else if(sub->type == FLAC_SUBFRAME_LPC) {
  1041. output_subframe_lpc(s, ch);
  1042. }
  1043. }
  1044. }
  1045. static void output_frame_footer(FlacEncodeContext *s)
  1046. {
  1047. int crc;
  1048. flush_put_bits(&s->pb);
  1049. crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
  1050. put_bits(&s->pb, 16, crc);
  1051. flush_put_bits(&s->pb);
  1052. }
  1053. static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  1054. int buf_size, void *data)
  1055. {
  1056. int ch;
  1057. FlacEncodeContext *s;
  1058. int16_t *samples = data;
  1059. int out_bytes;
  1060. s = avctx->priv_data;
  1061. s->blocksize = avctx->frame_size;
  1062. init_frame(s);
  1063. copy_samples(s, samples);
  1064. channel_decorrelation(s);
  1065. for(ch=0; ch<s->channels; ch++) {
  1066. encode_residual(s, ch);
  1067. }
  1068. init_put_bits(&s->pb, frame, buf_size);
  1069. output_frame_header(s);
  1070. output_subframes(s);
  1071. output_frame_footer(s);
  1072. out_bytes = put_bits_count(&s->pb) >> 3;
  1073. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  1074. /* frame too large. use verbatim mode */
  1075. for(ch=0; ch<s->channels; ch++) {
  1076. encode_residual_v(s, ch);
  1077. }
  1078. init_put_bits(&s->pb, frame, buf_size);
  1079. output_frame_header(s);
  1080. output_subframes(s);
  1081. output_frame_footer(s);
  1082. out_bytes = put_bits_count(&s->pb) >> 3;
  1083. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  1084. /* still too large. must be an error. */
  1085. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  1086. return -1;
  1087. }
  1088. }
  1089. s->frame_count++;
  1090. return out_bytes;
  1091. }
  1092. static int flac_encode_close(AVCodecContext *avctx)
  1093. {
  1094. av_freep(&avctx->extradata);
  1095. avctx->extradata_size = 0;
  1096. av_freep(&avctx->coded_frame);
  1097. return 0;
  1098. }
  1099. AVCodec flac_encoder = {
  1100. "flac",
  1101. CODEC_TYPE_AUDIO,
  1102. CODEC_ID_FLAC,
  1103. sizeof(FlacEncodeContext),
  1104. flac_encode_init,
  1105. flac_encode_frame,
  1106. flac_encode_close,
  1107. NULL,
  1108. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  1109. };