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.

1212 lines
38KB

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