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.

406 lines
12KB

  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, DEFAULT_MIN_PRED_ORDER, DEFAULT_MAX_PRED_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 write_compressed_frame(AlacEncodeContext *s)
  192. {
  193. int i, j;
  194. /* only simple mid/side decorrelation supported as of now */
  195. alac_stereo_decorrelation(s);
  196. put_bits(&s->pbctx, 8, s->interlacing_shift);
  197. put_bits(&s->pbctx, 8, s->interlacing_leftweight);
  198. for(i=0;i<s->avctx->channels;i++) {
  199. calc_predictor_params(s, i);
  200. put_bits(&s->pbctx, 4, 0); // prediction type : currently only type 0 has been RE'd
  201. put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
  202. put_bits(&s->pbctx, 3, s->rc.rice_modifier);
  203. put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
  204. // predictor coeff. table
  205. for(j=0;j<s->lpc[i].lpc_order;j++) {
  206. put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
  207. }
  208. }
  209. // apply lpc and entropy coding to audio samples
  210. for(i=0;i<s->avctx->channels;i++) {
  211. alac_linear_predictor(s, i);
  212. alac_entropy_coder(s);
  213. }
  214. }
  215. static av_cold int alac_encode_init(AVCodecContext *avctx)
  216. {
  217. AlacEncodeContext *s = avctx->priv_data;
  218. uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
  219. avctx->frame_size = DEFAULT_FRAME_SIZE;
  220. avctx->bits_per_sample = DEFAULT_SAMPLE_SIZE;
  221. if(avctx->sample_fmt != SAMPLE_FMT_S16) {
  222. av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
  223. return -1;
  224. }
  225. // Set default compression level
  226. if(avctx->compression_level == FF_COMPRESSION_DEFAULT)
  227. s->compression_level = 1;
  228. else
  229. s->compression_level = av_clip(avctx->compression_level, 0, 1);
  230. // Initialize default Rice parameters
  231. s->rc.history_mult = 40;
  232. s->rc.initial_history = 10;
  233. s->rc.k_modifier = 14;
  234. s->rc.rice_modifier = 4;
  235. s->max_coded_frame_size = (ALAC_FRAME_HEADER_SIZE + ALAC_FRAME_FOOTER_SIZE +
  236. avctx->frame_size*avctx->channels*avctx->bits_per_sample)>>3;
  237. s->write_sample_size = avctx->bits_per_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
  238. AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
  239. AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
  240. AV_WB32(alac_extradata+12, avctx->frame_size);
  241. AV_WB8 (alac_extradata+17, avctx->bits_per_sample);
  242. AV_WB8 (alac_extradata+21, avctx->channels);
  243. AV_WB32(alac_extradata+24, s->max_coded_frame_size);
  244. AV_WB32(alac_extradata+28, avctx->sample_rate*avctx->channels*avctx->bits_per_sample); // average bitrate
  245. AV_WB32(alac_extradata+32, avctx->sample_rate);
  246. // Set relevant extradata fields
  247. if(s->compression_level > 0) {
  248. AV_WB8(alac_extradata+18, s->rc.history_mult);
  249. AV_WB8(alac_extradata+19, s->rc.initial_history);
  250. AV_WB8(alac_extradata+20, s->rc.k_modifier);
  251. }
  252. if(avctx->min_prediction_order >= 0) {
  253. if(avctx->min_prediction_order < MIN_LPC_ORDER ||
  254. avctx->min_prediction_order > MAX_LPC_ORDER) {
  255. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order);
  256. return -1;
  257. }
  258. s->min_prediction_order = avctx->min_prediction_order;
  259. }
  260. if(avctx->max_prediction_order >= 0) {
  261. if(avctx->max_prediction_order < MIN_LPC_ORDER ||
  262. avctx->max_prediction_order > MAX_LPC_ORDER) {
  263. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order);
  264. return -1;
  265. }
  266. s->max_prediction_order = avctx->max_prediction_order;
  267. }
  268. if(s->max_prediction_order < s->min_prediction_order) {
  269. av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
  270. s->min_prediction_order, s->max_prediction_order);
  271. return -1;
  272. }
  273. avctx->extradata = alac_extradata;
  274. avctx->extradata_size = ALAC_EXTRADATA_SIZE;
  275. avctx->coded_frame = avcodec_alloc_frame();
  276. avctx->coded_frame->key_frame = 1;
  277. s->avctx = avctx;
  278. dsputil_init(&s->dspctx, avctx);
  279. return 0;
  280. }
  281. static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  282. int buf_size, void *data)
  283. {
  284. AlacEncodeContext *s = avctx->priv_data;
  285. PutBitContext *pb = &s->pbctx;
  286. int i, out_bytes, verbatim_flag = 0;
  287. if(avctx->frame_size > DEFAULT_FRAME_SIZE) {
  288. av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
  289. return -1;
  290. }
  291. if(buf_size < 2*s->max_coded_frame_size) {
  292. av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
  293. return -1;
  294. }
  295. verbatim:
  296. init_put_bits(pb, frame, buf_size);
  297. if((s->compression_level == 0) || verbatim_flag) {
  298. // Verbatim mode
  299. int16_t *samples = data;
  300. write_frame_header(s, 1);
  301. for(i=0; i<avctx->frame_size*avctx->channels; i++) {
  302. put_sbits(pb, 16, *samples++);
  303. }
  304. } else {
  305. init_sample_buffers(s, data);
  306. write_frame_header(s, 0);
  307. write_compressed_frame(s);
  308. }
  309. put_bits(pb, 3, 7);
  310. flush_put_bits(pb);
  311. out_bytes = put_bits_count(pb) >> 3;
  312. if(out_bytes > s->max_coded_frame_size) {
  313. /* frame too large. use verbatim mode */
  314. if(verbatim_flag || (s->compression_level == 0)) {
  315. /* still too large. must be an error. */
  316. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  317. return -1;
  318. }
  319. verbatim_flag = 1;
  320. goto verbatim;
  321. }
  322. return out_bytes;
  323. }
  324. static av_cold int alac_encode_close(AVCodecContext *avctx)
  325. {
  326. av_freep(&avctx->extradata);
  327. avctx->extradata_size = 0;
  328. av_freep(&avctx->coded_frame);
  329. return 0;
  330. }
  331. AVCodec alac_encoder = {
  332. "alac",
  333. CODEC_TYPE_AUDIO,
  334. CODEC_ID_ALAC,
  335. sizeof(AlacEncodeContext),
  336. alac_encode_init,
  337. alac_encode_frame,
  338. alac_encode_close,
  339. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  340. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  341. };