vorbis_enc.c 33 KB

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