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.

634 lines
15KB

  1. /**
  2. * FLAC audio encoder
  3. * Copyright (c) 2006 Justin Ruggles <jruggle@earthlink.net>
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. */
  19. #include "avcodec.h"
  20. #include "bitstream.h"
  21. #include "crc.h"
  22. #include "golomb.h"
  23. #define FLAC_MAX_CH 8
  24. #define FLAC_MIN_BLOCKSIZE 16
  25. #define FLAC_MAX_BLOCKSIZE 65535
  26. #define FLAC_SUBFRAME_CONSTANT 0
  27. #define FLAC_SUBFRAME_VERBATIM 1
  28. #define FLAC_SUBFRAME_FIXED 8
  29. #define FLAC_SUBFRAME_LPC 32
  30. #define FLAC_CHMODE_NOT_STEREO 0
  31. #define FLAC_CHMODE_LEFT_RIGHT 1
  32. #define FLAC_CHMODE_LEFT_SIDE 8
  33. #define FLAC_CHMODE_RIGHT_SIDE 9
  34. #define FLAC_CHMODE_MID_SIDE 10
  35. #define FLAC_STREAMINFO_SIZE 34
  36. typedef struct FlacSubframe {
  37. int type;
  38. int type_code;
  39. int obits;
  40. int order;
  41. int32_t samples[FLAC_MAX_BLOCKSIZE];
  42. int32_t residual[FLAC_MAX_BLOCKSIZE];
  43. } FlacSubframe;
  44. typedef struct FlacFrame {
  45. FlacSubframe subframes[FLAC_MAX_CH];
  46. int blocksize;
  47. int bs_code[2];
  48. uint8_t crc8;
  49. int ch_mode;
  50. } FlacFrame;
  51. typedef struct FlacEncodeContext {
  52. PutBitContext pb;
  53. int channels;
  54. int ch_code;
  55. int samplerate;
  56. int sr_code[2];
  57. int blocksize;
  58. int max_framesize;
  59. uint32_t frame_count;
  60. FlacFrame frame;
  61. } FlacEncodeContext;
  62. static const int flac_samplerates[16] = {
  63. 0, 0, 0, 0,
  64. 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
  65. 0, 0, 0, 0
  66. };
  67. static const int flac_blocksizes[16] = {
  68. 0,
  69. 192,
  70. 576, 1152, 2304, 4608,
  71. 0, 0,
  72. 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
  73. };
  74. /**
  75. * Writes streaminfo metadata block to byte array
  76. */
  77. static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
  78. {
  79. PutBitContext pb;
  80. memset(header, 0, FLAC_STREAMINFO_SIZE);
  81. init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
  82. /* streaminfo metadata block */
  83. put_bits(&pb, 16, s->blocksize);
  84. put_bits(&pb, 16, s->blocksize);
  85. put_bits(&pb, 24, 0);
  86. put_bits(&pb, 24, s->max_framesize);
  87. put_bits(&pb, 20, s->samplerate);
  88. put_bits(&pb, 3, s->channels-1);
  89. put_bits(&pb, 5, 15); /* bits per sample - 1 */
  90. flush_put_bits(&pb);
  91. /* total samples = 0 */
  92. /* MD5 signature = 0 */
  93. }
  94. #define BLOCK_TIME_MS 105
  95. /**
  96. * Sets blocksize based on samplerate
  97. * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
  98. */
  99. static int select_blocksize(int samplerate)
  100. {
  101. int i;
  102. int target;
  103. int blocksize;
  104. assert(samplerate > 0);
  105. blocksize = flac_blocksizes[1];
  106. target = (samplerate * BLOCK_TIME_MS) / 1000;
  107. for(i=0; i<16; i++) {
  108. if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
  109. blocksize = flac_blocksizes[i];
  110. }
  111. }
  112. return blocksize;
  113. }
  114. static int flac_encode_init(AVCodecContext *avctx)
  115. {
  116. int freq = avctx->sample_rate;
  117. int channels = avctx->channels;
  118. FlacEncodeContext *s = avctx->priv_data;
  119. int i;
  120. uint8_t *streaminfo;
  121. if(avctx->sample_fmt != SAMPLE_FMT_S16) {
  122. return -1;
  123. }
  124. if(channels < 1 || channels > FLAC_MAX_CH) {
  125. return -1;
  126. }
  127. s->channels = channels;
  128. s->ch_code = s->channels-1;
  129. /* find samplerate in table */
  130. if(freq < 1)
  131. return -1;
  132. for(i=4; i<12; i++) {
  133. if(freq == flac_samplerates[i]) {
  134. s->samplerate = flac_samplerates[i];
  135. s->sr_code[0] = i;
  136. s->sr_code[1] = 0;
  137. break;
  138. }
  139. }
  140. /* if not in table, samplerate is non-standard */
  141. if(i == 12) {
  142. if(freq % 1000 == 0 && freq < 255000) {
  143. s->sr_code[0] = 12;
  144. s->sr_code[1] = freq / 1000;
  145. } else if(freq % 10 == 0 && freq < 655350) {
  146. s->sr_code[0] = 14;
  147. s->sr_code[1] = freq / 10;
  148. } else if(freq < 65535) {
  149. s->sr_code[0] = 13;
  150. s->sr_code[1] = freq;
  151. } else {
  152. return -1;
  153. }
  154. s->samplerate = freq;
  155. }
  156. s->blocksize = select_blocksize(s->samplerate);
  157. avctx->frame_size = s->blocksize;
  158. /* set maximum encoded frame size in verbatim mode */
  159. if(s->channels == 2) {
  160. s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
  161. } else {
  162. s->max_framesize = 14 + (s->blocksize * s->channels * 2);
  163. }
  164. streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
  165. write_streaminfo(s, streaminfo);
  166. avctx->extradata = streaminfo;
  167. avctx->extradata_size = FLAC_STREAMINFO_SIZE;
  168. s->frame_count = 0;
  169. avctx->coded_frame = avcodec_alloc_frame();
  170. avctx->coded_frame->key_frame = 1;
  171. return 0;
  172. }
  173. static void init_frame(FlacEncodeContext *s)
  174. {
  175. int i, ch;
  176. FlacFrame *frame;
  177. frame = &s->frame;
  178. for(i=0; i<16; i++) {
  179. if(s->blocksize == flac_blocksizes[i]) {
  180. frame->blocksize = flac_blocksizes[i];
  181. frame->bs_code[0] = i;
  182. frame->bs_code[1] = 0;
  183. break;
  184. }
  185. }
  186. if(i == 16) {
  187. frame->blocksize = s->blocksize;
  188. if(frame->blocksize <= 256) {
  189. frame->bs_code[0] = 6;
  190. frame->bs_code[1] = frame->blocksize-1;
  191. } else {
  192. frame->bs_code[0] = 7;
  193. frame->bs_code[1] = frame->blocksize-1;
  194. }
  195. }
  196. for(ch=0; ch<s->channels; ch++) {
  197. frame->subframes[ch].obits = 16;
  198. }
  199. }
  200. /**
  201. * Copy channel-interleaved input samples into separate subframes
  202. */
  203. static void copy_samples(FlacEncodeContext *s, int16_t *samples)
  204. {
  205. int i, j, ch;
  206. FlacFrame *frame;
  207. frame = &s->frame;
  208. for(i=0,j=0; i<frame->blocksize; i++) {
  209. for(ch=0; ch<s->channels; ch++,j++) {
  210. frame->subframes[ch].samples[i] = samples[j];
  211. }
  212. }
  213. }
  214. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  215. {
  216. int i, best;
  217. int32_t lt, rt;
  218. uint64_t left, right, mid, side;
  219. uint64_t score[4];
  220. /* calculate sum of squares for each channel */
  221. left = right = mid = side = 0;
  222. for(i=2; i<n; i++) {
  223. lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
  224. rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
  225. mid += ABS((lt + rt) >> 1);
  226. side += ABS(lt - rt);
  227. left += ABS(lt);
  228. right += ABS(rt);
  229. }
  230. /* calculate score for each mode */
  231. score[0] = left + right;
  232. score[1] = left + side;
  233. score[2] = right + side;
  234. score[3] = mid + side;
  235. /* return mode with lowest score */
  236. best = 0;
  237. for(i=1; i<4; i++) {
  238. if(score[i] < score[best]) {
  239. best = i;
  240. }
  241. }
  242. if(best == 0) {
  243. return FLAC_CHMODE_LEFT_RIGHT;
  244. } else if(best == 1) {
  245. return FLAC_CHMODE_LEFT_SIDE;
  246. } else if(best == 2) {
  247. return FLAC_CHMODE_RIGHT_SIDE;
  248. } else {
  249. return FLAC_CHMODE_MID_SIDE;
  250. }
  251. }
  252. /**
  253. * Perform stereo channel decorrelation
  254. */
  255. static void channel_decorrelation(FlacEncodeContext *ctx)
  256. {
  257. FlacFrame *frame;
  258. int32_t *left, *right;
  259. int i, n;
  260. frame = &ctx->frame;
  261. n = frame->blocksize;
  262. left = frame->subframes[0].samples;
  263. right = frame->subframes[1].samples;
  264. if(ctx->channels != 2) {
  265. frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
  266. return;
  267. }
  268. frame->ch_mode = estimate_stereo_mode(left, right, n);
  269. /* perform decorrelation and adjust bits-per-sample */
  270. if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
  271. return;
  272. }
  273. if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
  274. int32_t tmp;
  275. for(i=0; i<n; i++) {
  276. tmp = left[i];
  277. left[i] = (tmp + right[i]) >> 1;
  278. right[i] = tmp - right[i];
  279. }
  280. frame->subframes[1].obits++;
  281. } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
  282. for(i=0; i<n; i++) {
  283. right[i] = left[i] - right[i];
  284. }
  285. frame->subframes[1].obits++;
  286. } else {
  287. for(i=0; i<n; i++) {
  288. left[i] -= right[i];
  289. }
  290. frame->subframes[0].obits++;
  291. }
  292. }
  293. static void encode_residual_verbatim(FlacEncodeContext *s, int ch)
  294. {
  295. FlacFrame *frame;
  296. FlacSubframe *sub;
  297. int32_t *res;
  298. int32_t *smp;
  299. int n;
  300. frame = &s->frame;
  301. sub = &frame->subframes[ch];
  302. res = sub->residual;
  303. smp = sub->samples;
  304. n = frame->blocksize;
  305. sub->order = 0;
  306. sub->type = FLAC_SUBFRAME_VERBATIM;
  307. sub->type_code = sub->type;
  308. memcpy(res, smp, n * sizeof(int32_t));
  309. }
  310. static void encode_residual_fixed(int32_t *res, int32_t *smp, int n, int order)
  311. {
  312. int i;
  313. for(i=0; i<order; i++) {
  314. res[i] = smp[i];
  315. }
  316. if(order==0){
  317. for(i=order; i<n; i++)
  318. res[i]= smp[i];
  319. }else if(order==1){
  320. for(i=order; i<n; i++)
  321. res[i]= smp[i] - smp[i-1];
  322. }else if(order==2){
  323. for(i=order; i<n; i++)
  324. res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
  325. }else if(order==3){
  326. for(i=order; i<n; i++)
  327. res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
  328. }else{
  329. for(i=order; i<n; i++)
  330. res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
  331. }
  332. }
  333. static void encode_residual(FlacEncodeContext *s, int ch)
  334. {
  335. FlacFrame *frame;
  336. FlacSubframe *sub;
  337. int32_t *res;
  338. int32_t *smp;
  339. int n;
  340. frame = &s->frame;
  341. sub = &frame->subframes[ch];
  342. res = sub->residual;
  343. smp = sub->samples;
  344. n = frame->blocksize;
  345. sub->order = 2;
  346. sub->type = FLAC_SUBFRAME_FIXED;
  347. sub->type_code = sub->type | sub->order;
  348. encode_residual_fixed(res, smp, n, sub->order);
  349. }
  350. static void
  351. put_sbits(PutBitContext *pb, int bits, int32_t val)
  352. {
  353. assert(bits >= 0 && bits <= 31);
  354. put_bits(pb, bits, val & ((1<<bits)-1));
  355. }
  356. static void
  357. write_utf8(PutBitContext *pb, uint32_t val)
  358. {
  359. int bytes, shift;
  360. if(val < 0x80){
  361. put_bits(pb, 8, val);
  362. return;
  363. }
  364. bytes= (av_log2(val)+4) / 5;
  365. shift = (bytes - 1) * 6;
  366. put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
  367. while(shift >= 6){
  368. shift -= 6;
  369. put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
  370. }
  371. }
  372. static void
  373. output_frame_header(FlacEncodeContext *s)
  374. {
  375. FlacFrame *frame;
  376. int crc;
  377. frame = &s->frame;
  378. put_bits(&s->pb, 16, 0xFFF8);
  379. put_bits(&s->pb, 4, frame->bs_code[0]);
  380. put_bits(&s->pb, 4, s->sr_code[0]);
  381. if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
  382. put_bits(&s->pb, 4, s->ch_code);
  383. } else {
  384. put_bits(&s->pb, 4, frame->ch_mode);
  385. }
  386. put_bits(&s->pb, 3, 4); /* bits-per-sample code */
  387. put_bits(&s->pb, 1, 0);
  388. write_utf8(&s->pb, s->frame_count);
  389. if(frame->bs_code[0] == 6) {
  390. put_bits(&s->pb, 8, frame->bs_code[1]);
  391. } else if(frame->bs_code[0] == 7) {
  392. put_bits(&s->pb, 16, frame->bs_code[1]);
  393. }
  394. if(s->sr_code[0] == 12) {
  395. put_bits(&s->pb, 8, s->sr_code[1]);
  396. } else if(s->sr_code[0] > 12) {
  397. put_bits(&s->pb, 16, s->sr_code[1]);
  398. }
  399. flush_put_bits(&s->pb);
  400. crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
  401. put_bits(&s->pb, 8, crc);
  402. }
  403. static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
  404. {
  405. int i;
  406. FlacFrame *frame;
  407. FlacSubframe *sub;
  408. int32_t res;
  409. frame = &s->frame;
  410. sub = &frame->subframes[ch];
  411. for(i=0; i<frame->blocksize; i++) {
  412. res = sub->residual[i];
  413. put_sbits(&s->pb, sub->obits, res);
  414. }
  415. }
  416. static void
  417. output_residual(FlacEncodeContext *ctx, int ch)
  418. {
  419. int i, j, p;
  420. int k, porder, psize, res_cnt;
  421. FlacFrame *frame;
  422. FlacSubframe *sub;
  423. frame = &ctx->frame;
  424. sub = &frame->subframes[ch];
  425. /* rice-encoded block */
  426. put_bits(&ctx->pb, 2, 0);
  427. /* partition order */
  428. porder = 0;
  429. psize = frame->blocksize;
  430. //porder = sub->rc.porder;
  431. //psize = frame->blocksize >> porder;
  432. put_bits(&ctx->pb, 4, porder);
  433. res_cnt = psize - sub->order;
  434. /* residual */
  435. j = sub->order;
  436. for(p=0; p<(1 << porder); p++) {
  437. //k = sub->rc.params[p];
  438. k = 9;
  439. put_bits(&ctx->pb, 4, k);
  440. if(p == 1) res_cnt = psize;
  441. for(i=0; i<res_cnt && j<frame->blocksize; i++, j++) {
  442. set_sr_golomb_flac(&ctx->pb, sub->residual[j], k, INT32_MAX, 0);
  443. }
  444. }
  445. }
  446. static void
  447. output_subframe_fixed(FlacEncodeContext *ctx, int ch)
  448. {
  449. int i;
  450. FlacFrame *frame;
  451. FlacSubframe *sub;
  452. frame = &ctx->frame;
  453. sub = &frame->subframes[ch];
  454. /* warm-up samples */
  455. for(i=0; i<sub->order; i++) {
  456. put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
  457. }
  458. /* residual */
  459. output_residual(ctx, ch);
  460. }
  461. static void output_subframes(FlacEncodeContext *s)
  462. {
  463. FlacFrame *frame;
  464. FlacSubframe *sub;
  465. int ch;
  466. frame = &s->frame;
  467. for(ch=0; ch<s->channels; ch++) {
  468. sub = &frame->subframes[ch];
  469. /* subframe header */
  470. put_bits(&s->pb, 1, 0);
  471. put_bits(&s->pb, 6, sub->type_code);
  472. put_bits(&s->pb, 1, 0); /* no wasted bits */
  473. /* subframe */
  474. if(sub->type == FLAC_SUBFRAME_VERBATIM) {
  475. output_subframe_verbatim(s, ch);
  476. } else {
  477. output_subframe_fixed(s, ch);
  478. }
  479. }
  480. }
  481. static void output_frame_footer(FlacEncodeContext *s)
  482. {
  483. int crc;
  484. flush_put_bits(&s->pb);
  485. crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
  486. put_bits(&s->pb, 16, crc);
  487. flush_put_bits(&s->pb);
  488. }
  489. static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  490. int buf_size, void *data)
  491. {
  492. int ch;
  493. FlacEncodeContext *s;
  494. int16_t *samples = data;
  495. int out_bytes;
  496. s = avctx->priv_data;
  497. s->blocksize = avctx->frame_size;
  498. init_frame(s);
  499. copy_samples(s, samples);
  500. channel_decorrelation(s);
  501. for(ch=0; ch<s->channels; ch++) {
  502. encode_residual(s, ch);
  503. }
  504. init_put_bits(&s->pb, frame, buf_size);
  505. output_frame_header(s);
  506. output_subframes(s);
  507. output_frame_footer(s);
  508. out_bytes = put_bits_count(&s->pb) >> 3;
  509. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  510. /* frame too large. use verbatim mode */
  511. for(ch=0; ch<s->channels; ch++) {
  512. encode_residual_verbatim(s, ch);
  513. }
  514. init_put_bits(&s->pb, frame, buf_size);
  515. output_frame_header(s);
  516. output_subframes(s);
  517. output_frame_footer(s);
  518. out_bytes = put_bits_count(&s->pb) >> 3;
  519. if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
  520. /* still too large. must be an error. */
  521. av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
  522. return -1;
  523. }
  524. }
  525. s->frame_count++;
  526. return out_bytes;
  527. }
  528. static int flac_encode_close(AVCodecContext *avctx)
  529. {
  530. av_freep(&avctx->extradata);
  531. avctx->extradata_size = 0;
  532. av_freep(&avctx->coded_frame);
  533. return 0;
  534. }
  535. AVCodec flac_encoder = {
  536. "flac",
  537. CODEC_TYPE_AUDIO,
  538. CODEC_ID_FLAC,
  539. sizeof(FlacEncodeContext),
  540. flac_encode_init,
  541. flac_encode_frame,
  542. flac_encode_close,
  543. NULL,
  544. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  545. };