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.

533 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 LPCContext {
  49. int lpc_order;
  50. int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
  51. int lpc_quant;
  52. } LPCContext;
  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. LPCContext lpc[MAX_CHANNELS];
  66. DSPContext dspctx;
  67. AVCodecContext *avctx;
  68. } AlacEncodeContext;
  69. static void init_sample_buffers(AlacEncodeContext *s, int16_t *input_samples)
  70. {
  71. int ch, i;
  72. for(ch=0;ch<s->avctx->channels;ch++) {
  73. 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->dspctx, 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, 1,
  132. ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
  133. s->lpc[ch].lpc_order = opt_order;
  134. s->lpc[ch].lpc_quant = shift[opt_order-1];
  135. memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
  136. }
  137. }
  138. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  139. {
  140. int i, best;
  141. int32_t lt, rt;
  142. uint64_t sum[4];
  143. uint64_t score[4];
  144. /* calculate sum of 2nd order residual for each channel */
  145. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  146. for(i=2; i<n; i++) {
  147. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  148. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  149. sum[2] += FFABS((lt + rt) >> 1);
  150. sum[3] += FFABS(lt - rt);
  151. sum[0] += FFABS(lt);
  152. sum[1] += FFABS(rt);
  153. }
  154. /* calculate score for each mode */
  155. score[0] = sum[0] + sum[1];
  156. score[1] = sum[0] + sum[3];
  157. score[2] = sum[1] + sum[3];
  158. score[3] = sum[2] + sum[3];
  159. /* return mode with lowest score */
  160. best = 0;
  161. for(i=1; i<4; i++) {
  162. if(score[i] < score[best]) {
  163. best = i;
  164. }
  165. }
  166. return best;
  167. }
  168. static void alac_stereo_decorrelation(AlacEncodeContext *s)
  169. {
  170. int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
  171. int i, mode, n = s->avctx->frame_size;
  172. int32_t tmp;
  173. mode = estimate_stereo_mode(left, right, n);
  174. switch(mode)
  175. {
  176. case ALAC_CHMODE_LEFT_RIGHT:
  177. s->interlacing_leftweight = 0;
  178. s->interlacing_shift = 0;
  179. break;
  180. case ALAC_CHMODE_LEFT_SIDE:
  181. for(i=0; i<n; i++) {
  182. right[i] = left[i] - right[i];
  183. }
  184. s->interlacing_leftweight = 1;
  185. s->interlacing_shift = 0;
  186. break;
  187. case ALAC_CHMODE_RIGHT_SIDE:
  188. for(i=0; i<n; i++) {
  189. tmp = right[i];
  190. right[i] = left[i] - right[i];
  191. left[i] = tmp + (right[i] >> 31);
  192. }
  193. s->interlacing_leftweight = 1;
  194. s->interlacing_shift = 31;
  195. break;
  196. default:
  197. for(i=0; i<n; i++) {
  198. tmp = left[i];
  199. left[i] = (tmp + right[i]) >> 1;
  200. right[i] = tmp - right[i];
  201. }
  202. s->interlacing_leftweight = 1;
  203. s->interlacing_shift = 1;
  204. break;
  205. }
  206. }
  207. static void alac_linear_predictor(AlacEncodeContext *s, int ch)
  208. {
  209. int i;
  210. LPCContext lpc = s->lpc[ch];
  211. if(lpc.lpc_order == 31) {
  212. s->predictor_buf[0] = s->sample_buf[ch][0];
  213. for(i=1; i<s->avctx->frame_size; i++)
  214. s->predictor_buf[i] = s->sample_buf[ch][i] - s->sample_buf[ch][i-1];
  215. return;
  216. }
  217. // generalised linear predictor
  218. if(lpc.lpc_order > 0) {
  219. int32_t *samples = s->sample_buf[ch];
  220. int32_t *residual = s->predictor_buf;
  221. // generate warm-up samples
  222. residual[0] = samples[0];
  223. for(i=1;i<=lpc.lpc_order;i++)
  224. residual[i] = samples[i] - samples[i-1];
  225. // perform lpc on remaining samples
  226. for(i = lpc.lpc_order + 1; i < s->avctx->frame_size; i++) {
  227. int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
  228. for (j = 0; j < lpc.lpc_order; j++) {
  229. sum += (samples[lpc.lpc_order-j] - samples[0]) *
  230. lpc.lpc_coeff[j];
  231. }
  232. sum >>= lpc.lpc_quant;
  233. sum += samples[0];
  234. residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
  235. s->write_sample_size);
  236. res_val = residual[i];
  237. if(res_val) {
  238. int index = lpc.lpc_order - 1;
  239. int neg = (res_val < 0);
  240. while(index >= 0 && (neg ? (res_val < 0):(res_val > 0))) {
  241. int val = samples[0] - samples[lpc.lpc_order - index];
  242. int sign = (val ? FFSIGN(val) : 0);
  243. if(neg)
  244. sign*=-1;
  245. lpc.lpc_coeff[index] -= sign;
  246. val *= sign;
  247. res_val -= ((val >> lpc.lpc_quant) *
  248. (lpc.lpc_order - index));
  249. index--;
  250. }
  251. }
  252. samples++;
  253. }
  254. }
  255. }
  256. static void alac_entropy_coder(AlacEncodeContext *s)
  257. {
  258. unsigned int history = s->rc.initial_history;
  259. int sign_modifier = 0, i, k;
  260. int32_t *samples = s->predictor_buf;
  261. for(i=0;i < s->avctx->frame_size;) {
  262. int x;
  263. k = av_log2((history >> 9) + 3);
  264. x = -2*(*samples)-1;
  265. x ^= (x>>31);
  266. samples++;
  267. i++;
  268. encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
  269. history += x * s->rc.history_mult
  270. - ((history * s->rc.history_mult) >> 9);
  271. sign_modifier = 0;
  272. if(x > 0xFFFF)
  273. history = 0xFFFF;
  274. if((history < 128) && (i < s->avctx->frame_size)) {
  275. unsigned int block_size = 0;
  276. k = 7 - av_log2(history) + ((history + 16) >> 6);
  277. while((*samples == 0) && (i < s->avctx->frame_size)) {
  278. samples++;
  279. i++;
  280. block_size++;
  281. }
  282. encode_scalar(s, block_size, k, 16);
  283. sign_modifier = (block_size <= 0xFFFF);
  284. history = 0;
  285. }
  286. }
  287. }
  288. static void write_compressed_frame(AlacEncodeContext *s)
  289. {
  290. int i, j;
  291. if(s->avctx->channels == 2)
  292. alac_stereo_decorrelation(s);
  293. put_bits(&s->pbctx, 8, s->interlacing_shift);
  294. put_bits(&s->pbctx, 8, s->interlacing_leftweight);
  295. for(i=0;i<s->avctx->channels;i++) {
  296. calc_predictor_params(s, i);
  297. put_bits(&s->pbctx, 4, 0); // prediction type : currently only type 0 has been RE'd
  298. put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
  299. put_bits(&s->pbctx, 3, s->rc.rice_modifier);
  300. put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
  301. // predictor coeff. table
  302. for(j=0;j<s->lpc[i].lpc_order;j++) {
  303. put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
  304. }
  305. }
  306. // apply lpc and entropy coding to audio samples
  307. for(i=0;i<s->avctx->channels;i++) {
  308. alac_linear_predictor(s, i);
  309. alac_entropy_coder(s);
  310. }
  311. }
  312. static av_cold int alac_encode_init(AVCodecContext *avctx)
  313. {
  314. AlacEncodeContext *s = avctx->priv_data;
  315. uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
  316. avctx->frame_size = DEFAULT_FRAME_SIZE;
  317. avctx->bits_per_coded_sample = DEFAULT_SAMPLE_SIZE;
  318. if(avctx->sample_fmt != SAMPLE_FMT_S16) {
  319. av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
  320. return -1;
  321. }
  322. // Set default compression level
  323. if(avctx->compression_level == FF_COMPRESSION_DEFAULT)
  324. s->compression_level = 2;
  325. else
  326. s->compression_level = av_clip(avctx->compression_level, 0, 2);
  327. // Initialize default Rice parameters
  328. s->rc.history_mult = 40;
  329. s->rc.initial_history = 10;
  330. s->rc.k_modifier = 14;
  331. s->rc.rice_modifier = 4;
  332. s->max_coded_frame_size = 8 + (avctx->frame_size*avctx->channels*avctx->bits_per_coded_sample>>3);
  333. s->write_sample_size = avctx->bits_per_coded_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
  334. AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
  335. AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
  336. AV_WB32(alac_extradata+12, avctx->frame_size);
  337. AV_WB8 (alac_extradata+17, avctx->bits_per_coded_sample);
  338. AV_WB8 (alac_extradata+21, avctx->channels);
  339. AV_WB32(alac_extradata+24, s->max_coded_frame_size);
  340. AV_WB32(alac_extradata+28, avctx->sample_rate*avctx->channels*avctx->bits_per_coded_sample); // average bitrate
  341. AV_WB32(alac_extradata+32, avctx->sample_rate);
  342. // Set relevant extradata fields
  343. if(s->compression_level > 0) {
  344. AV_WB8(alac_extradata+18, s->rc.history_mult);
  345. AV_WB8(alac_extradata+19, s->rc.initial_history);
  346. AV_WB8(alac_extradata+20, s->rc.k_modifier);
  347. }
  348. s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
  349. if(avctx->min_prediction_order >= 0) {
  350. if(avctx->min_prediction_order < MIN_LPC_ORDER ||
  351. avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
  352. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order);
  353. return -1;
  354. }
  355. s->min_prediction_order = avctx->min_prediction_order;
  356. }
  357. s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
  358. if(avctx->max_prediction_order >= 0) {
  359. if(avctx->max_prediction_order < MIN_LPC_ORDER ||
  360. avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
  361. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order);
  362. return -1;
  363. }
  364. s->max_prediction_order = avctx->max_prediction_order;
  365. }
  366. if(s->max_prediction_order < s->min_prediction_order) {
  367. av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
  368. s->min_prediction_order, s->max_prediction_order);
  369. return -1;
  370. }
  371. avctx->extradata = alac_extradata;
  372. avctx->extradata_size = ALAC_EXTRADATA_SIZE;
  373. avctx->coded_frame = avcodec_alloc_frame();
  374. avctx->coded_frame->key_frame = 1;
  375. s->avctx = avctx;
  376. dsputil_init(&s->dspctx, avctx);
  377. return 0;
  378. }
  379. static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  380. int buf_size, void *data)
  381. {
  382. AlacEncodeContext *s = avctx->priv_data;
  383. PutBitContext *pb = &s->pbctx;
  384. int i, out_bytes, verbatim_flag = 0;
  385. if(avctx->frame_size > DEFAULT_FRAME_SIZE) {
  386. av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
  387. return -1;
  388. }
  389. if(buf_size < 2*s->max_coded_frame_size) {
  390. av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
  391. return -1;
  392. }
  393. verbatim:
  394. init_put_bits(pb, frame, buf_size);
  395. if((s->compression_level == 0) || verbatim_flag) {
  396. // Verbatim mode
  397. int16_t *samples = data;
  398. write_frame_header(s, 1);
  399. for(i=0; i<avctx->frame_size*avctx->channels; i++) {
  400. put_sbits(pb, 16, *samples++);
  401. }
  402. } else {
  403. init_sample_buffers(s, data);
  404. write_frame_header(s, 0);
  405. write_compressed_frame(s);
  406. }
  407. put_bits(pb, 3, 7);
  408. flush_put_bits(pb);
  409. out_bytes = put_bits_count(pb) >> 3;
  410. if(out_bytes > s->max_coded_frame_size) {
  411. /* frame too large. use verbatim mode */
  412. if(verbatim_flag || (s->compression_level == 0)) {
  413. /* still too large. must be an error. */
  414. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  415. return -1;
  416. }
  417. verbatim_flag = 1;
  418. goto verbatim;
  419. }
  420. return out_bytes;
  421. }
  422. static av_cold int alac_encode_close(AVCodecContext *avctx)
  423. {
  424. av_freep(&avctx->extradata);
  425. avctx->extradata_size = 0;
  426. av_freep(&avctx->coded_frame);
  427. return 0;
  428. }
  429. AVCodec alac_encoder = {
  430. "alac",
  431. AVMEDIA_TYPE_AUDIO,
  432. CODEC_ID_ALAC,
  433. sizeof(AlacEncodeContext),
  434. alac_encode_init,
  435. alac_encode_frame,
  436. alac_encode_close,
  437. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  438. .sample_fmts = (const enum SampleFormat[]){ SAMPLE_FMT_S16, SAMPLE_FMT_NONE},
  439. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  440. };