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.

519 lines
15KB

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