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