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.

1372 lines
40KB

  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];
  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, lag_ptr;
  544. double tmp[len + lag];
  545. double *data1= tmp + lag;
  546. apply_welch_window(data, len, data1);
  547. for(i=0; i<lag; i++){
  548. autoc[i] = 1.0;
  549. data1[i-lag]= 0.0;
  550. }
  551. for(i=0; i<len; i++){
  552. for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
  553. autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
  554. }
  555. }
  556. }
  557. /**
  558. * Levinson-Durbin recursion.
  559. * Produces LPC coefficients from autocorrelation data.
  560. */
  561. static void compute_lpc_coefs(const double *autoc, int max_order,
  562. double lpc[][MAX_LPC_ORDER], double *ref)
  563. {
  564. int i, j, i2;
  565. double r, err, tmp;
  566. double lpc_tmp[MAX_LPC_ORDER];
  567. for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
  568. err = autoc[0];
  569. for(i=0; i<max_order; i++) {
  570. r = -autoc[i+1];
  571. for(j=0; j<i; j++) {
  572. r -= lpc_tmp[j] * autoc[i-j];
  573. }
  574. r /= err;
  575. ref[i] = fabs(r);
  576. err *= 1.0 - (r * r);
  577. i2 = (i >> 1);
  578. lpc_tmp[i] = r;
  579. for(j=0; j<i2; j++) {
  580. tmp = lpc_tmp[j];
  581. lpc_tmp[j] += r * lpc_tmp[i-1-j];
  582. lpc_tmp[i-1-j] += r * tmp;
  583. }
  584. if(i & 1) {
  585. lpc_tmp[j] += lpc_tmp[j] * r;
  586. }
  587. for(j=0; j<=i; j++) {
  588. lpc[i][j] = -lpc_tmp[j];
  589. }
  590. }
  591. }
  592. /**
  593. * Quantize LPC coefficients
  594. */
  595. static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
  596. int32_t *lpc_out, int *shift)
  597. {
  598. int i;
  599. double cmax, error;
  600. int32_t qmax;
  601. int sh;
  602. /* define maximum levels */
  603. qmax = (1 << (precision - 1)) - 1;
  604. /* find maximum coefficient value */
  605. cmax = 0.0;
  606. for(i=0; i<order; i++) {
  607. cmax= FFMAX(cmax, fabs(lpc_in[i]));
  608. }
  609. /* if maximum value quantizes to zero, return all zeros */
  610. if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
  611. *shift = 0;
  612. memset(lpc_out, 0, sizeof(int32_t) * order);
  613. return;
  614. }
  615. /* calculate level shift which scales max coeff to available bits */
  616. sh = MAX_LPC_SHIFT;
  617. while((cmax * (1 << sh) > qmax) && (sh > 0)) {
  618. sh--;
  619. }
  620. /* since negative shift values are unsupported in decoder, scale down
  621. coefficients instead */
  622. if(sh == 0 && cmax > qmax) {
  623. double scale = ((double)qmax) / cmax;
  624. for(i=0; i<order; i++) {
  625. lpc_in[i] *= scale;
  626. }
  627. }
  628. /* output quantized coefficients and level shift */
  629. error=0;
  630. for(i=0; i<order; i++) {
  631. error += lpc_in[i] * (1 << sh);
  632. lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
  633. error -= lpc_out[i];
  634. }
  635. *shift = sh;
  636. }
  637. static int estimate_best_order(double *ref, int max_order)
  638. {
  639. int i, est;
  640. est = 1;
  641. for(i=max_order-1; i>=0; i--) {
  642. if(ref[i] > 0.10) {
  643. est = i+1;
  644. break;
  645. }
  646. }
  647. return est;
  648. }
  649. /**
  650. * Calculate LPC coefficients for multiple orders
  651. */
  652. static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
  653. int precision, int32_t coefs[][MAX_LPC_ORDER],
  654. int *shift, int use_lpc, int omethod)
  655. {
  656. double autoc[MAX_LPC_ORDER+1];
  657. double ref[MAX_LPC_ORDER];
  658. double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
  659. int i, j, pass;
  660. int opt_order;
  661. assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
  662. if(use_lpc == 1){
  663. compute_autocorr(samples, blocksize, max_order+1, autoc);
  664. compute_lpc_coefs(autoc, max_order, lpc, ref);
  665. }else{
  666. LLSModel m[2];
  667. double var[MAX_LPC_ORDER+1], eval, weight;
  668. for(pass=0; pass<use_lpc-1; pass++){
  669. av_init_lls(&m[pass&1], max_order);
  670. weight=0;
  671. for(i=max_order; i<blocksize; i++){
  672. for(j=0; j<=max_order; j++)
  673. var[j]= samples[i-j];
  674. if(pass){
  675. eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
  676. eval= (512>>pass) + fabs(eval - var[0]);
  677. for(j=0; j<=max_order; j++)
  678. var[j]/= sqrt(eval);
  679. weight += 1/eval;
  680. }else
  681. weight++;
  682. av_update_lls(&m[pass&1], var, 1.0);
  683. }
  684. av_solve_lls(&m[pass&1], 0.001, 0);
  685. }
  686. for(i=0; i<max_order; i++){
  687. for(j=0; j<max_order; j++)
  688. lpc[i][j]= m[(pass-1)&1].coeff[i][j];
  689. ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
  690. }
  691. for(i=max_order-1; i>0; i--)
  692. ref[i] = ref[i-1] - ref[i];
  693. }
  694. opt_order = max_order;
  695. if(omethod == ORDER_METHOD_EST) {
  696. opt_order = estimate_best_order(ref, max_order);
  697. i = opt_order-1;
  698. quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
  699. } else {
  700. for(i=0; i<max_order; i++) {
  701. quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
  702. }
  703. }
  704. return opt_order;
  705. }
  706. static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
  707. {
  708. assert(n > 0);
  709. memcpy(res, smp, n * sizeof(int32_t));
  710. }
  711. static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
  712. int order)
  713. {
  714. int i;
  715. for(i=0; i<order; i++) {
  716. res[i] = smp[i];
  717. }
  718. if(order==0){
  719. for(i=order; i<n; i++)
  720. res[i]= smp[i];
  721. }else if(order==1){
  722. for(i=order; i<n; i++)
  723. res[i]= smp[i] - smp[i-1];
  724. }else if(order==2){
  725. for(i=order; i<n; i++)
  726. res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
  727. }else if(order==3){
  728. for(i=order; i<n; i++)
  729. res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
  730. }else{
  731. for(i=order; i<n; i++)
  732. res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
  733. }
  734. }
  735. static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
  736. int order, const int32_t *coefs, int shift)
  737. {
  738. int i, j;
  739. int32_t pred;
  740. for(i=0; i<order; i++) {
  741. res[i] = smp[i];
  742. }
  743. for(i=order; i<n; i++) {
  744. pred = 0;
  745. for(j=0; j<order; j++) {
  746. pred += coefs[j] * smp[i-j-1];
  747. }
  748. res[i] = smp[i] - (pred >> shift);
  749. }
  750. }
  751. static int encode_residual(FlacEncodeContext *ctx, int ch)
  752. {
  753. int i, n;
  754. int min_order, max_order, opt_order, precision, omethod;
  755. int min_porder, max_porder;
  756. FlacFrame *frame;
  757. FlacSubframe *sub;
  758. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  759. int shift[MAX_LPC_ORDER];
  760. int32_t *res, *smp;
  761. frame = &ctx->frame;
  762. sub = &frame->subframes[ch];
  763. res = sub->residual;
  764. smp = sub->samples;
  765. n = frame->blocksize;
  766. /* CONSTANT */
  767. for(i=1; i<n; i++) {
  768. if(smp[i] != smp[0]) break;
  769. }
  770. if(i == n) {
  771. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  772. res[0] = smp[0];
  773. return sub->obits;
  774. }
  775. /* VERBATIM */
  776. if(n < 5) {
  777. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  778. encode_residual_verbatim(res, smp, n);
  779. return sub->obits * n;
  780. }
  781. min_order = ctx->options.min_prediction_order;
  782. max_order = ctx->options.max_prediction_order;
  783. min_porder = ctx->options.min_partition_order;
  784. max_porder = ctx->options.max_partition_order;
  785. precision = ctx->options.lpc_coeff_precision;
  786. omethod = ctx->options.prediction_order_method;
  787. /* FIXED */
  788. if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
  789. uint32_t bits[MAX_FIXED_ORDER+1];
  790. if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
  791. opt_order = 0;
  792. bits[0] = UINT32_MAX;
  793. for(i=min_order; i<=max_order; i++) {
  794. encode_residual_fixed(res, smp, n, i);
  795. bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
  796. n, i, sub->obits);
  797. if(bits[i] < bits[opt_order]) {
  798. opt_order = i;
  799. }
  800. }
  801. sub->order = opt_order;
  802. sub->type = FLAC_SUBFRAME_FIXED;
  803. sub->type_code = sub->type | sub->order;
  804. if(sub->order != max_order) {
  805. encode_residual_fixed(res, smp, n, sub->order);
  806. return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
  807. sub->order, sub->obits);
  808. }
  809. return bits[sub->order];
  810. }
  811. /* LPC */
  812. opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
  813. if(omethod == ORDER_METHOD_2LEVEL ||
  814. omethod == ORDER_METHOD_4LEVEL ||
  815. omethod == ORDER_METHOD_8LEVEL) {
  816. int levels = 1 << omethod;
  817. uint32_t bits[levels];
  818. int order;
  819. int opt_index = levels-1;
  820. opt_order = max_order-1;
  821. bits[opt_index] = UINT32_MAX;
  822. for(i=levels-1; i>=0; i--) {
  823. order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
  824. if(order < 0) order = 0;
  825. encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
  826. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  827. res, n, order+1, sub->obits, precision);
  828. if(bits[i] < bits[opt_index]) {
  829. opt_index = i;
  830. opt_order = order;
  831. }
  832. }
  833. opt_order++;
  834. } else if(omethod == ORDER_METHOD_SEARCH) {
  835. // brute-force optimal order search
  836. uint32_t bits[MAX_LPC_ORDER];
  837. opt_order = 0;
  838. bits[0] = UINT32_MAX;
  839. for(i=min_order-1; i<max_order; i++) {
  840. encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
  841. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  842. res, n, i+1, sub->obits, precision);
  843. if(bits[i] < bits[opt_order]) {
  844. opt_order = i;
  845. }
  846. }
  847. opt_order++;
  848. } else if(omethod == ORDER_METHOD_LOG) {
  849. uint32_t bits[MAX_LPC_ORDER];
  850. int step;
  851. opt_order= min_order - 1 + (max_order-min_order)/3;
  852. memset(bits, -1, sizeof(bits));
  853. for(step=16 ;step; step>>=1){
  854. int last= opt_order;
  855. for(i=last-step; i<=last+step; i+= step){
  856. if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
  857. continue;
  858. encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
  859. bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
  860. res, n, i+1, sub->obits, precision);
  861. if(bits[i] < bits[opt_order])
  862. opt_order= i;
  863. }
  864. }
  865. opt_order++;
  866. }
  867. sub->order = opt_order;
  868. sub->type = FLAC_SUBFRAME_LPC;
  869. sub->type_code = sub->type | (sub->order-1);
  870. sub->shift = shift[sub->order-1];
  871. for(i=0; i<sub->order; i++) {
  872. sub->coefs[i] = coefs[sub->order-1][i];
  873. }
  874. encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
  875. return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
  876. sub->obits, precision);
  877. }
  878. static int encode_residual_v(FlacEncodeContext *ctx, int ch)
  879. {
  880. int i, n;
  881. FlacFrame *frame;
  882. FlacSubframe *sub;
  883. int32_t *res, *smp;
  884. frame = &ctx->frame;
  885. sub = &frame->subframes[ch];
  886. res = sub->residual;
  887. smp = sub->samples;
  888. n = frame->blocksize;
  889. /* CONSTANT */
  890. for(i=1; i<n; i++) {
  891. if(smp[i] != smp[0]) break;
  892. }
  893. if(i == n) {
  894. sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
  895. res[0] = smp[0];
  896. return sub->obits;
  897. }
  898. /* VERBATIM */
  899. sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
  900. encode_residual_verbatim(res, smp, n);
  901. return sub->obits * n;
  902. }
  903. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  904. {
  905. int i, best;
  906. int32_t lt, rt;
  907. uint64_t sum[4];
  908. uint64_t score[4];
  909. int k;
  910. /* calculate sum of 2nd order residual for each channel */
  911. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  912. for(i=2; i<n; i++) {
  913. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  914. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  915. sum[2] += FFABS((lt + rt) >> 1);
  916. sum[3] += FFABS(lt - rt);
  917. sum[0] += FFABS(lt);
  918. sum[1] += FFABS(rt);
  919. }
  920. /* estimate bit counts */
  921. for(i=0; i<4; i++) {
  922. k = find_optimal_param(2*sum[i], n);
  923. sum[i] = rice_encode_count(2*sum[i], n, k);
  924. }
  925. /* calculate score for each mode */
  926. score[0] = sum[0] + sum[1];
  927. score[1] = sum[0] + sum[3];
  928. score[2] = sum[1] + sum[3];
  929. score[3] = sum[2] + sum[3];
  930. /* return mode with lowest score */
  931. best = 0;
  932. for(i=1; i<4; i++) {
  933. if(score[i] < score[best]) {
  934. best = i;
  935. }
  936. }
  937. if(best == 0) {
  938. return FLAC_CHMODE_LEFT_RIGHT;
  939. } else if(best == 1) {
  940. return FLAC_CHMODE_LEFT_SIDE;
  941. } else if(best == 2) {
  942. return FLAC_CHMODE_RIGHT_SIDE;
  943. } else {
  944. return FLAC_CHMODE_MID_SIDE;
  945. }
  946. }
  947. /**
  948. * Perform stereo channel decorrelation
  949. */
  950. static void channel_decorrelation(FlacEncodeContext *ctx)
  951. {
  952. FlacFrame *frame;
  953. int32_t *left, *right;
  954. int i, n;
  955. frame = &ctx->frame;
  956. n = frame->blocksize;
  957. left = frame->subframes[0].samples;
  958. right = frame->subframes[1].samples;
  959. if(ctx->channels != 2) {
  960. frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
  961. return;
  962. }
  963. frame->ch_mode = estimate_stereo_mode(left, right, n);
  964. /* perform decorrelation and adjust bits-per-sample */
  965. if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
  966. return;
  967. }
  968. if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
  969. int32_t tmp;
  970. for(i=0; i<n; i++) {
  971. tmp = left[i];
  972. left[i] = (tmp + right[i]) >> 1;
  973. right[i] = tmp - right[i];
  974. }
  975. frame->subframes[1].obits++;
  976. } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
  977. for(i=0; i<n; i++) {
  978. right[i] = left[i] - right[i];
  979. }
  980. frame->subframes[1].obits++;
  981. } else {
  982. for(i=0; i<n; i++) {
  983. left[i] -= right[i];
  984. }
  985. frame->subframes[0].obits++;
  986. }
  987. }
  988. static void put_sbits(PutBitContext *pb, int bits, int32_t val)
  989. {
  990. assert(bits >= 0 && bits <= 31);
  991. put_bits(pb, bits, val & ((1<<bits)-1));
  992. }
  993. static void write_utf8(PutBitContext *pb, uint32_t val)
  994. {
  995. uint8_t tmp;
  996. PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
  997. }
  998. static void output_frame_header(FlacEncodeContext *s)
  999. {
  1000. FlacFrame *frame;
  1001. int crc;
  1002. frame = &s->frame;
  1003. put_bits(&s->pb, 16, 0xFFF8);
  1004. put_bits(&s->pb, 4, frame->bs_code[0]);
  1005. put_bits(&s->pb, 4, s->sr_code[0]);
  1006. if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
  1007. put_bits(&s->pb, 4, s->ch_code);
  1008. } else {
  1009. put_bits(&s->pb, 4, frame->ch_mode);
  1010. }
  1011. put_bits(&s->pb, 3, 4); /* bits-per-sample code */
  1012. put_bits(&s->pb, 1, 0);
  1013. write_utf8(&s->pb, s->frame_count);
  1014. if(frame->bs_code[0] == 6) {
  1015. put_bits(&s->pb, 8, frame->bs_code[1]);
  1016. } else if(frame->bs_code[0] == 7) {
  1017. put_bits(&s->pb, 16, frame->bs_code[1]);
  1018. }
  1019. if(s->sr_code[0] == 12) {
  1020. put_bits(&s->pb, 8, s->sr_code[1]);
  1021. } else if(s->sr_code[0] > 12) {
  1022. put_bits(&s->pb, 16, s->sr_code[1]);
  1023. }
  1024. flush_put_bits(&s->pb);
  1025. crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
  1026. put_bits(&s->pb, 8, crc);
  1027. }
  1028. static void output_subframe_constant(FlacEncodeContext *s, int ch)
  1029. {
  1030. FlacSubframe *sub;
  1031. int32_t res;
  1032. sub = &s->frame.subframes[ch];
  1033. res = sub->residual[0];
  1034. put_sbits(&s->pb, sub->obits, res);
  1035. }
  1036. static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
  1037. {
  1038. int i;
  1039. FlacFrame *frame;
  1040. FlacSubframe *sub;
  1041. int32_t res;
  1042. frame = &s->frame;
  1043. sub = &frame->subframes[ch];
  1044. for(i=0; i<frame->blocksize; i++) {
  1045. res = sub->residual[i];
  1046. put_sbits(&s->pb, sub->obits, res);
  1047. }
  1048. }
  1049. static void output_residual(FlacEncodeContext *ctx, int ch)
  1050. {
  1051. int i, j, p, n, parts;
  1052. int k, porder, psize, res_cnt;
  1053. FlacFrame *frame;
  1054. FlacSubframe *sub;
  1055. int32_t *res;
  1056. frame = &ctx->frame;
  1057. sub = &frame->subframes[ch];
  1058. res = sub->residual;
  1059. n = frame->blocksize;
  1060. /* rice-encoded block */
  1061. put_bits(&ctx->pb, 2, 0);
  1062. /* partition order */
  1063. porder = sub->rc.porder;
  1064. psize = n >> porder;
  1065. parts = (1 << porder);
  1066. put_bits(&ctx->pb, 4, porder);
  1067. res_cnt = psize - sub->order;
  1068. /* residual */
  1069. j = sub->order;
  1070. for(p=0; p<parts; p++) {
  1071. k = sub->rc.params[p];
  1072. put_bits(&ctx->pb, 4, k);
  1073. if(p == 1) res_cnt = psize;
  1074. for(i=0; i<res_cnt && j<n; i++, j++) {
  1075. set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
  1076. }
  1077. }
  1078. }
  1079. static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
  1080. {
  1081. int i;
  1082. FlacFrame *frame;
  1083. FlacSubframe *sub;
  1084. frame = &ctx->frame;
  1085. sub = &frame->subframes[ch];
  1086. /* warm-up samples */
  1087. for(i=0; i<sub->order; i++) {
  1088. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  1089. }
  1090. /* residual */
  1091. output_residual(ctx, ch);
  1092. }
  1093. static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
  1094. {
  1095. int i, cbits;
  1096. FlacFrame *frame;
  1097. FlacSubframe *sub;
  1098. frame = &ctx->frame;
  1099. sub = &frame->subframes[ch];
  1100. /* warm-up samples */
  1101. for(i=0; i<sub->order; i++) {
  1102. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  1103. }
  1104. /* LPC coefficients */
  1105. cbits = ctx->options.lpc_coeff_precision;
  1106. put_bits(&ctx->pb, 4, cbits-1);
  1107. put_sbits(&ctx->pb, 5, sub->shift);
  1108. for(i=0; i<sub->order; i++) {
  1109. put_sbits(&ctx->pb, cbits, sub->coefs[i]);
  1110. }
  1111. /* residual */
  1112. output_residual(ctx, ch);
  1113. }
  1114. static void output_subframes(FlacEncodeContext *s)
  1115. {
  1116. FlacFrame *frame;
  1117. FlacSubframe *sub;
  1118. int ch;
  1119. frame = &s->frame;
  1120. for(ch=0; ch<s->channels; ch++) {
  1121. sub = &frame->subframes[ch];
  1122. /* subframe header */
  1123. put_bits(&s->pb, 1, 0);
  1124. put_bits(&s->pb, 6, sub->type_code);
  1125. put_bits(&s->pb, 1, 0); /* no wasted bits */
  1126. /* subframe */
  1127. if(sub->type == FLAC_SUBFRAME_CONSTANT) {
  1128. output_subframe_constant(s, ch);
  1129. } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
  1130. output_subframe_verbatim(s, ch);
  1131. } else if(sub->type == FLAC_SUBFRAME_FIXED) {
  1132. output_subframe_fixed(s, ch);
  1133. } else if(sub->type == FLAC_SUBFRAME_LPC) {
  1134. output_subframe_lpc(s, ch);
  1135. }
  1136. }
  1137. }
  1138. static void output_frame_footer(FlacEncodeContext *s)
  1139. {
  1140. int crc;
  1141. flush_put_bits(&s->pb);
  1142. crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
  1143. put_bits(&s->pb, 16, crc);
  1144. flush_put_bits(&s->pb);
  1145. }
  1146. static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  1147. int buf_size, void *data)
  1148. {
  1149. int ch;
  1150. FlacEncodeContext *s;
  1151. int16_t *samples = data;
  1152. int out_bytes;
  1153. s = avctx->priv_data;
  1154. s->blocksize = avctx->frame_size;
  1155. init_frame(s);
  1156. copy_samples(s, samples);
  1157. channel_decorrelation(s);
  1158. for(ch=0; ch<s->channels; ch++) {
  1159. encode_residual(s, ch);
  1160. }
  1161. init_put_bits(&s->pb, frame, buf_size);
  1162. output_frame_header(s);
  1163. output_subframes(s);
  1164. output_frame_footer(s);
  1165. out_bytes = put_bits_count(&s->pb) >> 3;
  1166. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  1167. /* frame too large. use verbatim mode */
  1168. for(ch=0; ch<s->channels; ch++) {
  1169. encode_residual_v(s, ch);
  1170. }
  1171. init_put_bits(&s->pb, frame, buf_size);
  1172. output_frame_header(s);
  1173. output_subframes(s);
  1174. output_frame_footer(s);
  1175. out_bytes = put_bits_count(&s->pb) >> 3;
  1176. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  1177. /* still too large. must be an error. */
  1178. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  1179. return -1;
  1180. }
  1181. }
  1182. s->frame_count++;
  1183. return out_bytes;
  1184. }
  1185. static int flac_encode_close(AVCodecContext *avctx)
  1186. {
  1187. av_freep(&avctx->extradata);
  1188. avctx->extradata_size = 0;
  1189. av_freep(&avctx->coded_frame);
  1190. return 0;
  1191. }
  1192. AVCodec flac_encoder = {
  1193. "flac",
  1194. CODEC_TYPE_AUDIO,
  1195. CODEC_ID_FLAC,
  1196. sizeof(FlacEncodeContext),
  1197. flac_encode_init,
  1198. flac_encode_frame,
  1199. flac_encode_close,
  1200. NULL,
  1201. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  1202. };