2 * copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
4 * This file is part of FFmpeg.
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.
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.
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
23 * Native Vorbis encoder.
24 * @author Oded Shimon <ods15@ods15.dyndns.org>
28 #include "libavutil/float_dsp.h"
35 #include "vorbis_enc_data.h"
37 #define BITSTREAM_WRITER_LE
43 typedef struct vorbis_enc_codebook {
55 } vorbis_enc_codebook;
57 typedef struct vorbis_enc_floor_class {
62 } vorbis_enc_floor_class;
64 typedef struct vorbis_enc_floor {
66 int *partition_to_class;
68 vorbis_enc_floor_class *classes;
72 vorbis_floor1_entry *list;
75 typedef struct vorbis_enc_residue {
86 typedef struct vorbis_enc_mapping {
96 typedef struct vorbis_enc_mode {
101 typedef struct vorbis_enc_context {
104 int log2_blocksize[2];
110 float *floor; // also used for tmp values for mdct
111 float *coeffs; // also used for residue after floor
115 vorbis_enc_codebook *codebooks;
118 vorbis_enc_floor *floors;
121 vorbis_enc_residue *residues;
124 vorbis_enc_mapping *mappings;
127 vorbis_enc_mode *modes;
131 AVFloatDSPContext *fdsp;
132 } vorbis_enc_context;
134 #define MAX_CHANNELS 2
135 #define MAX_CODEBOOK_DIM 8
137 #define MAX_FLOOR_CLASS_DIM 4
138 #define NUM_FLOOR_PARTITIONS 8
139 #define MAX_FLOOR_VALUES (MAX_FLOOR_CLASS_DIM*NUM_FLOOR_PARTITIONS+2)
141 #define RESIDUE_SIZE 1600
142 #define RESIDUE_PART_SIZE 32
143 #define NUM_RESIDUE_PARTITIONS (RESIDUE_SIZE/RESIDUE_PART_SIZE)
145 static inline int put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,
148 av_assert2(entry >= 0);
149 av_assert2(entry < cb->nentries);
150 av_assert2(cb->lens[entry]);
151 if (pb->size_in_bits - put_bits_count(pb) < cb->lens[entry])
152 return AVERROR(EINVAL);
153 put_bits(pb, cb->lens[entry], cb->codewords[entry]);
157 static int cb_lookup_vals(int lookup, int dimensions, int entries)
160 return ff_vorbis_nth_root(entries, dimensions);
161 else if (lookup == 2)
162 return dimensions *entries;
166 static int ready_codebook(vorbis_enc_codebook *cb)
170 ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
173 cb->pow2 = cb->dimensions = NULL;
175 int vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
176 cb->dimensions = av_malloc_array(cb->nentries, sizeof(float) * cb->ndimensions);
177 cb->pow2 = av_mallocz_array(cb->nentries, sizeof(float));
178 if (!cb->dimensions || !cb->pow2)
179 return AVERROR(ENOMEM);
180 for (i = 0; i < cb->nentries; i++) {
184 for (j = 0; j < cb->ndimensions; j++) {
187 off = (i / div) % vals; // lookup type 1
189 off = i * cb->ndimensions + j; // lookup type 2
191 cb->dimensions[i * cb->ndimensions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
193 last = cb->dimensions[i * cb->ndimensions + j];
194 cb->pow2[i] += cb->dimensions[i * cb->ndimensions + j] * cb->dimensions[i * cb->ndimensions + j];
203 static int ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
206 av_assert0(rc->type == 2);
207 rc->maxes = av_mallocz_array(rc->classifications, sizeof(float[2]));
209 return AVERROR(ENOMEM);
210 for (i = 0; i < rc->classifications; i++) {
212 vorbis_enc_codebook * cb;
213 for (j = 0; j < 8; j++)
214 if (rc->books[i][j] != -1)
218 cb = &venc->codebooks[rc->books[i][j]];
219 assert(cb->ndimensions >= 2);
222 for (j = 0; j < cb->nentries; j++) {
226 a = fabs(cb->dimensions[j * cb->ndimensions]);
227 if (a > rc->maxes[i][0])
229 a = fabs(cb->dimensions[j * cb->ndimensions + 1]);
230 if (a > rc->maxes[i][1])
235 for (i = 0; i < rc->classifications; i++) {
236 rc->maxes[i][0] += 0.8;
237 rc->maxes[i][1] += 0.8;
242 static av_cold int dsp_init(AVCodecContext *avctx, vorbis_enc_context *venc)
246 venc->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
248 return AVERROR(ENOMEM);
251 venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
252 venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
254 if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0)
256 if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0)
262 static int create_vorbis_context(vorbis_enc_context *venc,
263 AVCodecContext *avctx)
265 vorbis_enc_floor *fc;
266 vorbis_enc_residue *rc;
267 vorbis_enc_mapping *mc;
270 venc->channels = avctx->channels;
271 venc->sample_rate = avctx->sample_rate;
272 venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
274 venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
275 venc->codebooks = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
276 if (!venc->codebooks)
277 return AVERROR(ENOMEM);
279 // codebook 0..14 - floor1 book, values 0..255
280 // codebook 15 residue masterbook
281 // codebook 16..29 residue
282 for (book = 0; book < venc->ncodebooks; book++) {
283 vorbis_enc_codebook *cb = &venc->codebooks[book];
285 cb->ndimensions = cvectors[book].dim;
286 cb->nentries = cvectors[book].real_len;
287 cb->min = cvectors[book].min;
288 cb->delta = cvectors[book].delta;
289 cb->lookup = cvectors[book].lookup;
292 cb->lens = av_malloc_array(cb->nentries, sizeof(uint8_t));
293 cb->codewords = av_malloc_array(cb->nentries, sizeof(uint32_t));
294 if (!cb->lens || !cb->codewords)
295 return AVERROR(ENOMEM);
296 memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
297 memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
300 vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
301 cb->quantlist = av_malloc_array(vals, sizeof(int));
303 return AVERROR(ENOMEM);
304 for (i = 0; i < vals; i++)
305 cb->quantlist[i] = cvectors[book].quant[i];
307 cb->quantlist = NULL;
309 if ((ret = ready_codebook(cb)) < 0)
314 venc->floors = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
316 return AVERROR(ENOMEM);
319 fc = &venc->floors[0];
320 fc->partitions = NUM_FLOOR_PARTITIONS;
321 fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
322 if (!fc->partition_to_class)
323 return AVERROR(ENOMEM);
325 for (i = 0; i < fc->partitions; i++) {
326 static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};
327 fc->partition_to_class[i] = a[i];
328 fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
331 fc->classes = av_malloc_array(fc->nclasses, sizeof(vorbis_enc_floor_class));
333 return AVERROR(ENOMEM);
334 for (i = 0; i < fc->nclasses; i++) {
335 vorbis_enc_floor_class * c = &fc->classes[i];
337 c->dim = floor_classes[i].dim;
338 c->subclass = floor_classes[i].subclass;
339 c->masterbook = floor_classes[i].masterbook;
340 books = (1 << c->subclass);
341 c->books = av_malloc_array(books, sizeof(int));
343 return AVERROR(ENOMEM);
344 for (j = 0; j < books; j++)
345 c->books[j] = floor_classes[i].nbooks[j];
348 fc->rangebits = venc->log2_blocksize[0] - 1;
351 for (i = 0; i < fc->partitions; i++)
352 fc->values += fc->classes[fc->partition_to_class[i]].dim;
354 fc->list = av_malloc_array(fc->values, sizeof(vorbis_floor1_entry));
356 return AVERROR(ENOMEM);
358 fc->list[1].x = 1 << fc->rangebits;
359 for (i = 2; i < fc->values; i++) {
360 static const int a[] = {
361 93, 23,372, 6, 46,186,750, 14, 33, 65,
362 130,260,556, 3, 10, 18, 28, 39, 55, 79,
363 111,158,220,312,464,650,850
365 fc->list[i].x = a[i - 2];
367 if (ff_vorbis_ready_floor1_list(avctx, fc->list, fc->values))
371 venc->residues = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
373 return AVERROR(ENOMEM);
376 rc = &venc->residues[0];
380 rc->partition_size = 32;
381 rc->classifications = 10;
383 rc->books = av_malloc(sizeof(*rc->books) * rc->classifications);
385 return AVERROR(ENOMEM);
387 static const int8_t a[10][8] = {
388 { -1, -1, -1, -1, -1, -1, -1, -1, },
389 { -1, -1, 16, -1, -1, -1, -1, -1, },
390 { -1, -1, 17, -1, -1, -1, -1, -1, },
391 { -1, -1, 18, -1, -1, -1, -1, -1, },
392 { -1, -1, 19, -1, -1, -1, -1, -1, },
393 { -1, -1, 20, -1, -1, -1, -1, -1, },
394 { -1, -1, 21, -1, -1, -1, -1, -1, },
395 { 22, 23, -1, -1, -1, -1, -1, -1, },
396 { 24, 25, -1, -1, -1, -1, -1, -1, },
397 { 26, 27, 28, -1, -1, -1, -1, -1, },
399 memcpy(rc->books, a, sizeof a);
401 if ((ret = ready_residue(rc, venc)) < 0)
405 venc->mappings = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
407 return AVERROR(ENOMEM);
410 mc = &venc->mappings[0];
412 mc->mux = av_malloc(sizeof(int) * venc->channels);
414 return AVERROR(ENOMEM);
415 for (i = 0; i < venc->channels; i++)
417 mc->floor = av_malloc(sizeof(int) * mc->submaps);
418 mc->residue = av_malloc(sizeof(int) * mc->submaps);
419 if (!mc->floor || !mc->residue)
420 return AVERROR(ENOMEM);
421 for (i = 0; i < mc->submaps; i++) {
425 mc->coupling_steps = venc->channels == 2 ? 1 : 0;
426 mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
427 mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
428 if (!mc->magnitude || !mc->angle)
429 return AVERROR(ENOMEM);
430 if (mc->coupling_steps) {
431 mc->magnitude[0] = 0;
436 venc->modes = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
438 return AVERROR(ENOMEM);
441 venc->modes[0].blockflag = 0;
442 venc->modes[0].mapping = 0;
444 venc->have_saved = 0;
445 venc->saved = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
446 venc->samples = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]));
447 venc->floor = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
448 venc->coeffs = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
449 if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs)
450 return AVERROR(ENOMEM);
452 if ((ret = dsp_init(avctx, venc)) < 0)
458 static void put_float(PutBitContext *pb, float f)
462 mant = (int)ldexp(frexp(f, &exp), 20);
468 res |= mant | (exp << 21);
472 static void put_codebook_header(PutBitContext *pb, vorbis_enc_codebook *cb)
477 put_bits(pb, 24, 0x564342); //magic
478 put_bits(pb, 16, cb->ndimensions);
479 put_bits(pb, 24, cb->nentries);
481 for (i = 1; i < cb->nentries; i++)
482 if (cb->lens[i] < cb->lens[i-1])
484 if (i == cb->nentries)
487 put_bits(pb, 1, ordered);
489 int len = cb->lens[0];
490 put_bits(pb, 5, len - 1);
492 while (i < cb->nentries) {
494 for (j = 0; j+i < cb->nentries; j++)
495 if (cb->lens[j+i] != len)
497 put_bits(pb, ilog(cb->nentries - i), j);
503 for (i = 0; i < cb->nentries; i++)
506 if (i != cb->nentries)
508 put_bits(pb, 1, sparse);
510 for (i = 0; i < cb->nentries; i++) {
512 put_bits(pb, 1, !!cb->lens[i]);
514 put_bits(pb, 5, cb->lens[i] - 1);
518 put_bits(pb, 4, cb->lookup);
520 int tmp = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
521 int bits = ilog(cb->quantlist[0]);
523 for (i = 1; i < tmp; i++)
524 bits = FFMAX(bits, ilog(cb->quantlist[i]));
526 put_float(pb, cb->min);
527 put_float(pb, cb->delta);
529 put_bits(pb, 4, bits - 1);
530 put_bits(pb, 1, cb->seq_p);
532 for (i = 0; i < tmp; i++)
533 put_bits(pb, bits, cb->quantlist[i]);
537 static void put_floor_header(PutBitContext *pb, vorbis_enc_floor *fc)
541 put_bits(pb, 16, 1); // type, only floor1 is supported
543 put_bits(pb, 5, fc->partitions);
545 for (i = 0; i < fc->partitions; i++)
546 put_bits(pb, 4, fc->partition_to_class[i]);
548 for (i = 0; i < fc->nclasses; i++) {
551 put_bits(pb, 3, fc->classes[i].dim - 1);
552 put_bits(pb, 2, fc->classes[i].subclass);
554 if (fc->classes[i].subclass)
555 put_bits(pb, 8, fc->classes[i].masterbook);
557 books = (1 << fc->classes[i].subclass);
559 for (j = 0; j < books; j++)
560 put_bits(pb, 8, fc->classes[i].books[j] + 1);
563 put_bits(pb, 2, fc->multiplier - 1);
564 put_bits(pb, 4, fc->rangebits);
566 for (i = 2; i < fc->values; i++)
567 put_bits(pb, fc->rangebits, fc->list[i].x);
570 static void put_residue_header(PutBitContext *pb, vorbis_enc_residue *rc)
574 put_bits(pb, 16, rc->type);
576 put_bits(pb, 24, rc->begin);
577 put_bits(pb, 24, rc->end);
578 put_bits(pb, 24, rc->partition_size - 1);
579 put_bits(pb, 6, rc->classifications - 1);
580 put_bits(pb, 8, rc->classbook);
582 for (i = 0; i < rc->classifications; i++) {
584 for (j = 0; j < 8; j++)
585 tmp |= (rc->books[i][j] != -1) << j;
587 put_bits(pb, 3, tmp & 7);
588 put_bits(pb, 1, tmp > 7);
591 put_bits(pb, 5, tmp >> 3);
594 for (i = 0; i < rc->classifications; i++) {
596 for (j = 0; j < 8; j++)
597 if (rc->books[i][j] != -1)
598 put_bits(pb, 8, rc->books[i][j]);
602 static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
607 int buffer_len = 50000;
608 uint8_t *buffer = av_mallocz(buffer_len), *p = buffer;
610 return AVERROR(ENOMEM);
612 // identification header
613 init_put_bits(&pb, p, buffer_len);
614 put_bits(&pb, 8, 1); //magic
615 for (i = 0; "vorbis"[i]; i++)
616 put_bits(&pb, 8, "vorbis"[i]);
617 put_bits32(&pb, 0); // version
618 put_bits(&pb, 8, venc->channels);
619 put_bits32(&pb, venc->sample_rate);
620 put_bits32(&pb, 0); // bitrate
621 put_bits32(&pb, 0); // bitrate
622 put_bits32(&pb, 0); // bitrate
623 put_bits(&pb, 4, venc->log2_blocksize[0]);
624 put_bits(&pb, 4, venc->log2_blocksize[1]);
625 put_bits(&pb, 1, 1); // framing
628 hlens[0] = put_bits_count(&pb) >> 3;
629 buffer_len -= hlens[0];
633 init_put_bits(&pb, p, buffer_len);
634 put_bits(&pb, 8, 3); //magic
635 for (i = 0; "vorbis"[i]; i++)
636 put_bits(&pb, 8, "vorbis"[i]);
637 put_bits32(&pb, 0); // vendor length TODO
638 put_bits32(&pb, 0); // amount of comments
639 put_bits(&pb, 1, 1); // framing
642 hlens[1] = put_bits_count(&pb) >> 3;
643 buffer_len -= hlens[1];
647 init_put_bits(&pb, p, buffer_len);
648 put_bits(&pb, 8, 5); //magic
649 for (i = 0; "vorbis"[i]; i++)
650 put_bits(&pb, 8, "vorbis"[i]);
653 put_bits(&pb, 8, venc->ncodebooks - 1);
654 for (i = 0; i < venc->ncodebooks; i++)
655 put_codebook_header(&pb, &venc->codebooks[i]);
657 // time domain, reserved, zero
659 put_bits(&pb, 16, 0);
662 put_bits(&pb, 6, venc->nfloors - 1);
663 for (i = 0; i < venc->nfloors; i++)
664 put_floor_header(&pb, &venc->floors[i]);
667 put_bits(&pb, 6, venc->nresidues - 1);
668 for (i = 0; i < venc->nresidues; i++)
669 put_residue_header(&pb, &venc->residues[i]);
672 put_bits(&pb, 6, venc->nmappings - 1);
673 for (i = 0; i < venc->nmappings; i++) {
674 vorbis_enc_mapping *mc = &venc->mappings[i];
676 put_bits(&pb, 16, 0); // mapping type
678 put_bits(&pb, 1, mc->submaps > 1);
680 put_bits(&pb, 4, mc->submaps - 1);
682 put_bits(&pb, 1, !!mc->coupling_steps);
683 if (mc->coupling_steps) {
684 put_bits(&pb, 8, mc->coupling_steps - 1);
685 for (j = 0; j < mc->coupling_steps; j++) {
686 put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
687 put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
691 put_bits(&pb, 2, 0); // reserved
694 for (j = 0; j < venc->channels; j++)
695 put_bits(&pb, 4, mc->mux[j]);
697 for (j = 0; j < mc->submaps; j++) {
698 put_bits(&pb, 8, 0); // reserved time configuration
699 put_bits(&pb, 8, mc->floor[j]);
700 put_bits(&pb, 8, mc->residue[j]);
705 put_bits(&pb, 6, venc->nmodes - 1);
706 for (i = 0; i < venc->nmodes; i++) {
707 put_bits(&pb, 1, venc->modes[i].blockflag);
708 put_bits(&pb, 16, 0); // reserved window type
709 put_bits(&pb, 16, 0); // reserved transform type
710 put_bits(&pb, 8, venc->modes[i].mapping);
713 put_bits(&pb, 1, 1); // framing
716 hlens[2] = put_bits_count(&pb) >> 3;
718 len = hlens[0] + hlens[1] + hlens[2];
719 p = *out = av_mallocz(64 + len + len/255);
721 return AVERROR(ENOMEM);
724 p += av_xiphlacing(p, hlens[0]);
725 p += av_xiphlacing(p, hlens[1]);
727 for (i = 0; i < 3; i++) {
728 memcpy(p, buffer + buffer_len, hlens[i]);
730 buffer_len += hlens[i];
737 static float get_floor_average(vorbis_enc_floor * fc, float *coeffs, int i)
739 int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
740 int end = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
744 for (j = begin; j < end; j++)
745 average += fabs(coeffs[j]);
746 return average / (end - begin);
749 static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
750 float *coeffs, uint16_t *posts, int samples)
752 int range = 255 / fc->multiplier + 1;
754 float tot_average = 0.0;
755 float averages[MAX_FLOOR_VALUES];
756 for (i = 0; i < fc->values; i++) {
757 averages[i] = get_floor_average(fc, coeffs, i);
758 tot_average += averages[i];
760 tot_average /= fc->values;
761 tot_average /= venc->quality;
763 for (i = 0; i < fc->values; i++) {
764 int position = fc->list[fc->list[i].sort].x;
765 float average = averages[i];
768 average = sqrt(tot_average * average) * pow(1.25f, position*0.005f); // MAGIC!
769 for (j = 0; j < range - 1; j++)
770 if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
772 posts[fc->list[i].sort] = j;
776 static int render_point(int x0, int y0, int x1, int y1, int x)
778 return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
781 static int floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
782 PutBitContext *pb, uint16_t *posts,
783 float *floor, int samples)
785 int range = 255 / fc->multiplier + 1;
786 int coded[MAX_FLOOR_VALUES]; // first 2 values are unused
789 if (pb->size_in_bits - put_bits_count(pb) < 1 + 2 * ilog(range - 1))
790 return AVERROR(EINVAL);
791 put_bits(pb, 1, 1); // non zero
792 put_bits(pb, ilog(range - 1), posts[0]);
793 put_bits(pb, ilog(range - 1), posts[1]);
794 coded[0] = coded[1] = 1;
796 for (i = 2; i < fc->values; i++) {
797 int predicted = render_point(fc->list[fc->list[i].low].x,
798 posts[fc->list[i].low],
799 fc->list[fc->list[i].high].x,
800 posts[fc->list[i].high],
802 int highroom = range - predicted;
803 int lowroom = predicted;
804 int room = FFMIN(highroom, lowroom);
805 if (predicted == posts[i]) {
806 coded[i] = 0; // must be used later as flag!
809 if (!coded[fc->list[i].low ])
810 coded[fc->list[i].low ] = -1;
811 if (!coded[fc->list[i].high])
812 coded[fc->list[i].high] = -1;
814 if (posts[i] > predicted) {
815 if (posts[i] - predicted > room)
816 coded[i] = posts[i] - predicted + lowroom;
818 coded[i] = (posts[i] - predicted) << 1;
820 if (predicted - posts[i] > room)
821 coded[i] = predicted - posts[i] + highroom - 1;
823 coded[i] = ((predicted - posts[i]) << 1) - 1;
828 for (i = 0; i < fc->partitions; i++) {
829 vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
830 int k, cval = 0, csub = 1<<c->subclass;
832 vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
834 for (k = 0; k < c->dim; k++) {
836 for (l = 0; l < csub; l++) {
838 if (c->books[l] != -1)
839 maxval = venc->codebooks[c->books[l]].nentries;
840 // coded could be -1, but this still works, cause that is 0
841 if (coded[counter + k] < maxval)
846 cshift += c->subclass;
848 if (put_codeword(pb, book, cval))
849 return AVERROR(EINVAL);
851 for (k = 0; k < c->dim; k++) {
852 int book = c->books[cval & (csub-1)];
853 int entry = coded[counter++];
854 cval >>= c->subclass;
859 if (put_codeword(pb, &venc->codebooks[book], entry))
860 return AVERROR(EINVAL);
864 ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,
865 fc->multiplier, floor, samples);
870 static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
874 float distance = FLT_MAX;
875 assert(book->dimensions);
876 for (i = 0; i < book->nentries; i++) {
877 float * vec = book->dimensions + i * book->ndimensions, d = book->pow2[i];
881 for (j = 0; j < book->ndimensions; j++)
882 d -= vec[j] * num[j];
888 if (put_codeword(pb, book, entry))
890 return &book->dimensions[entry * book->ndimensions];
893 static int residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
894 PutBitContext *pb, float *coeffs, int samples,
897 int pass, i, j, p, k;
898 int psize = rc->partition_size;
899 int partitions = (rc->end - rc->begin) / psize;
900 int channels = (rc->type == 2) ? 1 : real_ch;
901 int classes[MAX_CHANNELS][NUM_RESIDUE_PARTITIONS];
902 int classwords = venc->codebooks[rc->classbook].ndimensions;
904 av_assert0(rc->type == 2);
905 av_assert0(real_ch == 2);
906 for (p = 0; p < partitions; p++) {
907 float max1 = 0.0, max2 = 0.0;
908 int s = rc->begin + p * psize;
909 for (k = s; k < s + psize; k += 2) {
910 max1 = FFMAX(max1, fabs(coeffs[ k / real_ch]));
911 max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
914 for (i = 0; i < rc->classifications - 1; i++)
915 if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1])
920 for (pass = 0; pass < 8; pass++) {
922 while (p < partitions) {
924 for (j = 0; j < channels; j++) {
925 vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
927 for (i = 0; i < classwords; i++) {
928 entry *= rc->classifications;
929 entry += classes[j][p + i];
931 if (put_codeword(pb, book, entry))
932 return AVERROR(EINVAL);
934 for (i = 0; i < classwords && p < partitions; i++, p++) {
935 for (j = 0; j < channels; j++) {
936 int nbook = rc->books[classes[j][p]][pass];
937 vorbis_enc_codebook * book = &venc->codebooks[nbook];
938 float *buf = coeffs + samples*j + rc->begin + p*psize;
942 assert(rc->type == 0 || rc->type == 2);
943 assert(!(psize % book->ndimensions));
946 for (k = 0; k < psize; k += book->ndimensions) {
948 float *a = put_vector(book, pb, &buf[k]);
950 return AVERROR(EINVAL);
951 for (l = 0; l < book->ndimensions; l++)
955 int s = rc->begin + p * psize, a1, b1;
956 a1 = (s % real_ch) * samples;
958 s = real_ch * samples;
959 for (k = 0; k < psize; k += book->ndimensions) {
960 int dim, a2 = a1, b2 = b1;
961 float vec[MAX_CODEBOOK_DIM], *pv = vec;
962 for (dim = book->ndimensions; dim--; ) {
963 *pv++ = coeffs[a2 + b2];
964 if ((a2 += samples) == s) {
969 pv = put_vector(book, pb, vec);
971 return AVERROR(EINVAL);
972 for (dim = book->ndimensions; dim--; ) {
973 coeffs[a1 + b1] -= *pv++;
974 if ((a1 += samples) == s) {
988 static int apply_window_and_mdct(vorbis_enc_context *venc,
989 float **audio, int samples)
992 const float * win = venc->win[0];
993 int window_len = 1 << (venc->log2_blocksize[0] - 1);
994 float n = (float)(1 << venc->log2_blocksize[0]) / 4.0;
997 if (!venc->have_saved && !samples)
1000 if (venc->have_saved) {
1001 for (channel = 0; channel < venc->channels; channel++)
1002 memcpy(venc->samples + channel * window_len * 2,
1003 venc->saved + channel * window_len, sizeof(float) * window_len);
1005 for (channel = 0; channel < venc->channels; channel++)
1006 memset(venc->samples + channel * window_len * 2, 0,
1007 sizeof(float) * window_len);
1011 for (channel = 0; channel < venc->channels; channel++) {
1012 float * offset = venc->samples + channel*window_len*2 + window_len;
1013 for (i = 0; i < samples; i++)
1014 offset[i] = audio[channel][i] / n * win[window_len - i - 1];
1017 for (channel = 0; channel < venc->channels; channel++)
1018 memset(venc->samples + channel * window_len * 2 + window_len,
1019 0, sizeof(float) * window_len);
1022 for (channel = 0; channel < venc->channels; channel++)
1023 venc->mdct[0].mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,
1024 venc->samples + channel * window_len * 2);
1027 for (channel = 0; channel < venc->channels; channel++) {
1028 float *offset = venc->saved + channel * window_len;
1029 for (i = 0; i < samples; i++)
1030 offset[i] = audio[channel][i] / n * win[i];
1032 venc->have_saved = 1;
1034 venc->have_saved = 0;
1039 static int vorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1040 const AVFrame *frame, int *got_packet_ptr)
1042 vorbis_enc_context *venc = avctx->priv_data;
1043 float **audio = frame ? (float **)frame->extended_data : NULL;
1044 int samples = frame ? frame->nb_samples : 0;
1045 vorbis_enc_mode *mode;
1046 vorbis_enc_mapping *mapping;
1050 if (!apply_window_and_mdct(venc, audio, samples))
1052 samples = 1 << (venc->log2_blocksize[0] - 1);
1054 if ((ret = ff_alloc_packet2(avctx, avpkt, 8192, 0)) < 0)
1057 init_put_bits(&pb, avpkt->data, avpkt->size);
1059 if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {
1060 av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1061 return AVERROR(EINVAL);
1064 put_bits(&pb, 1, 0); // magic bit
1066 put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
1068 mode = &venc->modes[0];
1069 mapping = &venc->mappings[mode->mapping];
1070 if (mode->blockflag) {
1071 put_bits(&pb, 1, 0);
1072 put_bits(&pb, 1, 0);
1075 for (i = 0; i < venc->channels; i++) {
1076 vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
1077 uint16_t posts[MAX_FLOOR_VALUES];
1078 floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
1079 if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples)) {
1080 av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1081 return AVERROR(EINVAL);
1085 for (i = 0; i < venc->channels * samples; i++)
1086 venc->coeffs[i] /= venc->floor[i];
1088 for (i = 0; i < mapping->coupling_steps; i++) {
1089 float *mag = venc->coeffs + mapping->magnitude[i] * samples;
1090 float *ang = venc->coeffs + mapping->angle[i] * samples;
1092 for (j = 0; j < samples; j++) {
1102 if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],
1103 &pb, venc->coeffs, samples, venc->channels)) {
1104 av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1105 return AVERROR(EINVAL);
1108 flush_put_bits(&pb);
1109 avpkt->size = put_bits_count(&pb) >> 3;
1111 avpkt->duration = ff_samples_to_time_base(avctx, avctx->frame_size);
1113 if (frame->pts != AV_NOPTS_VALUE)
1114 avpkt->pts = ff_samples_to_time_base(avctx, frame->pts);
1116 avpkt->pts = venc->next_pts;
1118 if (avpkt->pts != AV_NOPTS_VALUE)
1119 venc->next_pts = avpkt->pts + avpkt->duration;
1121 *got_packet_ptr = 1;
1126 static av_cold int vorbis_encode_close(AVCodecContext *avctx)
1128 vorbis_enc_context *venc = avctx->priv_data;
1131 if (venc->codebooks)
1132 for (i = 0; i < venc->ncodebooks; i++) {
1133 av_freep(&venc->codebooks[i].lens);
1134 av_freep(&venc->codebooks[i].codewords);
1135 av_freep(&venc->codebooks[i].quantlist);
1136 av_freep(&venc->codebooks[i].dimensions);
1137 av_freep(&venc->codebooks[i].pow2);
1139 av_freep(&venc->codebooks);
1142 for (i = 0; i < venc->nfloors; i++) {
1144 if (venc->floors[i].classes)
1145 for (j = 0; j < venc->floors[i].nclasses; j++)
1146 av_freep(&venc->floors[i].classes[j].books);
1147 av_freep(&venc->floors[i].classes);
1148 av_freep(&venc->floors[i].partition_to_class);
1149 av_freep(&venc->floors[i].list);
1151 av_freep(&venc->floors);
1154 for (i = 0; i < venc->nresidues; i++) {
1155 av_freep(&venc->residues[i].books);
1156 av_freep(&venc->residues[i].maxes);
1158 av_freep(&venc->residues);
1161 for (i = 0; i < venc->nmappings; i++) {
1162 av_freep(&venc->mappings[i].mux);
1163 av_freep(&venc->mappings[i].floor);
1164 av_freep(&venc->mappings[i].residue);
1165 av_freep(&venc->mappings[i].magnitude);
1166 av_freep(&venc->mappings[i].angle);
1168 av_freep(&venc->mappings);
1170 av_freep(&venc->modes);
1172 av_freep(&venc->saved);
1173 av_freep(&venc->samples);
1174 av_freep(&venc->floor);
1175 av_freep(&venc->coeffs);
1176 av_freep(&venc->fdsp);
1178 ff_mdct_end(&venc->mdct[0]);
1179 ff_mdct_end(&venc->mdct[1]);
1181 av_freep(&avctx->extradata);
1186 static av_cold int vorbis_encode_init(AVCodecContext *avctx)
1188 vorbis_enc_context *venc = avctx->priv_data;
1191 if (avctx->channels != 2) {
1192 av_log(avctx, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
1196 if ((ret = create_vorbis_context(venc, avctx)) < 0)
1199 avctx->bit_rate = 0;
1200 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1201 venc->quality = avctx->global_quality / (float)FF_QP2LAMBDA;
1204 venc->quality *= venc->quality;
1206 if ((ret = put_main_header(venc, (uint8_t**)&avctx->extradata)) < 0)
1208 avctx->extradata_size = ret;
1210 avctx->frame_size = 1 << (venc->log2_blocksize[0] - 1);
1214 vorbis_encode_close(avctx);
1218 AVCodec ff_vorbis_encoder = {
1220 .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
1221 .type = AVMEDIA_TYPE_AUDIO,
1222 .id = AV_CODEC_ID_VORBIS,
1223 .priv_data_size = sizeof(vorbis_enc_context),
1224 .init = vorbis_encode_init,
1225 .encode2 = vorbis_encode_frame,
1226 .close = vorbis_encode_close,
1227 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_EXPERIMENTAL,
1228 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
1229 AV_SAMPLE_FMT_NONE },