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.

1382 lines
40KB

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