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.

1200 lines
37KB

  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 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 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 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.;
  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 *avccontext)
  210. {
  211. vorbis_enc_floor *fc;
  212. vorbis_enc_residue *rc;
  213. vorbis_enc_mapping *mc;
  214. int i, book, ret;
  215. venc->channels = avccontext->channels;
  216. venc->sample_rate = avccontext->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. ff_vorbis_ready_floor1_list(fc->list, fc->values);
  305. venc->nresidues = 1;
  306. venc->residues = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
  307. if (!venc->residues)
  308. return AVERROR(ENOMEM);
  309. // single residue
  310. rc = &venc->residues[0];
  311. rc->type = 2;
  312. rc->begin = 0;
  313. rc->end = 1600;
  314. rc->partition_size = 32;
  315. rc->classifications = 10;
  316. rc->classbook = 15;
  317. rc->books = av_malloc(sizeof(*rc->books) * rc->classifications);
  318. if (!rc->books)
  319. return AVERROR(ENOMEM);
  320. {
  321. static const int8_t a[10][8] = {
  322. { -1, -1, -1, -1, -1, -1, -1, -1, },
  323. { -1, -1, 16, -1, -1, -1, -1, -1, },
  324. { -1, -1, 17, -1, -1, -1, -1, -1, },
  325. { -1, -1, 18, -1, -1, -1, -1, -1, },
  326. { -1, -1, 19, -1, -1, -1, -1, -1, },
  327. { -1, -1, 20, -1, -1, -1, -1, -1, },
  328. { -1, -1, 21, -1, -1, -1, -1, -1, },
  329. { 22, 23, -1, -1, -1, -1, -1, -1, },
  330. { 24, 25, -1, -1, -1, -1, -1, -1, },
  331. { 26, 27, 28, -1, -1, -1, -1, -1, },
  332. };
  333. memcpy(rc->books, a, sizeof a);
  334. }
  335. if ((ret = ready_residue(rc, venc)) < 0)
  336. return ret;
  337. venc->nmappings = 1;
  338. venc->mappings = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
  339. if (!venc->mappings)
  340. return AVERROR(ENOMEM);
  341. // single mapping
  342. mc = &venc->mappings[0];
  343. mc->submaps = 1;
  344. mc->mux = av_malloc(sizeof(int) * venc->channels);
  345. if (!mc->mux)
  346. return AVERROR(ENOMEM);
  347. for (i = 0; i < venc->channels; i++)
  348. mc->mux[i] = 0;
  349. mc->floor = av_malloc(sizeof(int) * mc->submaps);
  350. mc->residue = av_malloc(sizeof(int) * mc->submaps);
  351. if (!mc->floor || !mc->residue)
  352. return AVERROR(ENOMEM);
  353. for (i = 0; i < mc->submaps; i++) {
  354. mc->floor[i] = 0;
  355. mc->residue[i] = 0;
  356. }
  357. mc->coupling_steps = venc->channels == 2 ? 1 : 0;
  358. mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
  359. mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
  360. if (!mc->magnitude || !mc->angle)
  361. return AVERROR(ENOMEM);
  362. if (mc->coupling_steps) {
  363. mc->magnitude[0] = 0;
  364. mc->angle[0] = 1;
  365. }
  366. venc->nmodes = 1;
  367. venc->modes = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
  368. if (!venc->modes)
  369. return AVERROR(ENOMEM);
  370. // single mode
  371. venc->modes[0].blockflag = 0;
  372. venc->modes[0].mapping = 0;
  373. venc->have_saved = 0;
  374. venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  375. venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
  376. venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  377. venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
  378. if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs)
  379. return AVERROR(ENOMEM);
  380. venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
  381. venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
  382. if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0)
  383. return ret;
  384. if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0)
  385. return ret;
  386. return 0;
  387. }
  388. static void put_float(PutBitContext *pb, float f)
  389. {
  390. int exp, mant;
  391. uint32_t res = 0;
  392. mant = (int)ldexp(frexp(f, &exp), 20);
  393. exp += 788 - 20;
  394. if (mant < 0) {
  395. res |= (1U << 31);
  396. mant = -mant;
  397. }
  398. res |= mant | (exp << 21);
  399. put_bits32(pb, res);
  400. }
  401. static void put_codebook_header(PutBitContext *pb, vorbis_enc_codebook *cb)
  402. {
  403. int i;
  404. int ordered = 0;
  405. put_bits(pb, 24, 0x564342); //magic
  406. put_bits(pb, 16, cb->ndimensions);
  407. put_bits(pb, 24, cb->nentries);
  408. for (i = 1; i < cb->nentries; i++)
  409. if (cb->lens[i] < cb->lens[i-1])
  410. break;
  411. if (i == cb->nentries)
  412. ordered = 1;
  413. put_bits(pb, 1, ordered);
  414. if (ordered) {
  415. int len = cb->lens[0];
  416. put_bits(pb, 5, len - 1);
  417. i = 0;
  418. while (i < cb->nentries) {
  419. int j;
  420. for (j = 0; j+i < cb->nentries; j++)
  421. if (cb->lens[j+i] != len)
  422. break;
  423. put_bits(pb, ilog(cb->nentries - i), j);
  424. i += j;
  425. len++;
  426. }
  427. } else {
  428. int sparse = 0;
  429. for (i = 0; i < cb->nentries; i++)
  430. if (!cb->lens[i])
  431. break;
  432. if (i != cb->nentries)
  433. sparse = 1;
  434. put_bits(pb, 1, sparse);
  435. for (i = 0; i < cb->nentries; i++) {
  436. if (sparse)
  437. put_bits(pb, 1, !!cb->lens[i]);
  438. if (cb->lens[i])
  439. put_bits(pb, 5, cb->lens[i] - 1);
  440. }
  441. }
  442. put_bits(pb, 4, cb->lookup);
  443. if (cb->lookup) {
  444. int tmp = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
  445. int bits = ilog(cb->quantlist[0]);
  446. for (i = 1; i < tmp; i++)
  447. bits = FFMAX(bits, ilog(cb->quantlist[i]));
  448. put_float(pb, cb->min);
  449. put_float(pb, cb->delta);
  450. put_bits(pb, 4, bits - 1);
  451. put_bits(pb, 1, cb->seq_p);
  452. for (i = 0; i < tmp; i++)
  453. put_bits(pb, bits, cb->quantlist[i]);
  454. }
  455. }
  456. static void put_floor_header(PutBitContext *pb, vorbis_enc_floor *fc)
  457. {
  458. int i;
  459. put_bits(pb, 16, 1); // type, only floor1 is supported
  460. put_bits(pb, 5, fc->partitions);
  461. for (i = 0; i < fc->partitions; i++)
  462. put_bits(pb, 4, fc->partition_to_class[i]);
  463. for (i = 0; i < fc->nclasses; i++) {
  464. int j, books;
  465. put_bits(pb, 3, fc->classes[i].dim - 1);
  466. put_bits(pb, 2, fc->classes[i].subclass);
  467. if (fc->classes[i].subclass)
  468. put_bits(pb, 8, fc->classes[i].masterbook);
  469. books = (1 << fc->classes[i].subclass);
  470. for (j = 0; j < books; j++)
  471. put_bits(pb, 8, fc->classes[i].books[j] + 1);
  472. }
  473. put_bits(pb, 2, fc->multiplier - 1);
  474. put_bits(pb, 4, fc->rangebits);
  475. for (i = 2; i < fc->values; i++)
  476. put_bits(pb, fc->rangebits, fc->list[i].x);
  477. }
  478. static void put_residue_header(PutBitContext *pb, vorbis_enc_residue *rc)
  479. {
  480. int i;
  481. put_bits(pb, 16, rc->type);
  482. put_bits(pb, 24, rc->begin);
  483. put_bits(pb, 24, rc->end);
  484. put_bits(pb, 24, rc->partition_size - 1);
  485. put_bits(pb, 6, rc->classifications - 1);
  486. put_bits(pb, 8, rc->classbook);
  487. for (i = 0; i < rc->classifications; i++) {
  488. int j, tmp = 0;
  489. for (j = 0; j < 8; j++)
  490. tmp |= (rc->books[i][j] != -1) << j;
  491. put_bits(pb, 3, tmp & 7);
  492. put_bits(pb, 1, tmp > 7);
  493. if (tmp > 7)
  494. put_bits(pb, 5, tmp >> 3);
  495. }
  496. for (i = 0; i < rc->classifications; i++) {
  497. int j;
  498. for (j = 0; j < 8; j++)
  499. if (rc->books[i][j] != -1)
  500. put_bits(pb, 8, rc->books[i][j]);
  501. }
  502. }
  503. static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
  504. {
  505. int i;
  506. PutBitContext pb;
  507. uint8_t buffer[50000] = {0}, *p = buffer;
  508. int buffer_len = sizeof buffer;
  509. int len, hlens[3];
  510. // identification header
  511. init_put_bits(&pb, p, buffer_len);
  512. put_bits(&pb, 8, 1); //magic
  513. for (i = 0; "vorbis"[i]; i++)
  514. put_bits(&pb, 8, "vorbis"[i]);
  515. put_bits32(&pb, 0); // version
  516. put_bits(&pb, 8, venc->channels);
  517. put_bits32(&pb, venc->sample_rate);
  518. put_bits32(&pb, 0); // bitrate
  519. put_bits32(&pb, 0); // bitrate
  520. put_bits32(&pb, 0); // bitrate
  521. put_bits(&pb, 4, venc->log2_blocksize[0]);
  522. put_bits(&pb, 4, venc->log2_blocksize[1]);
  523. put_bits(&pb, 1, 1); // framing
  524. flush_put_bits(&pb);
  525. hlens[0] = put_bits_count(&pb) >> 3;
  526. buffer_len -= hlens[0];
  527. p += hlens[0];
  528. // comment header
  529. init_put_bits(&pb, p, buffer_len);
  530. put_bits(&pb, 8, 3); //magic
  531. for (i = 0; "vorbis"[i]; i++)
  532. put_bits(&pb, 8, "vorbis"[i]);
  533. put_bits32(&pb, 0); // vendor length TODO
  534. put_bits32(&pb, 0); // amount of comments
  535. put_bits(&pb, 1, 1); // framing
  536. flush_put_bits(&pb);
  537. hlens[1] = put_bits_count(&pb) >> 3;
  538. buffer_len -= hlens[1];
  539. p += hlens[1];
  540. // setup header
  541. init_put_bits(&pb, p, buffer_len);
  542. put_bits(&pb, 8, 5); //magic
  543. for (i = 0; "vorbis"[i]; i++)
  544. put_bits(&pb, 8, "vorbis"[i]);
  545. // codebooks
  546. put_bits(&pb, 8, venc->ncodebooks - 1);
  547. for (i = 0; i < venc->ncodebooks; i++)
  548. put_codebook_header(&pb, &venc->codebooks[i]);
  549. // time domain, reserved, zero
  550. put_bits(&pb, 6, 0);
  551. put_bits(&pb, 16, 0);
  552. // floors
  553. put_bits(&pb, 6, venc->nfloors - 1);
  554. for (i = 0; i < venc->nfloors; i++)
  555. put_floor_header(&pb, &venc->floors[i]);
  556. // residues
  557. put_bits(&pb, 6, venc->nresidues - 1);
  558. for (i = 0; i < venc->nresidues; i++)
  559. put_residue_header(&pb, &venc->residues[i]);
  560. // mappings
  561. put_bits(&pb, 6, venc->nmappings - 1);
  562. for (i = 0; i < venc->nmappings; i++) {
  563. vorbis_enc_mapping *mc = &venc->mappings[i];
  564. int j;
  565. put_bits(&pb, 16, 0); // mapping type
  566. put_bits(&pb, 1, mc->submaps > 1);
  567. if (mc->submaps > 1)
  568. put_bits(&pb, 4, mc->submaps - 1);
  569. put_bits(&pb, 1, !!mc->coupling_steps);
  570. if (mc->coupling_steps) {
  571. put_bits(&pb, 8, mc->coupling_steps - 1);
  572. for (j = 0; j < mc->coupling_steps; j++) {
  573. put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
  574. put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
  575. }
  576. }
  577. put_bits(&pb, 2, 0); // reserved
  578. if (mc->submaps > 1)
  579. for (j = 0; j < venc->channels; j++)
  580. put_bits(&pb, 4, mc->mux[j]);
  581. for (j = 0; j < mc->submaps; j++) {
  582. put_bits(&pb, 8, 0); // reserved time configuration
  583. put_bits(&pb, 8, mc->floor[j]);
  584. put_bits(&pb, 8, mc->residue[j]);
  585. }
  586. }
  587. // modes
  588. put_bits(&pb, 6, venc->nmodes - 1);
  589. for (i = 0; i < venc->nmodes; i++) {
  590. put_bits(&pb, 1, venc->modes[i].blockflag);
  591. put_bits(&pb, 16, 0); // reserved window type
  592. put_bits(&pb, 16, 0); // reserved transform type
  593. put_bits(&pb, 8, venc->modes[i].mapping);
  594. }
  595. put_bits(&pb, 1, 1); // framing
  596. flush_put_bits(&pb);
  597. hlens[2] = put_bits_count(&pb) >> 3;
  598. len = hlens[0] + hlens[1] + hlens[2];
  599. p = *out = av_mallocz(64 + len + len/255);
  600. if (!p)
  601. return AVERROR(ENOMEM);
  602. *p++ = 2;
  603. p += av_xiphlacing(p, hlens[0]);
  604. p += av_xiphlacing(p, hlens[1]);
  605. buffer_len = 0;
  606. for (i = 0; i < 3; i++) {
  607. memcpy(p, buffer + buffer_len, hlens[i]);
  608. p += hlens[i];
  609. buffer_len += hlens[i];
  610. }
  611. return p - *out;
  612. }
  613. static float get_floor_average(vorbis_enc_floor * fc, float *coeffs, int i)
  614. {
  615. int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
  616. int end = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
  617. int j;
  618. float average = 0;
  619. for (j = begin; j < end; j++)
  620. average += fabs(coeffs[j]);
  621. return average / (end - begin);
  622. }
  623. static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
  624. float *coeffs, uint16_t *posts, int samples)
  625. {
  626. int range = 255 / fc->multiplier + 1;
  627. int i;
  628. float tot_average = 0.;
  629. float averages[MAX_FLOOR_VALUES];
  630. for (i = 0; i < fc->values; i++) {
  631. averages[i] = get_floor_average(fc, coeffs, i);
  632. tot_average += averages[i];
  633. }
  634. tot_average /= fc->values;
  635. tot_average /= venc->quality;
  636. for (i = 0; i < fc->values; i++) {
  637. int position = fc->list[fc->list[i].sort].x;
  638. float average = averages[i];
  639. int j;
  640. average = sqrt(tot_average * average) * pow(1.25f, position*0.005f); // MAGIC!
  641. for (j = 0; j < range - 1; j++)
  642. if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
  643. break;
  644. posts[fc->list[i].sort] = j;
  645. }
  646. }
  647. static int render_point(int x0, int y0, int x1, int y1, int x)
  648. {
  649. return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
  650. }
  651. static int floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
  652. PutBitContext *pb, uint16_t *posts,
  653. float *floor, int samples)
  654. {
  655. int range = 255 / fc->multiplier + 1;
  656. int coded[MAX_FLOOR_VALUES]; // first 2 values are unused
  657. int i, counter;
  658. if (pb->size_in_bits - put_bits_count(pb) < 1 + 2 * ilog(range - 1))
  659. return AVERROR(EINVAL);
  660. put_bits(pb, 1, 1); // non zero
  661. put_bits(pb, ilog(range - 1), posts[0]);
  662. put_bits(pb, ilog(range - 1), posts[1]);
  663. coded[0] = coded[1] = 1;
  664. for (i = 2; i < fc->values; i++) {
  665. int predicted = render_point(fc->list[fc->list[i].low].x,
  666. posts[fc->list[i].low],
  667. fc->list[fc->list[i].high].x,
  668. posts[fc->list[i].high],
  669. fc->list[i].x);
  670. int highroom = range - predicted;
  671. int lowroom = predicted;
  672. int room = FFMIN(highroom, lowroom);
  673. if (predicted == posts[i]) {
  674. coded[i] = 0; // must be used later as flag!
  675. continue;
  676. } else {
  677. if (!coded[fc->list[i].low ])
  678. coded[fc->list[i].low ] = -1;
  679. if (!coded[fc->list[i].high])
  680. coded[fc->list[i].high] = -1;
  681. }
  682. if (posts[i] > predicted) {
  683. if (posts[i] - predicted > room)
  684. coded[i] = posts[i] - predicted + lowroom;
  685. else
  686. coded[i] = (posts[i] - predicted) << 1;
  687. } else {
  688. if (predicted - posts[i] > room)
  689. coded[i] = predicted - posts[i] + highroom - 1;
  690. else
  691. coded[i] = ((predicted - posts[i]) << 1) - 1;
  692. }
  693. }
  694. counter = 2;
  695. for (i = 0; i < fc->partitions; i++) {
  696. vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
  697. int k, cval = 0, csub = 1<<c->subclass;
  698. if (c->subclass) {
  699. vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
  700. int cshift = 0;
  701. for (k = 0; k < c->dim; k++) {
  702. int l;
  703. for (l = 0; l < csub; l++) {
  704. int maxval = 1;
  705. if (c->books[l] != -1)
  706. maxval = venc->codebooks[c->books[l]].nentries;
  707. // coded could be -1, but this still works, cause that is 0
  708. if (coded[counter + k] < maxval)
  709. break;
  710. }
  711. assert(l != csub);
  712. cval |= l << cshift;
  713. cshift += c->subclass;
  714. }
  715. if (put_codeword(pb, book, cval))
  716. return AVERROR(EINVAL);
  717. }
  718. for (k = 0; k < c->dim; k++) {
  719. int book = c->books[cval & (csub-1)];
  720. int entry = coded[counter++];
  721. cval >>= c->subclass;
  722. if (book == -1)
  723. continue;
  724. if (entry == -1)
  725. entry = 0;
  726. if (put_codeword(pb, &venc->codebooks[book], entry))
  727. return AVERROR(EINVAL);
  728. }
  729. }
  730. ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,
  731. fc->multiplier, floor, samples);
  732. return 0;
  733. }
  734. static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
  735. float *num)
  736. {
  737. int i, entry = -1;
  738. float distance = FLT_MAX;
  739. assert(book->dimensions);
  740. for (i = 0; i < book->nentries; i++) {
  741. float * vec = book->dimensions + i * book->ndimensions, d = book->pow2[i];
  742. int j;
  743. if (!book->lens[i])
  744. continue;
  745. for (j = 0; j < book->ndimensions; j++)
  746. d -= vec[j] * num[j];
  747. if (distance > d) {
  748. entry = i;
  749. distance = d;
  750. }
  751. }
  752. if (put_codeword(pb, book, entry))
  753. return NULL;
  754. return &book->dimensions[entry * book->ndimensions];
  755. }
  756. static int residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
  757. PutBitContext *pb, float *coeffs, int samples,
  758. int real_ch)
  759. {
  760. int pass, i, j, p, k;
  761. int psize = rc->partition_size;
  762. int partitions = (rc->end - rc->begin) / psize;
  763. int channels = (rc->type == 2) ? 1 : real_ch;
  764. int classes[MAX_CHANNELS][NUM_RESIDUE_PARTITIONS];
  765. int classwords = venc->codebooks[rc->classbook].ndimensions;
  766. assert(rc->type == 2);
  767. assert(real_ch == 2);
  768. for (p = 0; p < partitions; p++) {
  769. float max1 = 0., max2 = 0.;
  770. int s = rc->begin + p * psize;
  771. for (k = s; k < s + psize; k += 2) {
  772. max1 = FFMAX(max1, fabs(coeffs[ k / real_ch]));
  773. max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
  774. }
  775. for (i = 0; i < rc->classifications - 1; i++)
  776. if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1])
  777. break;
  778. classes[0][p] = i;
  779. }
  780. for (pass = 0; pass < 8; pass++) {
  781. p = 0;
  782. while (p < partitions) {
  783. if (pass == 0)
  784. for (j = 0; j < channels; j++) {
  785. vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
  786. int entry = 0;
  787. for (i = 0; i < classwords; i++) {
  788. entry *= rc->classifications;
  789. entry += classes[j][p + i];
  790. }
  791. if (put_codeword(pb, book, entry))
  792. return AVERROR(EINVAL);
  793. }
  794. for (i = 0; i < classwords && p < partitions; i++, p++) {
  795. for (j = 0; j < channels; j++) {
  796. int nbook = rc->books[classes[j][p]][pass];
  797. vorbis_enc_codebook * book = &venc->codebooks[nbook];
  798. float *buf = coeffs + samples*j + rc->begin + p*psize;
  799. if (nbook == -1)
  800. continue;
  801. assert(rc->type == 0 || rc->type == 2);
  802. assert(!(psize % book->ndimensions));
  803. if (rc->type == 0) {
  804. for (k = 0; k < psize; k += book->ndimensions) {
  805. int l;
  806. float *a = put_vector(book, pb, &buf[k]);
  807. if (!a)
  808. return AVERROR(EINVAL);
  809. for (l = 0; l < book->ndimensions; l++)
  810. buf[k + l] -= a[l];
  811. }
  812. } else {
  813. int s = rc->begin + p * psize, a1, b1;
  814. a1 = (s % real_ch) * samples;
  815. b1 = s / real_ch;
  816. s = real_ch * samples;
  817. for (k = 0; k < psize; k += book->ndimensions) {
  818. int dim, a2 = a1, b2 = b1;
  819. float vec[MAX_CODEBOOK_DIM], *pv = vec;
  820. for (dim = book->ndimensions; dim--; ) {
  821. *pv++ = coeffs[a2 + b2];
  822. if ((a2 += samples) == s) {
  823. a2 = 0;
  824. b2++;
  825. }
  826. }
  827. pv = put_vector(book, pb, vec);
  828. if (!pv)
  829. return AVERROR(EINVAL);
  830. for (dim = book->ndimensions; dim--; ) {
  831. coeffs[a1 + b1] -= *pv++;
  832. if ((a1 += samples) == s) {
  833. a1 = 0;
  834. b1++;
  835. }
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. return 0;
  844. }
  845. static int apply_window_and_mdct(vorbis_enc_context *venc, const signed short *audio,
  846. int samples)
  847. {
  848. int i, j, channel;
  849. const float * win = venc->win[0];
  850. int window_len = 1 << (venc->log2_blocksize[0] - 1);
  851. float n = (float)(1 << venc->log2_blocksize[0]) / 4.;
  852. // FIXME use dsp
  853. if (!venc->have_saved && !samples)
  854. return 0;
  855. if (venc->have_saved) {
  856. for (channel = 0; channel < venc->channels; channel++)
  857. memcpy(venc->samples + channel * window_len * 2,
  858. venc->saved + channel * window_len, sizeof(float) * window_len);
  859. } else {
  860. for (channel = 0; channel < venc->channels; channel++)
  861. memset(venc->samples + channel * window_len * 2, 0,
  862. sizeof(float) * window_len);
  863. }
  864. if (samples) {
  865. for (channel = 0; channel < venc->channels; channel++) {
  866. float * offset = venc->samples + channel*window_len*2 + window_len;
  867. j = channel;
  868. for (i = 0; i < samples; i++, j += venc->channels)
  869. offset[i] = audio[j] / 32768. / 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. j = channel;
  883. for (i = 0; i < samples; i++, j += venc->channels)
  884. offset[i] = audio[j] / 32768. / 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 *avccontext,
  893. unsigned char *packets,
  894. int buf_size, void *data)
  895. {
  896. vorbis_enc_context *venc = avccontext->priv_data;
  897. const signed short *audio = data;
  898. int samples = data ? avccontext->frame_size : 0;
  899. vorbis_enc_mode *mode;
  900. vorbis_enc_mapping *mapping;
  901. PutBitContext pb;
  902. int i;
  903. if (!apply_window_and_mdct(venc, audio, samples))
  904. return 0;
  905. samples = 1 << (venc->log2_blocksize[0] - 1);
  906. init_put_bits(&pb, packets, buf_size);
  907. if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {
  908. av_log(avccontext, AV_LOG_ERROR, "output buffer is too small\n");
  909. return AVERROR(EINVAL);
  910. }
  911. put_bits(&pb, 1, 0); // magic bit
  912. put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
  913. mode = &venc->modes[0];
  914. mapping = &venc->mappings[mode->mapping];
  915. if (mode->blockflag) {
  916. put_bits(&pb, 1, 0);
  917. put_bits(&pb, 1, 0);
  918. }
  919. for (i = 0; i < venc->channels; i++) {
  920. vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
  921. uint16_t posts[MAX_FLOOR_VALUES];
  922. floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
  923. if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples)) {
  924. av_log(avccontext, AV_LOG_ERROR, "output buffer is too small\n");
  925. return AVERROR(EINVAL);
  926. }
  927. }
  928. for (i = 0; i < venc->channels * samples; i++)
  929. venc->coeffs[i] /= venc->floor[i];
  930. for (i = 0; i < mapping->coupling_steps; i++) {
  931. float *mag = venc->coeffs + mapping->magnitude[i] * samples;
  932. float *ang = venc->coeffs + mapping->angle[i] * samples;
  933. int j;
  934. for (j = 0; j < samples; j++) {
  935. float a = ang[j];
  936. ang[j] -= mag[j];
  937. if (mag[j] > 0)
  938. ang[j] = -ang[j];
  939. if (ang[j] < 0)
  940. mag[j] = a;
  941. }
  942. }
  943. if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],
  944. &pb, venc->coeffs, samples, venc->channels)) {
  945. av_log(avccontext, AV_LOG_ERROR, "output buffer is too small\n");
  946. return AVERROR(EINVAL);
  947. }
  948. avccontext->coded_frame->pts = venc->sample_count;
  949. venc->sample_count += avccontext->frame_size;
  950. flush_put_bits(&pb);
  951. return put_bits_count(&pb) >> 3;
  952. }
  953. static av_cold int vorbis_encode_close(AVCodecContext *avccontext)
  954. {
  955. vorbis_enc_context *venc = avccontext->priv_data;
  956. int i;
  957. if (venc->codebooks)
  958. for (i = 0; i < venc->ncodebooks; i++) {
  959. av_freep(&venc->codebooks[i].lens);
  960. av_freep(&venc->codebooks[i].codewords);
  961. av_freep(&venc->codebooks[i].quantlist);
  962. av_freep(&venc->codebooks[i].dimensions);
  963. av_freep(&venc->codebooks[i].pow2);
  964. }
  965. av_freep(&venc->codebooks);
  966. if (venc->floors)
  967. for (i = 0; i < venc->nfloors; i++) {
  968. int j;
  969. if (venc->floors[i].classes)
  970. for (j = 0; j < venc->floors[i].nclasses; j++)
  971. av_freep(&venc->floors[i].classes[j].books);
  972. av_freep(&venc->floors[i].classes);
  973. av_freep(&venc->floors[i].partition_to_class);
  974. av_freep(&venc->floors[i].list);
  975. }
  976. av_freep(&venc->floors);
  977. if (venc->residues)
  978. for (i = 0; i < venc->nresidues; i++) {
  979. av_freep(&venc->residues[i].books);
  980. av_freep(&venc->residues[i].maxes);
  981. }
  982. av_freep(&venc->residues);
  983. if (venc->mappings)
  984. for (i = 0; i < venc->nmappings; i++) {
  985. av_freep(&venc->mappings[i].mux);
  986. av_freep(&venc->mappings[i].floor);
  987. av_freep(&venc->mappings[i].residue);
  988. av_freep(&venc->mappings[i].magnitude);
  989. av_freep(&venc->mappings[i].angle);
  990. }
  991. av_freep(&venc->mappings);
  992. av_freep(&venc->modes);
  993. av_freep(&venc->saved);
  994. av_freep(&venc->samples);
  995. av_freep(&venc->floor);
  996. av_freep(&venc->coeffs);
  997. ff_mdct_end(&venc->mdct[0]);
  998. ff_mdct_end(&venc->mdct[1]);
  999. av_freep(&avccontext->coded_frame);
  1000. av_freep(&avccontext->extradata);
  1001. return 0 ;
  1002. }
  1003. static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
  1004. {
  1005. vorbis_enc_context *venc = avccontext->priv_data;
  1006. int ret;
  1007. if (avccontext->channels != 2) {
  1008. av_log(avccontext, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
  1009. return -1;
  1010. }
  1011. if ((ret = create_vorbis_context(venc, avccontext)) < 0)
  1012. goto error;
  1013. if (avccontext->flags & CODEC_FLAG_QSCALE)
  1014. venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
  1015. else
  1016. venc->quality = 8;
  1017. venc->quality *= venc->quality;
  1018. if ((ret = put_main_header(venc, (uint8_t**)&avccontext->extradata)) < 0)
  1019. goto error;
  1020. avccontext->extradata_size = ret;
  1021. avccontext->frame_size = 1 << (venc->log2_blocksize[0] - 1);
  1022. avccontext->coded_frame = avcodec_alloc_frame();
  1023. if (!avccontext->coded_frame) {
  1024. ret = AVERROR(ENOMEM);
  1025. goto error;
  1026. }
  1027. return 0;
  1028. error:
  1029. vorbis_encode_close(avccontext);
  1030. return ret;
  1031. }
  1032. AVCodec ff_vorbis_encoder = {
  1033. .name = "vorbis",
  1034. .type = AVMEDIA_TYPE_AUDIO,
  1035. .id = CODEC_ID_VORBIS,
  1036. .priv_data_size = sizeof(vorbis_enc_context),
  1037. .init = vorbis_encode_init,
  1038. .encode = vorbis_encode_frame,
  1039. .close = vorbis_encode_close,
  1040. .capabilities= CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  1041. .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
  1042. .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
  1043. };