You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
16KB

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