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.

1467 lines
43KB

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