flacenc.c 40 KB

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