flacenc.c 40 KB

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