alacenc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /**
  2. * ALAC audio encoder
  3. * Copyright (c) 2008 Jaikrishnan Menon <realityman@gmx.net>
  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 "avcodec.h"
  22. #include "bitstream.h"
  23. #include "dsputil.h"
  24. #include "lpc.h"
  25. #define DEFAULT_FRAME_SIZE 4096
  26. #define DEFAULT_SAMPLE_SIZE 16
  27. #define MAX_CHANNELS 8
  28. #define ALAC_EXTRADATA_SIZE 36
  29. #define ALAC_FRAME_HEADER_SIZE 55
  30. #define ALAC_FRAME_FOOTER_SIZE 3
  31. #define ALAC_ESCAPE_CODE 0x1FF
  32. #define ALAC_MAX_LPC_ORDER 30
  33. #define DEFAULT_MAX_PRED_ORDER 6
  34. #define DEFAULT_MIN_PRED_ORDER 4
  35. #define ALAC_MAX_LPC_PRECISION 9
  36. #define ALAC_MAX_LPC_SHIFT 9
  37. #define ALAC_CHMODE_LEFT_RIGHT 0
  38. #define ALAC_CHMODE_LEFT_SIDE 1
  39. #define ALAC_CHMODE_RIGHT_SIDE 2
  40. #define ALAC_CHMODE_MID_SIDE 3
  41. typedef struct RiceContext {
  42. int history_mult;
  43. int initial_history;
  44. int k_modifier;
  45. int rice_modifier;
  46. } RiceContext;
  47. typedef struct LPCContext {
  48. int lpc_order;
  49. int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
  50. int lpc_quant;
  51. } LPCContext;
  52. typedef struct AlacEncodeContext {
  53. int compression_level;
  54. int min_prediction_order;
  55. int max_prediction_order;
  56. int max_coded_frame_size;
  57. int write_sample_size;
  58. int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
  59. int32_t predictor_buf[DEFAULT_FRAME_SIZE];
  60. int interlacing_shift;
  61. int interlacing_leftweight;
  62. PutBitContext pbctx;
  63. RiceContext rc;
  64. LPCContext lpc[MAX_CHANNELS];
  65. DSPContext dspctx;
  66. AVCodecContext *avctx;
  67. } AlacEncodeContext;
  68. static void init_sample_buffers(AlacEncodeContext *s, int16_t *input_samples)
  69. {
  70. int ch, i;
  71. for(ch=0;ch<s->avctx->channels;ch++) {
  72. int16_t *sptr = input_samples + ch;
  73. for(i=0;i<s->avctx->frame_size;i++) {
  74. s->sample_buf[ch][i] = *sptr;
  75. sptr += s->avctx->channels;
  76. }
  77. }
  78. }
  79. static void encode_scalar(AlacEncodeContext *s, int x, int k, int write_sample_size)
  80. {
  81. int divisor, q, r;
  82. k = FFMIN(k, s->rc.k_modifier);
  83. divisor = (1<<k) - 1;
  84. q = x / divisor;
  85. r = x % divisor;
  86. if(q > 8) {
  87. // write escape code and sample value directly
  88. put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
  89. put_bits(&s->pbctx, write_sample_size, x);
  90. } else {
  91. if(q)
  92. put_bits(&s->pbctx, q, (1<<q) - 1);
  93. put_bits(&s->pbctx, 1, 0);
  94. if(k != 1) {
  95. if(r > 0)
  96. put_bits(&s->pbctx, k, r+1);
  97. else
  98. put_bits(&s->pbctx, k-1, 0);
  99. }
  100. }
  101. }
  102. static void write_frame_header(AlacEncodeContext *s, int is_verbatim)
  103. {
  104. put_bits(&s->pbctx, 3, s->avctx->channels-1); // No. of channels -1
  105. put_bits(&s->pbctx, 16, 0); // Seems to be zero
  106. put_bits(&s->pbctx, 1, 1); // Sample count is in the header
  107. put_bits(&s->pbctx, 2, 0); // FIXME: Wasted bytes field
  108. put_bits(&s->pbctx, 1, is_verbatim); // Audio block is verbatim
  109. put_bits(&s->pbctx, 32, s->avctx->frame_size); // No. of samples in the frame
  110. }
  111. static void calc_predictor_params(AlacEncodeContext *s, int ch)
  112. {
  113. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  114. int shift[MAX_LPC_ORDER];
  115. int opt_order;
  116. opt_order = ff_lpc_calc_coefs(&s->dspctx, s->sample_buf[ch], s->avctx->frame_size, s->min_prediction_order, s->max_prediction_order,
  117. ALAC_MAX_LPC_PRECISION, coefs, shift, 1, ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
  118. s->lpc[ch].lpc_order = opt_order;
  119. s->lpc[ch].lpc_quant = shift[opt_order-1];
  120. memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
  121. }
  122. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  123. {
  124. int i, best;
  125. int32_t lt, rt;
  126. uint64_t sum[4];
  127. uint64_t score[4];
  128. /* calculate sum of 2nd order residual for each channel */
  129. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  130. for(i=2; i<n; i++) {
  131. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  132. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  133. sum[2] += FFABS((lt + rt) >> 1);
  134. sum[3] += FFABS(lt - rt);
  135. sum[0] += FFABS(lt);
  136. sum[1] += FFABS(rt);
  137. }
  138. /* calculate score for each mode */
  139. score[0] = sum[0] + sum[1];
  140. score[1] = sum[0] + sum[3];
  141. score[2] = sum[1] + sum[3];
  142. score[3] = sum[2] + sum[3];
  143. /* return mode with lowest score */
  144. best = 0;
  145. for(i=1; i<4; i++) {
  146. if(score[i] < score[best]) {
  147. best = i;
  148. }
  149. }
  150. return best;
  151. }
  152. static void alac_stereo_decorrelation(AlacEncodeContext *s)
  153. {
  154. int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
  155. int i, mode, n = s->avctx->frame_size;
  156. int32_t tmp;
  157. mode = estimate_stereo_mode(left, right, n);
  158. switch(mode)
  159. {
  160. case ALAC_CHMODE_LEFT_RIGHT:
  161. s->interlacing_leftweight = 0;
  162. s->interlacing_shift = 0;
  163. break;
  164. case ALAC_CHMODE_LEFT_SIDE:
  165. for(i=0; i<n; i++) {
  166. right[i] = left[i] - right[i];
  167. }
  168. s->interlacing_leftweight = 1;
  169. s->interlacing_shift = 0;
  170. break;
  171. case ALAC_CHMODE_RIGHT_SIDE:
  172. for(i=0; i<n; i++) {
  173. tmp = right[i];
  174. right[i] = left[i] - right[i];
  175. left[i] = tmp + (right[i] >> 31);
  176. }
  177. s->interlacing_leftweight = 1;
  178. s->interlacing_shift = 31;
  179. break;
  180. default:
  181. for(i=0; i<n; i++) {
  182. tmp = left[i];
  183. left[i] = (tmp + right[i]) >> 1;
  184. right[i] = tmp - right[i];
  185. }
  186. s->interlacing_leftweight = 1;
  187. s->interlacing_shift = 1;
  188. break;
  189. }
  190. }
  191. static void alac_linear_predictor(AlacEncodeContext *s, int ch)
  192. {
  193. int i;
  194. LPCContext lpc = s->lpc[ch];
  195. if(lpc.lpc_order == 31) {
  196. s->predictor_buf[0] = s->sample_buf[ch][0];
  197. for(i=1; i<s->avctx->frame_size; i++)
  198. s->predictor_buf[i] = s->sample_buf[ch][i] - s->sample_buf[ch][i-1];
  199. return;
  200. }
  201. // generalised linear predictor
  202. if(lpc.lpc_order > 0) {
  203. int32_t *samples = s->sample_buf[ch];
  204. int32_t *residual = s->predictor_buf;
  205. // generate warm-up samples
  206. residual[0] = samples[0];
  207. for(i=1;i<=lpc.lpc_order;i++)
  208. residual[i] = samples[i] - samples[i-1];
  209. // perform lpc on remaining samples
  210. for(i = lpc.lpc_order + 1; i < s->avctx->frame_size; i++) {
  211. int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
  212. for (j = 0; j < lpc.lpc_order; j++) {
  213. sum += (samples[lpc.lpc_order-j] - samples[0]) *
  214. lpc.lpc_coeff[j];
  215. }
  216. sum >>= lpc.lpc_quant;
  217. sum += samples[0];
  218. residual[i] = (samples[lpc.lpc_order+1] - sum) << (32 - s->write_sample_size) >>
  219. (32 - s->write_sample_size);
  220. res_val = residual[i];
  221. if(res_val) {
  222. int index = lpc.lpc_order - 1;
  223. int neg = (res_val < 0);
  224. while(index >= 0 && (neg ? (res_val < 0):(res_val > 0))) {
  225. int val = samples[0] - samples[lpc.lpc_order - index];
  226. int sign = (val ? FFSIGN(val) : 0);
  227. if(neg)
  228. sign*=-1;
  229. lpc.lpc_coeff[index] -= sign;
  230. val *= sign;
  231. res_val -= ((val >> lpc.lpc_quant) *
  232. (lpc.lpc_order - index));
  233. index--;
  234. }
  235. }
  236. samples++;
  237. }
  238. }
  239. }
  240. static void alac_entropy_coder(AlacEncodeContext *s)
  241. {
  242. unsigned int history = s->rc.initial_history;
  243. int sign_modifier = 0, i, k;
  244. int32_t *samples = s->predictor_buf;
  245. for(i=0;i < s->avctx->frame_size;) {
  246. int x;
  247. k = av_log2((history >> 9) + 3);
  248. x = -2*(*samples)-1;
  249. x ^= (x>>31);
  250. samples++;
  251. i++;
  252. encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
  253. history += x * s->rc.history_mult
  254. - ((history * s->rc.history_mult) >> 9);
  255. sign_modifier = 0;
  256. if(x > 0xFFFF)
  257. history = 0xFFFF;
  258. if((history < 128) && (i < s->avctx->frame_size)) {
  259. unsigned int block_size = 0;
  260. k = 7 - av_log2(history) + ((history + 16) >> 6);
  261. while((*samples == 0) && (i < s->avctx->frame_size)) {
  262. samples++;
  263. i++;
  264. block_size++;
  265. }
  266. encode_scalar(s, block_size, k, 16);
  267. sign_modifier = (block_size <= 0xFFFF);
  268. history = 0;
  269. }
  270. }
  271. }
  272. static void write_compressed_frame(AlacEncodeContext *s)
  273. {
  274. int i, j;
  275. /* only simple mid/side decorrelation supported as of now */
  276. if(s->avctx->channels == 2)
  277. alac_stereo_decorrelation(s);
  278. put_bits(&s->pbctx, 8, s->interlacing_shift);
  279. put_bits(&s->pbctx, 8, s->interlacing_leftweight);
  280. for(i=0;i<s->avctx->channels;i++) {
  281. calc_predictor_params(s, i);
  282. put_bits(&s->pbctx, 4, 0); // prediction type : currently only type 0 has been RE'd
  283. put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
  284. put_bits(&s->pbctx, 3, s->rc.rice_modifier);
  285. put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
  286. // predictor coeff. table
  287. for(j=0;j<s->lpc[i].lpc_order;j++) {
  288. put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
  289. }
  290. }
  291. // apply lpc and entropy coding to audio samples
  292. for(i=0;i<s->avctx->channels;i++) {
  293. alac_linear_predictor(s, i);
  294. alac_entropy_coder(s);
  295. }
  296. }
  297. static av_cold int alac_encode_init(AVCodecContext *avctx)
  298. {
  299. AlacEncodeContext *s = avctx->priv_data;
  300. uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
  301. avctx->frame_size = DEFAULT_FRAME_SIZE;
  302. avctx->bits_per_coded_sample = DEFAULT_SAMPLE_SIZE;
  303. if(avctx->sample_fmt != SAMPLE_FMT_S16) {
  304. av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
  305. return -1;
  306. }
  307. // Set default compression level
  308. if(avctx->compression_level == FF_COMPRESSION_DEFAULT)
  309. s->compression_level = 1;
  310. else
  311. s->compression_level = av_clip(avctx->compression_level, 0, 1);
  312. // Initialize default Rice parameters
  313. s->rc.history_mult = 40;
  314. s->rc.initial_history = 10;
  315. s->rc.k_modifier = 14;
  316. s->rc.rice_modifier = 4;
  317. s->max_coded_frame_size = (ALAC_FRAME_HEADER_SIZE + ALAC_FRAME_FOOTER_SIZE +
  318. avctx->frame_size*avctx->channels*avctx->bits_per_coded_sample)>>3;
  319. s->write_sample_size = avctx->bits_per_coded_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
  320. AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
  321. AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
  322. AV_WB32(alac_extradata+12, avctx->frame_size);
  323. AV_WB8 (alac_extradata+17, avctx->bits_per_coded_sample);
  324. AV_WB8 (alac_extradata+21, avctx->channels);
  325. AV_WB32(alac_extradata+24, s->max_coded_frame_size);
  326. AV_WB32(alac_extradata+28, avctx->sample_rate*avctx->channels*avctx->bits_per_coded_sample); // average bitrate
  327. AV_WB32(alac_extradata+32, avctx->sample_rate);
  328. // Set relevant extradata fields
  329. if(s->compression_level > 0) {
  330. AV_WB8(alac_extradata+18, s->rc.history_mult);
  331. AV_WB8(alac_extradata+19, s->rc.initial_history);
  332. AV_WB8(alac_extradata+20, s->rc.k_modifier);
  333. }
  334. s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
  335. if(avctx->min_prediction_order >= 0) {
  336. if(avctx->min_prediction_order < MIN_LPC_ORDER ||
  337. avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
  338. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order);
  339. return -1;
  340. }
  341. s->min_prediction_order = avctx->min_prediction_order;
  342. }
  343. s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
  344. if(avctx->max_prediction_order >= 0) {
  345. if(avctx->max_prediction_order < MIN_LPC_ORDER ||
  346. avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
  347. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order);
  348. return -1;
  349. }
  350. s->max_prediction_order = avctx->max_prediction_order;
  351. }
  352. if(s->max_prediction_order < s->min_prediction_order) {
  353. av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
  354. s->min_prediction_order, s->max_prediction_order);
  355. return -1;
  356. }
  357. avctx->extradata = alac_extradata;
  358. avctx->extradata_size = ALAC_EXTRADATA_SIZE;
  359. avctx->coded_frame = avcodec_alloc_frame();
  360. avctx->coded_frame->key_frame = 1;
  361. s->avctx = avctx;
  362. dsputil_init(&s->dspctx, avctx);
  363. return 0;
  364. }
  365. static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  366. int buf_size, void *data)
  367. {
  368. AlacEncodeContext *s = avctx->priv_data;
  369. PutBitContext *pb = &s->pbctx;
  370. int i, out_bytes, verbatim_flag = 0;
  371. if(avctx->frame_size > DEFAULT_FRAME_SIZE) {
  372. av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
  373. return -1;
  374. }
  375. if(buf_size < 2*s->max_coded_frame_size) {
  376. av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
  377. return -1;
  378. }
  379. verbatim:
  380. init_put_bits(pb, frame, buf_size);
  381. if((s->compression_level == 0) || verbatim_flag) {
  382. // Verbatim mode
  383. int16_t *samples = data;
  384. write_frame_header(s, 1);
  385. for(i=0; i<avctx->frame_size*avctx->channels; i++) {
  386. put_sbits(pb, 16, *samples++);
  387. }
  388. } else {
  389. init_sample_buffers(s, data);
  390. write_frame_header(s, 0);
  391. write_compressed_frame(s);
  392. }
  393. put_bits(pb, 3, 7);
  394. flush_put_bits(pb);
  395. out_bytes = put_bits_count(pb) >> 3;
  396. if(out_bytes > s->max_coded_frame_size) {
  397. /* frame too large. use verbatim mode */
  398. if(verbatim_flag || (s->compression_level == 0)) {
  399. /* still too large. must be an error. */
  400. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  401. return -1;
  402. }
  403. verbatim_flag = 1;
  404. goto verbatim;
  405. }
  406. return out_bytes;
  407. }
  408. static av_cold int alac_encode_close(AVCodecContext *avctx)
  409. {
  410. av_freep(&avctx->extradata);
  411. avctx->extradata_size = 0;
  412. av_freep(&avctx->coded_frame);
  413. return 0;
  414. }
  415. AVCodec alac_encoder = {
  416. "alac",
  417. CODEC_TYPE_AUDIO,
  418. CODEC_ID_ALAC,
  419. sizeof(AlacEncodeContext),
  420. alac_encode_init,
  421. alac_encode_frame,
  422. alac_encode_close,
  423. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  424. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  425. };