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.

562 lines
17KB

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