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.

1173 lines
36KB

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