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.

1209 lines
37KB

  1. /*
  2. * copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * Native Vorbis encoder.
  23. * @author Oded Shimon <ods15@ods15.dyndns.org>
  24. */
  25. #include <float.h>
  26. #include "avcodec.h"
  27. #include "internal.h"
  28. #include "fft.h"
  29. #include "vorbis.h"
  30. #include "vorbis_enc_data.h"
  31. #define BITSTREAM_WRITER_LE
  32. #include "put_bits.h"
  33. #undef NDEBUG
  34. #include <assert.h>
  35. typedef struct {
  36. int nentries;
  37. uint8_t *lens;
  38. uint32_t *codewords;
  39. int ndimensions;
  40. float min;
  41. float delta;
  42. int seq_p;
  43. int lookup;
  44. int *quantlist;
  45. float *dimensions;
  46. float *pow2;
  47. } vorbis_enc_codebook;
  48. typedef struct {
  49. int dim;
  50. int subclass;
  51. int masterbook;
  52. int *books;
  53. } vorbis_enc_floor_class;
  54. typedef struct {
  55. int partitions;
  56. int *partition_to_class;
  57. int nclasses;
  58. vorbis_enc_floor_class *classes;
  59. int multiplier;
  60. int rangebits;
  61. int values;
  62. vorbis_floor1_entry *list;
  63. } vorbis_enc_floor;
  64. typedef struct {
  65. int type;
  66. int begin;
  67. int end;
  68. int partition_size;
  69. int classifications;
  70. int classbook;
  71. int8_t (*books)[8];
  72. float (*maxes)[2];
  73. } vorbis_enc_residue;
  74. typedef struct {
  75. int submaps;
  76. int *mux;
  77. int *floor;
  78. int *residue;
  79. int coupling_steps;
  80. int *magnitude;
  81. int *angle;
  82. } vorbis_enc_mapping;
  83. typedef struct {
  84. int blockflag;
  85. int mapping;
  86. } vorbis_enc_mode;
  87. typedef struct {
  88. int channels;
  89. int sample_rate;
  90. int log2_blocksize[2];
  91. FFTContext mdct[2];
  92. const float *win[2];
  93. int have_saved;
  94. float *saved;
  95. float *samples;
  96. float *floor; // also used for tmp values for mdct
  97. float *coeffs; // also used for residue after floor
  98. float quality;
  99. int ncodebooks;
  100. vorbis_enc_codebook *codebooks;
  101. int nfloors;
  102. vorbis_enc_floor *floors;
  103. int nresidues;
  104. vorbis_enc_residue *residues;
  105. int nmappings;
  106. vorbis_enc_mapping *mappings;
  107. int nmodes;
  108. vorbis_enc_mode *modes;
  109. int64_t next_pts;
  110. } vorbis_enc_context;
  111. #define MAX_CHANNELS 2
  112. #define MAX_CODEBOOK_DIM 8
  113. #define MAX_FLOOR_CLASS_DIM 4
  114. #define NUM_FLOOR_PARTITIONS 8
  115. #define MAX_FLOOR_VALUES (MAX_FLOOR_CLASS_DIM*NUM_FLOOR_PARTITIONS+2)
  116. #define RESIDUE_SIZE 1600
  117. #define RESIDUE_PART_SIZE 32
  118. #define NUM_RESIDUE_PARTITIONS (RESIDUE_SIZE/RESIDUE_PART_SIZE)
  119. static inline int put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,
  120. int entry)
  121. {
  122. assert(entry >= 0);
  123. assert(entry < cb->nentries);
  124. assert(cb->lens[entry]);
  125. if (pb->size_in_bits - put_bits_count(pb) < cb->lens[entry])
  126. return AVERROR(EINVAL);
  127. put_bits(pb, cb->lens[entry], cb->codewords[entry]);
  128. return 0;
  129. }
  130. static int cb_lookup_vals(int lookup, int dimensions, int entries)
  131. {
  132. if (lookup == 1)
  133. return ff_vorbis_nth_root(entries, dimensions);
  134. else if (lookup == 2)
  135. return dimensions *entries;
  136. return 0;
  137. }
  138. static int ready_codebook(vorbis_enc_codebook *cb)
  139. {
  140. int i;
  141. ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
  142. if (!cb->lookup) {
  143. cb->pow2 = cb->dimensions = NULL;
  144. } else {
  145. int vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
  146. cb->dimensions = av_malloc(sizeof(float) * cb->nentries * cb->ndimensions);
  147. cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);
  148. if (!cb->dimensions || !cb->pow2)
  149. return AVERROR(ENOMEM);
  150. for (i = 0; i < cb->nentries; i++) {
  151. float last = 0;
  152. int j;
  153. int div = 1;
  154. for (j = 0; j < cb->ndimensions; j++) {
  155. int off;
  156. if (cb->lookup == 1)
  157. off = (i / div) % vals; // lookup type 1
  158. else
  159. off = i * cb->ndimensions + j; // lookup type 2
  160. cb->dimensions[i * cb->ndimensions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
  161. if (cb->seq_p)
  162. last = cb->dimensions[i * cb->ndimensions + j];
  163. cb->pow2[i] += cb->dimensions[i * cb->ndimensions + j] * cb->dimensions[i * cb->ndimensions + j];
  164. div *= vals;
  165. }
  166. cb->pow2[i] /= 2.0;
  167. }
  168. }
  169. return 0;
  170. }
  171. static int ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
  172. {
  173. int i;
  174. assert(rc->type == 2);
  175. rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);
  176. if (!rc->maxes)
  177. return AVERROR(ENOMEM);
  178. for (i = 0; i < rc->classifications; i++) {
  179. int j;
  180. vorbis_enc_codebook * cb;
  181. for (j = 0; j < 8; j++)
  182. if (rc->books[i][j] != -1)
  183. break;
  184. if (j == 8) // zero
  185. continue;
  186. cb = &venc->codebooks[rc->books[i][j]];
  187. assert(cb->ndimensions >= 2);
  188. assert(cb->lookup);
  189. for (j = 0; j < cb->nentries; j++) {
  190. float a;
  191. if (!cb->lens[j])
  192. continue;
  193. a = fabs(cb->dimensions[j * cb->ndimensions]);
  194. if (a > rc->maxes[i][0])
  195. rc->maxes[i][0] = a;
  196. a = fabs(cb->dimensions[j * cb->ndimensions + 1]);
  197. if (a > rc->maxes[i][1])
  198. rc->maxes[i][1] = a;
  199. }
  200. }
  201. // small bias
  202. for (i = 0; i < rc->classifications; i++) {
  203. rc->maxes[i][0] += 0.8;
  204. rc->maxes[i][1] += 0.8;
  205. }
  206. return 0;
  207. }
  208. static int create_vorbis_context(vorbis_enc_context *venc,
  209. AVCodecContext *avctx)
  210. {
  211. vorbis_enc_floor *fc;
  212. vorbis_enc_residue *rc;
  213. vorbis_enc_mapping *mc;
  214. int i, book, ret;
  215. venc->channels = avctx->channels;
  216. venc->sample_rate = avctx->sample_rate;
  217. venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
  218. venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
  219. venc->codebooks = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
  220. if (!venc->codebooks)
  221. return AVERROR(ENOMEM);
  222. // codebook 0..14 - floor1 book, values 0..255
  223. // codebook 15 residue masterbook
  224. // codebook 16..29 residue
  225. for (book = 0; book < venc->ncodebooks; book++) {
  226. vorbis_enc_codebook *cb = &venc->codebooks[book];
  227. int vals;
  228. cb->ndimensions = cvectors[book].dim;
  229. cb->nentries = cvectors[book].real_len;
  230. cb->min = cvectors[book].min;
  231. cb->delta = cvectors[book].delta;
  232. cb->lookup = cvectors[book].lookup;
  233. cb->seq_p = 0;
  234. cb->lens = av_malloc(sizeof(uint8_t) * cb->nentries);
  235. cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);
  236. if (!cb->lens || !cb->codewords)
  237. return AVERROR(ENOMEM);
  238. memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
  239. memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
  240. if (cb->lookup) {
  241. vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
  242. cb->quantlist = av_malloc(sizeof(int) * vals);
  243. if (!cb->quantlist)
  244. return AVERROR(ENOMEM);
  245. for (i = 0; i < vals; i++)
  246. cb->quantlist[i] = cvectors[book].quant[i];
  247. } else {
  248. cb->quantlist = NULL;
  249. }
  250. if ((ret = ready_codebook(cb)) < 0)
  251. return ret;
  252. }
  253. venc->nfloors = 1;
  254. venc->floors = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
  255. if (!venc->floors)
  256. return AVERROR(ENOMEM);
  257. // just 1 floor
  258. fc = &venc->floors[0];
  259. fc->partitions = NUM_FLOOR_PARTITIONS;
  260. fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
  261. if (!fc->partition_to_class)
  262. return AVERROR(ENOMEM);
  263. fc->nclasses = 0;
  264. for (i = 0; i < fc->partitions; i++) {
  265. static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};
  266. fc->partition_to_class[i] = a[i];
  267. fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
  268. }
  269. fc->nclasses++;
  270. fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses);
  271. if (!fc->classes)
  272. return AVERROR(ENOMEM);
  273. for (i = 0; i < fc->nclasses; i++) {
  274. vorbis_enc_floor_class * c = &fc->classes[i];
  275. int j, books;
  276. c->dim = floor_classes[i].dim;
  277. c->subclass = floor_classes[i].subclass;
  278. c->masterbook = floor_classes[i].masterbook;
  279. books = (1 << c->subclass);
  280. c->books = av_malloc(sizeof(int) * books);
  281. if (!c->books)
  282. return AVERROR(ENOMEM);
  283. for (j = 0; j < books; j++)
  284. c->books[j] = floor_classes[i].nbooks[j];
  285. }
  286. fc->multiplier = 2;
  287. fc->rangebits = venc->log2_blocksize[0] - 1;
  288. fc->values = 2;
  289. for (i = 0; i < fc->partitions; i++)
  290. fc->values += fc->classes[fc->partition_to_class[i]].dim;
  291. fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values);
  292. if (!fc->list)
  293. return AVERROR(ENOMEM);
  294. fc->list[0].x = 0;
  295. fc->list[1].x = 1 << fc->rangebits;
  296. for (i = 2; i < fc->values; i++) {
  297. static const int a[] = {
  298. 93, 23,372, 6, 46,186,750, 14, 33, 65,
  299. 130,260,556, 3, 10, 18, 28, 39, 55, 79,
  300. 111,158,220,312,464,650,850
  301. };
  302. fc->list[i].x = a[i - 2];
  303. }
  304. if (ff_vorbis_ready_floor1_list(avctx, fc->list, fc->values))
  305. return AVERROR_BUG;
  306. venc->nresidues = 1;
  307. venc->residues = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
  308. if (!venc->residues)
  309. return AVERROR(ENOMEM);
  310. // single residue
  311. rc = &venc->residues[0];
  312. rc->type = 2;
  313. rc->begin = 0;
  314. rc->end = 1600;
  315. rc->partition_size = 32;
  316. rc->classifications = 10;
  317. rc->classbook = 15;
  318. rc->books = av_malloc(sizeof(*rc->books) * rc->classifications);
  319. if (!rc->books)
  320. return AVERROR(ENOMEM);
  321. {
  322. static const int8_t a[10][8] = {
  323. { -1, -1, -1, -1, -1, -1, -1, -1, },
  324. { -1, -1, 16, -1, -1, -1, -1, -1, },
  325. { -1, -1, 17, -1, -1, -1, -1, -1, },
  326. { -1, -1, 18, -1, -1, -1, -1, -1, },
  327. { -1, -1, 19, -1, -1, -1, -1, -1, },
  328. { -1, -1, 20, -1, -1, -1, -1, -1, },
  329. { -1, -1, 21, -1, -1, -1, -1, -1, },
  330. { 22, 23, -1, -1, -1, -1, -1, -1, },
  331. { 24, 25, -1, -1, -1, -1, -1, -1, },
  332. { 26, 27, 28, -1, -1, -1, -1, -1, },
  333. };
  334. memcpy(rc->books, a, sizeof a);
  335. }
  336. if ((ret = ready_residue(rc, venc)) < 0)
  337. return ret;
  338. venc->nmappings = 1;
  339. venc->mappings = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
  340. if (!venc->mappings)
  341. return AVERROR(ENOMEM);
  342. // single mapping
  343. mc = &venc->mappings[0];
  344. mc->submaps = 1;
  345. mc->mux = av_malloc(sizeof(int) * venc->channels);
  346. if (!mc->mux)
  347. return AVERROR(ENOMEM);
  348. for (i = 0; i < venc->channels; i++)
  349. mc->mux[i] = 0;
  350. mc->floor = av_malloc(sizeof(int) * mc->submaps);
  351. mc->residue = av_malloc(sizeof(int) * mc->submaps);
  352. if (!mc->floor || !mc->residue)
  353. return AVERROR(ENOMEM);
  354. for (i = 0; i < mc->submaps; i++) {
  355. mc->floor[i] = 0;
  356. mc->residue[i] = 0;
  357. }
  358. mc->coupling_steps = venc->channels == 2 ? 1 : 0;
  359. mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
  360. mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
  361. if (!mc->magnitude || !mc->angle)
  362. return AVERROR(ENOMEM);
  363. if (mc->coupling_steps) {
  364. mc->magnitude[0] = 0;
  365. mc->angle[0] = 1;
  366. }
  367. venc->nmodes = 1;
  368. venc->modes = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
  369. if (!venc->modes)
  370. return AVERROR(ENOMEM);
  371. // single mode
  372. venc->modes[0].blockflag = 0;
  373. venc->modes[0].mapping = 0;
  374. venc->have_saved = 0;
  375. venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  376. venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
  377. venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  378. venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  379. if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs)
  380. return AVERROR(ENOMEM);
  381. venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
  382. venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
  383. if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0)
  384. return ret;
  385. if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0)
  386. return ret;
  387. return 0;
  388. }
  389. static void put_float(PutBitContext *pb, float f)
  390. {
  391. int exp, mant;
  392. uint32_t res = 0;
  393. mant = (int)ldexp(frexp(f, &exp), 20);
  394. exp += 788 - 20;
  395. if (mant < 0) {
  396. res |= (1U << 31);
  397. mant = -mant;
  398. }
  399. res |= mant | (exp << 21);
  400. put_bits32(pb, res);
  401. }
  402. static void put_codebook_header(PutBitContext *pb, vorbis_enc_codebook *cb)
  403. {
  404. int i;
  405. int ordered = 0;
  406. put_bits(pb, 24, 0x564342); //magic
  407. put_bits(pb, 16, cb->ndimensions);
  408. put_bits(pb, 24, cb->nentries);
  409. for (i = 1; i < cb->nentries; i++)
  410. if (cb->lens[i] < cb->lens[i-1])
  411. break;
  412. if (i == cb->nentries)
  413. ordered = 1;
  414. put_bits(pb, 1, ordered);
  415. if (ordered) {
  416. int len = cb->lens[0];
  417. put_bits(pb, 5, len - 1);
  418. i = 0;
  419. while (i < cb->nentries) {
  420. int j;
  421. for (j = 0; j+i < cb->nentries; j++)
  422. if (cb->lens[j+i] != len)
  423. break;
  424. put_bits(pb, ilog(cb->nentries - i), j);
  425. i += j;
  426. len++;
  427. }
  428. } else {
  429. int sparse = 0;
  430. for (i = 0; i < cb->nentries; i++)
  431. if (!cb->lens[i])
  432. break;
  433. if (i != cb->nentries)
  434. sparse = 1;
  435. put_bits(pb, 1, sparse);
  436. for (i = 0; i < cb->nentries; i++) {
  437. if (sparse)
  438. put_bits(pb, 1, !!cb->lens[i]);
  439. if (cb->lens[i])
  440. put_bits(pb, 5, cb->lens[i] - 1);
  441. }
  442. }
  443. put_bits(pb, 4, cb->lookup);
  444. if (cb->lookup) {
  445. int tmp = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
  446. int bits = ilog(cb->quantlist[0]);
  447. for (i = 1; i < tmp; i++)
  448. bits = FFMAX(bits, ilog(cb->quantlist[i]));
  449. put_float(pb, cb->min);
  450. put_float(pb, cb->delta);
  451. put_bits(pb, 4, bits - 1);
  452. put_bits(pb, 1, cb->seq_p);
  453. for (i = 0; i < tmp; i++)
  454. put_bits(pb, bits, cb->quantlist[i]);
  455. }
  456. }
  457. static void put_floor_header(PutBitContext *pb, vorbis_enc_floor *fc)
  458. {
  459. int i;
  460. put_bits(pb, 16, 1); // type, only floor1 is supported
  461. put_bits(pb, 5, fc->partitions);
  462. for (i = 0; i < fc->partitions; i++)
  463. put_bits(pb, 4, fc->partition_to_class[i]);
  464. for (i = 0; i < fc->nclasses; i++) {
  465. int j, books;
  466. put_bits(pb, 3, fc->classes[i].dim - 1);
  467. put_bits(pb, 2, fc->classes[i].subclass);
  468. if (fc->classes[i].subclass)
  469. put_bits(pb, 8, fc->classes[i].masterbook);
  470. books = (1 << fc->classes[i].subclass);
  471. for (j = 0; j < books; j++)
  472. put_bits(pb, 8, fc->classes[i].books[j] + 1);
  473. }
  474. put_bits(pb, 2, fc->multiplier - 1);
  475. put_bits(pb, 4, fc->rangebits);
  476. for (i = 2; i < fc->values; i++)
  477. put_bits(pb, fc->rangebits, fc->list[i].x);
  478. }
  479. static void put_residue_header(PutBitContext *pb, vorbis_enc_residue *rc)
  480. {
  481. int i;
  482. put_bits(pb, 16, rc->type);
  483. put_bits(pb, 24, rc->begin);
  484. put_bits(pb, 24, rc->end);
  485. put_bits(pb, 24, rc->partition_size - 1);
  486. put_bits(pb, 6, rc->classifications - 1);
  487. put_bits(pb, 8, rc->classbook);
  488. for (i = 0; i < rc->classifications; i++) {
  489. int j, tmp = 0;
  490. for (j = 0; j < 8; j++)
  491. tmp |= (rc->books[i][j] != -1) << j;
  492. put_bits(pb, 3, tmp & 7);
  493. put_bits(pb, 1, tmp > 7);
  494. if (tmp > 7)
  495. put_bits(pb, 5, tmp >> 3);
  496. }
  497. for (i = 0; i < rc->classifications; i++) {
  498. int j;
  499. for (j = 0; j < 8; j++)
  500. if (rc->books[i][j] != -1)
  501. put_bits(pb, 8, rc->books[i][j]);
  502. }
  503. }
  504. static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
  505. {
  506. int i;
  507. PutBitContext pb;
  508. uint8_t buffer[50000] = {0}, *p = buffer;
  509. int buffer_len = sizeof buffer;
  510. int len, hlens[3];
  511. // identification header
  512. init_put_bits(&pb, p, buffer_len);
  513. put_bits(&pb, 8, 1); //magic
  514. for (i = 0; "vorbis"[i]; i++)
  515. put_bits(&pb, 8, "vorbis"[i]);
  516. put_bits32(&pb, 0); // version
  517. put_bits(&pb, 8, venc->channels);
  518. put_bits32(&pb, venc->sample_rate);
  519. put_bits32(&pb, 0); // bitrate
  520. put_bits32(&pb, 0); // bitrate
  521. put_bits32(&pb, 0); // bitrate
  522. put_bits(&pb, 4, venc->log2_blocksize[0]);
  523. put_bits(&pb, 4, venc->log2_blocksize[1]);
  524. put_bits(&pb, 1, 1); // framing
  525. flush_put_bits(&pb);
  526. hlens[0] = put_bits_count(&pb) >> 3;
  527. buffer_len -= hlens[0];
  528. p += hlens[0];
  529. // comment header
  530. init_put_bits(&pb, p, buffer_len);
  531. put_bits(&pb, 8, 3); //magic
  532. for (i = 0; "vorbis"[i]; i++)
  533. put_bits(&pb, 8, "vorbis"[i]);
  534. put_bits32(&pb, 0); // vendor length TODO
  535. put_bits32(&pb, 0); // amount of comments
  536. put_bits(&pb, 1, 1); // framing
  537. flush_put_bits(&pb);
  538. hlens[1] = put_bits_count(&pb) >> 3;
  539. buffer_len -= hlens[1];
  540. p += hlens[1];
  541. // setup header
  542. init_put_bits(&pb, p, buffer_len);
  543. put_bits(&pb, 8, 5); //magic
  544. for (i = 0; "vorbis"[i]; i++)
  545. put_bits(&pb, 8, "vorbis"[i]);
  546. // codebooks
  547. put_bits(&pb, 8, venc->ncodebooks - 1);
  548. for (i = 0; i < venc->ncodebooks; i++)
  549. put_codebook_header(&pb, &venc->codebooks[i]);
  550. // time domain, reserved, zero
  551. put_bits(&pb, 6, 0);
  552. put_bits(&pb, 16, 0);
  553. // floors
  554. put_bits(&pb, 6, venc->nfloors - 1);
  555. for (i = 0; i < venc->nfloors; i++)
  556. put_floor_header(&pb, &venc->floors[i]);
  557. // residues
  558. put_bits(&pb, 6, venc->nresidues - 1);
  559. for (i = 0; i < venc->nresidues; i++)
  560. put_residue_header(&pb, &venc->residues[i]);
  561. // mappings
  562. put_bits(&pb, 6, venc->nmappings - 1);
  563. for (i = 0; i < venc->nmappings; i++) {
  564. vorbis_enc_mapping *mc = &venc->mappings[i];
  565. int j;
  566. put_bits(&pb, 16, 0); // mapping type
  567. put_bits(&pb, 1, mc->submaps > 1);
  568. if (mc->submaps > 1)
  569. put_bits(&pb, 4, mc->submaps - 1);
  570. put_bits(&pb, 1, !!mc->coupling_steps);
  571. if (mc->coupling_steps) {
  572. put_bits(&pb, 8, mc->coupling_steps - 1);
  573. for (j = 0; j < mc->coupling_steps; j++) {
  574. put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
  575. put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
  576. }
  577. }
  578. put_bits(&pb, 2, 0); // reserved
  579. if (mc->submaps > 1)
  580. for (j = 0; j < venc->channels; j++)
  581. put_bits(&pb, 4, mc->mux[j]);
  582. for (j = 0; j < mc->submaps; j++) {
  583. put_bits(&pb, 8, 0); // reserved time configuration
  584. put_bits(&pb, 8, mc->floor[j]);
  585. put_bits(&pb, 8, mc->residue[j]);
  586. }
  587. }
  588. // modes
  589. put_bits(&pb, 6, venc->nmodes - 1);
  590. for (i = 0; i < venc->nmodes; i++) {
  591. put_bits(&pb, 1, venc->modes[i].blockflag);
  592. put_bits(&pb, 16, 0); // reserved window type
  593. put_bits(&pb, 16, 0); // reserved transform type
  594. put_bits(&pb, 8, venc->modes[i].mapping);
  595. }
  596. put_bits(&pb, 1, 1); // framing
  597. flush_put_bits(&pb);
  598. hlens[2] = put_bits_count(&pb) >> 3;
  599. len = hlens[0] + hlens[1] + hlens[2];
  600. p = *out = av_mallocz(64 + len + len/255);
  601. if (!p)
  602. return AVERROR(ENOMEM);
  603. *p++ = 2;
  604. p += av_xiphlacing(p, hlens[0]);
  605. p += av_xiphlacing(p, hlens[1]);
  606. buffer_len = 0;
  607. for (i = 0; i < 3; i++) {
  608. memcpy(p, buffer + buffer_len, hlens[i]);
  609. p += hlens[i];
  610. buffer_len += hlens[i];
  611. }
  612. return p - *out;
  613. }
  614. static float get_floor_average(vorbis_enc_floor * fc, float *coeffs, int i)
  615. {
  616. int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
  617. int end = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
  618. int j;
  619. float average = 0;
  620. for (j = begin; j < end; j++)
  621. average += fabs(coeffs[j]);
  622. return average / (end - begin);
  623. }
  624. static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
  625. float *coeffs, uint16_t *posts, int samples)
  626. {
  627. int range = 255 / fc->multiplier + 1;
  628. int i;
  629. float tot_average = 0.0;
  630. float averages[MAX_FLOOR_VALUES];
  631. for (i = 0; i < fc->values; i++) {
  632. averages[i] = get_floor_average(fc, coeffs, i);
  633. tot_average += averages[i];
  634. }
  635. tot_average /= fc->values;
  636. tot_average /= venc->quality;
  637. for (i = 0; i < fc->values; i++) {
  638. int position = fc->list[fc->list[i].sort].x;
  639. float average = averages[i];
  640. int j;
  641. average = sqrt(tot_average * average) * pow(1.25f, position*0.005f); // MAGIC!
  642. for (j = 0; j < range - 1; j++)
  643. if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
  644. break;
  645. posts[fc->list[i].sort] = j;
  646. }
  647. }
  648. static int render_point(int x0, int y0, int x1, int y1, int x)
  649. {
  650. return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
  651. }
  652. static int floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
  653. PutBitContext *pb, uint16_t *posts,
  654. float *floor, int samples)
  655. {
  656. int range = 255 / fc->multiplier + 1;
  657. int coded[MAX_FLOOR_VALUES]; // first 2 values are unused
  658. int i, counter;
  659. if (pb->size_in_bits - put_bits_count(pb) < 1 + 2 * ilog(range - 1))
  660. return AVERROR(EINVAL);
  661. put_bits(pb, 1, 1); // non zero
  662. put_bits(pb, ilog(range - 1), posts[0]);
  663. put_bits(pb, ilog(range - 1), posts[1]);
  664. coded[0] = coded[1] = 1;
  665. for (i = 2; i < fc->values; i++) {
  666. int predicted = render_point(fc->list[fc->list[i].low].x,
  667. posts[fc->list[i].low],
  668. fc->list[fc->list[i].high].x,
  669. posts[fc->list[i].high],
  670. fc->list[i].x);
  671. int highroom = range - predicted;
  672. int lowroom = predicted;
  673. int room = FFMIN(highroom, lowroom);
  674. if (predicted == posts[i]) {
  675. coded[i] = 0; // must be used later as flag!
  676. continue;
  677. } else {
  678. if (!coded[fc->list[i].low ])
  679. coded[fc->list[i].low ] = -1;
  680. if (!coded[fc->list[i].high])
  681. coded[fc->list[i].high] = -1;
  682. }
  683. if (posts[i] > predicted) {
  684. if (posts[i] - predicted > room)
  685. coded[i] = posts[i] - predicted + lowroom;
  686. else
  687. coded[i] = (posts[i] - predicted) << 1;
  688. } else {
  689. if (predicted - posts[i] > room)
  690. coded[i] = predicted - posts[i] + highroom - 1;
  691. else
  692. coded[i] = ((predicted - posts[i]) << 1) - 1;
  693. }
  694. }
  695. counter = 2;
  696. for (i = 0; i < fc->partitions; i++) {
  697. vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
  698. int k, cval = 0, csub = 1<<c->subclass;
  699. if (c->subclass) {
  700. vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
  701. int cshift = 0;
  702. for (k = 0; k < c->dim; k++) {
  703. int l;
  704. for (l = 0; l < csub; l++) {
  705. int maxval = 1;
  706. if (c->books[l] != -1)
  707. maxval = venc->codebooks[c->books[l]].nentries;
  708. // coded could be -1, but this still works, cause that is 0
  709. if (coded[counter + k] < maxval)
  710. break;
  711. }
  712. assert(l != csub);
  713. cval |= l << cshift;
  714. cshift += c->subclass;
  715. }
  716. if (put_codeword(pb, book, cval))
  717. return AVERROR(EINVAL);
  718. }
  719. for (k = 0; k < c->dim; k++) {
  720. int book = c->books[cval & (csub-1)];
  721. int entry = coded[counter++];
  722. cval >>= c->subclass;
  723. if (book == -1)
  724. continue;
  725. if (entry == -1)
  726. entry = 0;
  727. if (put_codeword(pb, &venc->codebooks[book], entry))
  728. return AVERROR(EINVAL);
  729. }
  730. }
  731. ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,
  732. fc->multiplier, floor, samples);
  733. return 0;
  734. }
  735. static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
  736. float *num)
  737. {
  738. int i, entry = -1;
  739. float distance = FLT_MAX;
  740. assert(book->dimensions);
  741. for (i = 0; i < book->nentries; i++) {
  742. float * vec = book->dimensions + i * book->ndimensions, d = book->pow2[i];
  743. int j;
  744. if (!book->lens[i])
  745. continue;
  746. for (j = 0; j < book->ndimensions; j++)
  747. d -= vec[j] * num[j];
  748. if (distance > d) {
  749. entry = i;
  750. distance = d;
  751. }
  752. }
  753. if (put_codeword(pb, book, entry))
  754. return NULL;
  755. return &book->dimensions[entry * book->ndimensions];
  756. }
  757. static int residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
  758. PutBitContext *pb, float *coeffs, int samples,
  759. int real_ch)
  760. {
  761. int pass, i, j, p, k;
  762. int psize = rc->partition_size;
  763. int partitions = (rc->end - rc->begin) / psize;
  764. int channels = (rc->type == 2) ? 1 : real_ch;
  765. int classes[MAX_CHANNELS][NUM_RESIDUE_PARTITIONS];
  766. int classwords = venc->codebooks[rc->classbook].ndimensions;
  767. assert(rc->type == 2);
  768. assert(real_ch == 2);
  769. for (p = 0; p < partitions; p++) {
  770. float max1 = 0.0, max2 = 0.0;
  771. int s = rc->begin + p * psize;
  772. for (k = s; k < s + psize; k += 2) {
  773. max1 = FFMAX(max1, fabs(coeffs[ k / real_ch]));
  774. max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
  775. }
  776. for (i = 0; i < rc->classifications - 1; i++)
  777. if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1])
  778. break;
  779. classes[0][p] = i;
  780. }
  781. for (pass = 0; pass < 8; pass++) {
  782. p = 0;
  783. while (p < partitions) {
  784. if (pass == 0)
  785. for (j = 0; j < channels; j++) {
  786. vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
  787. int entry = 0;
  788. for (i = 0; i < classwords; i++) {
  789. entry *= rc->classifications;
  790. entry += classes[j][p + i];
  791. }
  792. if (put_codeword(pb, book, entry))
  793. return AVERROR(EINVAL);
  794. }
  795. for (i = 0; i < classwords && p < partitions; i++, p++) {
  796. for (j = 0; j < channels; j++) {
  797. int nbook = rc->books[classes[j][p]][pass];
  798. vorbis_enc_codebook * book = &venc->codebooks[nbook];
  799. float *buf = coeffs + samples*j + rc->begin + p*psize;
  800. if (nbook == -1)
  801. continue;
  802. assert(rc->type == 0 || rc->type == 2);
  803. assert(!(psize % book->ndimensions));
  804. if (rc->type == 0) {
  805. for (k = 0; k < psize; k += book->ndimensions) {
  806. int l;
  807. float *a = put_vector(book, pb, &buf[k]);
  808. if (!a)
  809. return AVERROR(EINVAL);
  810. for (l = 0; l < book->ndimensions; l++)
  811. buf[k + l] -= a[l];
  812. }
  813. } else {
  814. int s = rc->begin + p * psize, a1, b1;
  815. a1 = (s % real_ch) * samples;
  816. b1 = s / real_ch;
  817. s = real_ch * samples;
  818. for (k = 0; k < psize; k += book->ndimensions) {
  819. int dim, a2 = a1, b2 = b1;
  820. float vec[MAX_CODEBOOK_DIM], *pv = vec;
  821. for (dim = book->ndimensions; dim--; ) {
  822. *pv++ = coeffs[a2 + b2];
  823. if ((a2 += samples) == s) {
  824. a2 = 0;
  825. b2++;
  826. }
  827. }
  828. pv = put_vector(book, pb, vec);
  829. if (!pv)
  830. return AVERROR(EINVAL);
  831. for (dim = book->ndimensions; dim--; ) {
  832. coeffs[a1 + b1] -= *pv++;
  833. if ((a1 += samples) == s) {
  834. a1 = 0;
  835. b1++;
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. return 0;
  845. }
  846. static int apply_window_and_mdct(vorbis_enc_context *venc,
  847. float **audio, int samples)
  848. {
  849. int i, channel;
  850. const float * win = venc->win[0];
  851. int window_len = 1 << (venc->log2_blocksize[0] - 1);
  852. float n = (float)(1 << venc->log2_blocksize[0]) / 4.0;
  853. // FIXME use dsp
  854. if (!venc->have_saved && !samples)
  855. return 0;
  856. if (venc->have_saved) {
  857. for (channel = 0; channel < venc->channels; channel++)
  858. memcpy(venc->samples + channel * window_len * 2,
  859. venc->saved + channel * window_len, sizeof(float) * window_len);
  860. } else {
  861. for (channel = 0; channel < venc->channels; channel++)
  862. memset(venc->samples + channel * window_len * 2, 0,
  863. sizeof(float) * window_len);
  864. }
  865. if (samples) {
  866. for (channel = 0; channel < venc->channels; channel++) {
  867. float * offset = venc->samples + channel*window_len*2 + window_len;
  868. for (i = 0; i < samples; i++)
  869. offset[i] = audio[channel][i] / n * win[window_len - i - 1];
  870. }
  871. } else {
  872. for (channel = 0; channel < venc->channels; channel++)
  873. memset(venc->samples + channel * window_len * 2 + window_len,
  874. 0, sizeof(float) * window_len);
  875. }
  876. for (channel = 0; channel < venc->channels; channel++)
  877. venc->mdct[0].mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,
  878. venc->samples + channel * window_len * 2);
  879. if (samples) {
  880. for (channel = 0; channel < venc->channels; channel++) {
  881. float *offset = venc->saved + channel * window_len;
  882. for (i = 0; i < samples; i++)
  883. offset[i] = audio[channel][i] / n * win[i];
  884. }
  885. venc->have_saved = 1;
  886. } else {
  887. venc->have_saved = 0;
  888. }
  889. return 1;
  890. }
  891. static int vorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  892. const AVFrame *frame, int *got_packet_ptr)
  893. {
  894. vorbis_enc_context *venc = avctx->priv_data;
  895. float **audio = frame ? (float **)frame->extended_data : NULL;
  896. int samples = frame ? frame->nb_samples : 0;
  897. vorbis_enc_mode *mode;
  898. vorbis_enc_mapping *mapping;
  899. PutBitContext pb;
  900. int i, ret;
  901. if (!apply_window_and_mdct(venc, audio, samples))
  902. return 0;
  903. samples = 1 << (venc->log2_blocksize[0] - 1);
  904. if ((ret = ff_alloc_packet(avpkt, 8192))) {
  905. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  906. return ret;
  907. }
  908. init_put_bits(&pb, avpkt->data, avpkt->size);
  909. if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {
  910. av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
  911. return AVERROR(EINVAL);
  912. }
  913. put_bits(&pb, 1, 0); // magic bit
  914. put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
  915. mode = &venc->modes[0];
  916. mapping = &venc->mappings[mode->mapping];
  917. if (mode->blockflag) {
  918. put_bits(&pb, 1, 0);
  919. put_bits(&pb, 1, 0);
  920. }
  921. for (i = 0; i < venc->channels; i++) {
  922. vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
  923. uint16_t posts[MAX_FLOOR_VALUES];
  924. floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
  925. if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples)) {
  926. av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
  927. return AVERROR(EINVAL);
  928. }
  929. }
  930. for (i = 0; i < venc->channels * samples; i++)
  931. venc->coeffs[i] /= venc->floor[i];
  932. for (i = 0; i < mapping->coupling_steps; i++) {
  933. float *mag = venc->coeffs + mapping->magnitude[i] * samples;
  934. float *ang = venc->coeffs + mapping->angle[i] * samples;
  935. int j;
  936. for (j = 0; j < samples; j++) {
  937. float a = ang[j];
  938. ang[j] -= mag[j];
  939. if (mag[j] > 0)
  940. ang[j] = -ang[j];
  941. if (ang[j] < 0)
  942. mag[j] = a;
  943. }
  944. }
  945. if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],
  946. &pb, venc->coeffs, samples, venc->channels)) {
  947. av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
  948. return AVERROR(EINVAL);
  949. }
  950. flush_put_bits(&pb);
  951. avpkt->size = put_bits_count(&pb) >> 3;
  952. avpkt->duration = ff_samples_to_time_base(avctx, avctx->frame_size);
  953. if (frame)
  954. if (frame->pts != AV_NOPTS_VALUE)
  955. avpkt->pts = ff_samples_to_time_base(avctx, frame->pts);
  956. else
  957. avpkt->pts = venc->next_pts;
  958. if (avpkt->pts != AV_NOPTS_VALUE)
  959. venc->next_pts = avpkt->pts + avpkt->duration;
  960. *got_packet_ptr = 1;
  961. return 0;
  962. }
  963. static av_cold int vorbis_encode_close(AVCodecContext *avctx)
  964. {
  965. vorbis_enc_context *venc = avctx->priv_data;
  966. int i;
  967. if (venc->codebooks)
  968. for (i = 0; i < venc->ncodebooks; i++) {
  969. av_freep(&venc->codebooks[i].lens);
  970. av_freep(&venc->codebooks[i].codewords);
  971. av_freep(&venc->codebooks[i].quantlist);
  972. av_freep(&venc->codebooks[i].dimensions);
  973. av_freep(&venc->codebooks[i].pow2);
  974. }
  975. av_freep(&venc->codebooks);
  976. if (venc->floors)
  977. for (i = 0; i < venc->nfloors; i++) {
  978. int j;
  979. if (venc->floors[i].classes)
  980. for (j = 0; j < venc->floors[i].nclasses; j++)
  981. av_freep(&venc->floors[i].classes[j].books);
  982. av_freep(&venc->floors[i].classes);
  983. av_freep(&venc->floors[i].partition_to_class);
  984. av_freep(&venc->floors[i].list);
  985. }
  986. av_freep(&venc->floors);
  987. if (venc->residues)
  988. for (i = 0; i < venc->nresidues; i++) {
  989. av_freep(&venc->residues[i].books);
  990. av_freep(&venc->residues[i].maxes);
  991. }
  992. av_freep(&venc->residues);
  993. if (venc->mappings)
  994. for (i = 0; i < venc->nmappings; i++) {
  995. av_freep(&venc->mappings[i].mux);
  996. av_freep(&venc->mappings[i].floor);
  997. av_freep(&venc->mappings[i].residue);
  998. av_freep(&venc->mappings[i].magnitude);
  999. av_freep(&venc->mappings[i].angle);
  1000. }
  1001. av_freep(&venc->mappings);
  1002. av_freep(&venc->modes);
  1003. av_freep(&venc->saved);
  1004. av_freep(&venc->samples);
  1005. av_freep(&venc->floor);
  1006. av_freep(&venc->coeffs);
  1007. ff_mdct_end(&venc->mdct[0]);
  1008. ff_mdct_end(&venc->mdct[1]);
  1009. av_freep(&avctx->extradata);
  1010. return 0 ;
  1011. }
  1012. static av_cold int vorbis_encode_init(AVCodecContext *avctx)
  1013. {
  1014. vorbis_enc_context *venc = avctx->priv_data;
  1015. int ret;
  1016. if (avctx->channels != 2) {
  1017. av_log(avctx, AV_LOG_ERROR, "Current Libav Vorbis encoder only supports 2 channels.\n");
  1018. return -1;
  1019. }
  1020. if ((ret = create_vorbis_context(venc, avctx)) < 0)
  1021. goto error;
  1022. avctx->bit_rate = 0;
  1023. if (avctx->flags & CODEC_FLAG_QSCALE)
  1024. venc->quality = avctx->global_quality / (float)FF_QP2LAMBDA;
  1025. else
  1026. venc->quality = 3.0;
  1027. venc->quality *= venc->quality;
  1028. if ((ret = put_main_header(venc, (uint8_t**)&avctx->extradata)) < 0)
  1029. goto error;
  1030. avctx->extradata_size = ret;
  1031. avctx->frame_size = 1 << (venc->log2_blocksize[0] - 1);
  1032. return 0;
  1033. error:
  1034. vorbis_encode_close(avctx);
  1035. return ret;
  1036. }
  1037. AVCodec ff_vorbis_encoder = {
  1038. .name = "vorbis",
  1039. .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
  1040. .type = AVMEDIA_TYPE_AUDIO,
  1041. .id = AV_CODEC_ID_VORBIS,
  1042. .priv_data_size = sizeof(vorbis_enc_context),
  1043. .init = vorbis_encode_init,
  1044. .encode2 = vorbis_encode_frame,
  1045. .close = vorbis_encode_close,
  1046. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  1047. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
  1048. AV_SAMPLE_FMT_NONE },
  1049. };