flacenc.c 40 KB

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