flacenc.c 43 KB

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