opus_multistream_encoder.c 38.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* Copyright (c) 2011 Xiph.Org Foundation
   Written by Jean-Marc Valin */
/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "opus_multistream.h"
#include "opus.h"
#include "opus_private.h"
#include "stack_alloc.h"
#include <stdarg.h>
#include "float_cast.h"
#include "os_support.h"
39
#include "mathops.h"
Jean-Marc Valin's avatar
Jean-Marc Valin committed
40 41 42 43
#include "mdct.h"
#include "modes.h"
#include "bands.h"
#include "quant_bands.h"
44
#include "pitch.h"
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
typedef struct {
   int nb_streams;
   int nb_coupled_streams;
   unsigned char mapping[8];
} VorbisLayout;

/* Index is nb_channel-1*/
static const VorbisLayout vorbis_mappings[8] = {
      {1, 0, {0}},                      /* 1: mono */
      {1, 1, {0, 1}},                   /* 2: stereo */
      {2, 1, {0, 2, 1}},                /* 3: 1-d surround */
      {2, 2, {0, 1, 2, 3}},             /* 4: quadraphonic surround */
      {3, 2, {0, 4, 1, 2, 3}},          /* 5: 5-channel surround */
      {4, 2, {0, 4, 1, 2, 3, 5}},       /* 6: 5.1 surround */
      {4, 3, {0, 4, 1, 2, 3, 5, 6}},    /* 7: 6.1 surround */
      {5, 3, {0, 6, 1, 2, 3, 4, 5, 7}}, /* 8: 7.1 surround */
};

Jean-Marc Valin's avatar
Jean-Marc Valin committed
64 65 66 67 68 69 70 71 72
typedef void (*opus_copy_channel_in_func)(
  opus_val16 *dst,
  int dst_stride,
  const void *src,
  int src_stride,
  int src_channel,
  int frame_size
);

73 74
typedef enum {
  MAPPING_TYPE_NONE,
75
  MAPPING_TYPE_SURROUND
76
#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
77 78
  ,  /* Do not include comma at end of enumerator list */
  MAPPING_TYPE_AMBISONICS
79 80 81
#endif
} MappingType;

82 83
struct OpusMSEncoder {
   ChannelLayout layout;
84
   int arch;
85
   int lfe_stream;
86
   int application;
87
   int variable_duration;
88
   MappingType mapping_type;
89
   opus_int32 bitrate_bps;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
90
   float subframe_mem[3];
91
   /* Encoder states go here */
Jean-Marc Valin's avatar
Jean-Marc Valin committed
92 93
   /* then opus_val32 window_mem[channels*120]; */
   /* then opus_val32 preemph_mem[channels]; */
94 95
};

Jean-Marc Valin's avatar
Jean-Marc Valin committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
static opus_val32 *ms_get_preemph_mem(OpusMSEncoder *st)
{
   int s;
   char *ptr;
   int coupled_size, mono_size;

   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   for (s=0;s<st->layout.nb_streams;s++)
   {
      if (s < st->layout.nb_coupled_streams)
         ptr += align(coupled_size);
      else
         ptr += align(mono_size);
   }
112 113
   /* void* cast avoids clang -Wcast-align warning */
   return (opus_val32*)(void*)(ptr+st->layout.nb_channels*120*sizeof(opus_val32));
Jean-Marc Valin's avatar
Jean-Marc Valin committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
}

static opus_val32 *ms_get_window_mem(OpusMSEncoder *st)
{
   int s;
   char *ptr;
   int coupled_size, mono_size;

   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   for (s=0;s<st->layout.nb_streams;s++)
   {
      if (s < st->layout.nb_coupled_streams)
         ptr += align(coupled_size);
      else
         ptr += align(mono_size);
   }
132 133
   /* void* cast avoids clang -Wcast-align warning */
   return (opus_val32*)(void*)ptr;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
134
}
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

static int validate_encoder_layout(const ChannelLayout *layout)
{
   int s;
   for (s=0;s<layout->nb_streams;s++)
   {
      if (s < layout->nb_coupled_streams)
      {
         if (get_left_channel(layout, s, -1)==-1)
            return 0;
         if (get_right_channel(layout, s, -1)==-1)
            return 0;
      } else {
         if (get_mono_channel(layout, s, -1)==-1)
            return 0;
      }
   }
   return 1;
}

Jean-Marc Valin's avatar
Jean-Marc Valin committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
static void channel_pos(int channels, int pos[8])
{
   /* Position in the mix: 0 don't mix, 1: left, 2: center, 3:right */
   if (channels==4)
   {
      pos[0]=1;
      pos[1]=3;
      pos[2]=1;
      pos[3]=3;
   } else if (channels==3||channels==5||channels==6)
   {
      pos[0]=1;
      pos[1]=2;
      pos[2]=3;
      pos[3]=1;
      pos[4]=3;
      pos[5]=0;
   } else if (channels==7)
   {
      pos[0]=1;
      pos[1]=2;
      pos[2]=3;
      pos[3]=1;
      pos[4]=3;
      pos[5]=2;
      pos[6]=0;
   } else if (channels==8)
   {
      pos[0]=1;
      pos[1]=2;
      pos[2]=3;
      pos[3]=1;
      pos[4]=3;
      pos[5]=1;
      pos[6]=3;
      pos[7]=0;
   }
}

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#if 1
/* Computes a rough approximation of log2(2^a + 2^b) */
static opus_val16 logSum(opus_val16 a, opus_val16 b)
{
   opus_val16 max;
   opus_val32 diff;
   opus_val16 frac;
   static const opus_val16 diff_table[17] = {
         QCONST16(0.5000000f, DB_SHIFT), QCONST16(0.2924813f, DB_SHIFT), QCONST16(0.1609640f, DB_SHIFT), QCONST16(0.0849625f, DB_SHIFT),
         QCONST16(0.0437314f, DB_SHIFT), QCONST16(0.0221971f, DB_SHIFT), QCONST16(0.0111839f, DB_SHIFT), QCONST16(0.0056136f, DB_SHIFT),
         QCONST16(0.0028123f, DB_SHIFT)
   };
   int low;
   if (a>b)
   {
      max = a;
      diff = SUB32(EXTEND32(a),EXTEND32(b));
   } else {
      max = b;
      diff = SUB32(EXTEND32(b),EXTEND32(a));
   }
215
   if (!(diff < QCONST16(8.f, DB_SHIFT)))  /* inverted to catch NaNs */
216 217 218 219 220
      return max;
#ifdef FIXED_POINT
   low = SHR32(diff, DB_SHIFT-1);
   frac = SHL16(diff - SHL16(low, DB_SHIFT-1), 16-DB_SHIFT);
#else
221
   low = (int)floor(2*diff);
222 223 224 225 226 227 228 229 230 231 232
   frac = 2*diff - low;
#endif
   return max + diff_table[low] + MULT16_16_Q15(frac, SUB16(diff_table[low+1], diff_table[low]));
}
#else
opus_val16 logSum(opus_val16 a, opus_val16 b)
{
   return log2(pow(4, a)+ pow(4, b))/2;
}
#endif

Jean-Marc Valin's avatar
Jean-Marc Valin committed
233
void surround_analysis(const CELTMode *celt_mode, const void *pcm, opus_val16 *bandLogE, opus_val32 *mem, opus_val32 *preemph_mem,
234
      int len, int overlap, int channels, int rate, opus_copy_channel_in_func copy_channel_in, int arch
Jean-Marc Valin's avatar
Jean-Marc Valin committed
235 236 237 238
)
{
   int c;
   int i;
239
   int LM;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
240 241
   int pos[8] = {0};
   int upsample;
242
   int frame_size;
243
   int freq_size;
244
   opus_val16 channel_offset;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
245 246 247 248
   opus_val32 bandE[21];
   opus_val16 maskLogE[3][21];
   VARDECL(opus_val32, in);
   VARDECL(opus_val16, x);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
249
   VARDECL(opus_val32, freq);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
250
   SAVE_STACK;
251 252 253

   upsample = resampling_factor(rate);
   frame_size = len*upsample;
254
   freq_size = IMIN(960, frame_size);
255

256
   /* LM = log2(frame_size / 120) */
257
   for (LM=0;LM<celt_mode->maxLM;LM++)
258 259 260
      if (celt_mode->shortMdctSize<<LM==frame_size)
         break;

261
   ALLOC(in, frame_size+overlap, opus_val32);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
262
   ALLOC(x, len, opus_val16);
263
   ALLOC(freq, freq_size, opus_val32);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
264 265 266

   channel_pos(channels, pos);

267
   for (c=0;c<3;c++)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
268
      for (i=0;i<21;i++)
269
         maskLogE[c][i] = -QCONST16(28.f, DB_SHIFT);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
270 271 272

   for (c=0;c<channels;c++)
   {
273 274 275
      int frame;
      int nb_frames = frame_size/freq_size;
      celt_assert(nb_frames*freq_size == frame_size);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
276 277
      OPUS_COPY(in, mem+c*overlap, overlap);
      (*copy_channel_in)(x, 1, pcm, channels, c, len);
278
      celt_preemphasis(x, in+overlap, frame_size, 1, upsample, celt_mode->preemph, preemph_mem+c, 0);
279 280 281 282 283 284 285 286 287 288 289 290 291
#ifndef FIXED_POINT
      {
         opus_val32 sum;
         sum = celt_inner_prod(in, in, frame_size+overlap, 0);
         /* This should filter out both NaNs and ridiculous signals that could
            cause NaNs further down. */
         if (!(sum < 1e9f) || celt_isnan(sum))
         {
            OPUS_CLEAR(in, frame_size+overlap);
            preemph_mem[c] = 0;
         }
      }
#endif
292 293
      OPUS_CLEAR(bandE, 21);
      for (frame=0;frame<nb_frames;frame++)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
294
      {
295 296 297 298 299 300 301 302 303 304 305
         opus_val32 tmpE[21];
         clt_mdct_forward(&celt_mode->mdct, in+960*frame, freq, celt_mode->window,
               overlap, celt_mode->maxLM-LM, 1, arch);
         if (upsample != 1)
         {
            int bound = freq_size/upsample;
            for (i=0;i<bound;i++)
               freq[i] *= upsample;
            for (;i<freq_size;i++)
               freq[i] = 0;
         }
Jean-Marc Valin's avatar
Jean-Marc Valin committed
306

307 308 309 310 311
         compute_band_energies(celt_mode, freq, tmpE, 21, 1, LM);
         /* If we have multiple frames, take the max energy. */
         for (i=0;i<21;i++)
            bandE[i] = MAX32(bandE[i], tmpE[i]);
      }
312
      amp2Log2(celt_mode, 21, 21, bandE, bandLogE+21*c, 1);
313 314 315 316 317
      /* Apply spreading function with -6 dB/band going up and -12 dB/band going down. */
      for (i=1;i<21;i++)
         bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i-1]-QCONST16(1.f, DB_SHIFT));
      for (i=19;i>=0;i--)
         bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i+1]-QCONST16(2.f, DB_SHIFT));
Jean-Marc Valin's avatar
Jean-Marc Valin committed
318 319 320
      if (pos[c]==1)
      {
         for (i=0;i<21;i++)
321
            maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
322 323 324
      } else if (pos[c]==3)
      {
         for (i=0;i<21;i++)
325
            maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
326 327 328 329
      } else if (pos[c]==2)
      {
         for (i=0;i<21;i++)
         {
330 331
            maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT));
            maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT));
Jean-Marc Valin's avatar
Jean-Marc Valin committed
332 333 334 335 336 337 338 339 340 341
         }
      }
#if 0
      for (i=0;i<21;i++)
         printf("%f ", bandLogE[21*c+i]);
      float sum=0;
      for (i=0;i<21;i++)
         sum += bandLogE[21*c+i];
      printf("%f ", sum/21);
#endif
342
      OPUS_COPY(mem+c*overlap, in+frame_size, overlap);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
343 344
   }
   for (i=0;i<21;i++)
345
      maskLogE[1][i] = MIN32(maskLogE[0][i],maskLogE[2][i]);
346
   channel_offset = HALF16(celt_log2(QCONST32(2.f,14)/(channels-1)));
Jean-Marc Valin's avatar
Jean-Marc Valin committed
347 348
   for (c=0;c<3;c++)
      for (i=0;i<21;i++)
349
         maskLogE[c][i] += channel_offset;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
#if 0
   for (c=0;c<3;c++)
   {
      for (i=0;i<21;i++)
         printf("%f ", maskLogE[c][i]);
   }
#endif
   for (c=0;c<channels;c++)
   {
      opus_val16 *mask;
      if (pos[c]!=0)
      {
         mask = &maskLogE[pos[c]-1][0];
         for (i=0;i<21;i++)
            bandLogE[21*c+i] = bandLogE[21*c+i] - mask[i];
      } else {
         for (i=0;i<21;i++)
            bandLogE[21*c+i] = 0;
      }
#if 0
      for (i=0;i<21;i++)
         printf("%f ", bandLogE[21*c+i]);
      printf("\n");
#endif
#if 0
      float sum=0;
      for (i=0;i<21;i++)
         sum += bandLogE[21*c+i];
378
      printf("%f ", sum/(float)QCONST32(21.f, DB_SHIFT));
Jean-Marc Valin's avatar
Jean-Marc Valin committed
379 380 381 382 383
      printf("\n");
#endif
   }
   RESTORE_STACK;
}
384 385 386 387 388 389 390 391 392 393 394 395 396 397

opus_int32 opus_multistream_encoder_get_size(int nb_streams, int nb_coupled_streams)
{
   int coupled_size;
   int mono_size;

   if(nb_streams<1||nb_coupled_streams>nb_streams||nb_coupled_streams<0)return 0;
   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);
   return align(sizeof(OpusMSEncoder))
        + nb_coupled_streams * align(coupled_size)
        + (nb_streams-nb_coupled_streams) * align(mono_size);
}

398 399 400 401
opus_int32 opus_multistream_surround_encoder_get_size(int channels, int mapping_family)
{
   int nb_streams;
   int nb_coupled_streams;
402
   opus_int32 size;
403

404
   if (mapping_family==0)
405
   {
406 407 408 409 410 411 412 413 414 415 416
      if (channels==1)
      {
         nb_streams=1;
         nb_coupled_streams=0;
      } else if (channels==2)
      {
         nb_streams=1;
         nb_coupled_streams=1;
      } else
         return 0;
   } else if (mapping_family==1 && channels<=8 && channels>=1)
417
   {
418 419 420
      nb_streams=vorbis_mappings[channels-1].nb_streams;
      nb_coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams;
   } else if (mapping_family==255)
421
   {
422 423
      nb_streams=channels;
      nb_coupled_streams=0;
424 425 426 427 428 429
#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
   } else if (mapping_family==254)
   {
      nb_streams=channels;
      nb_coupled_streams=0;
#endif
430 431
   } else
      return 0;
432 433
   size = opus_multistream_encoder_get_size(nb_streams, nb_coupled_streams);
   if (channels>2)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
434 435 436
   {
      size += channels*(120*sizeof(opus_val32) + sizeof(opus_val32));
   }
437
   return size;
438
}
439

440
static int opus_multistream_encoder_init_impl(
441 442 443 444 445 446
      OpusMSEncoder *st,
      opus_int32 Fs,
      int channels,
      int streams,
      int coupled_streams,
      const unsigned char *mapping,
447
      int application,
448
      MappingType mapping_type
449 450 451 452 453 454 455 456
)
{
   int coupled_size;
   int mono_size;
   int i, ret;
   char *ptr;

   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
Mark Harris's avatar
Mark Harris committed
457
       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
458 459
      return OPUS_BAD_ARG;

460
   st->arch = opus_select_arch();
461 462 463
   st->layout.nb_channels = channels;
   st->layout.nb_streams = streams;
   st->layout.nb_coupled_streams = coupled_streams;
464
   st->subframe_mem[0]=st->subframe_mem[1]=st->subframe_mem[2]=0;
465
   if (mapping_type != MAPPING_TYPE_SURROUND)
466
      st->lfe_stream = -1;
467
   st->bitrate_bps = OPUS_AUTO;
468
   st->application = application;
469
   st->variable_duration = OPUS_FRAMESIZE_ARG;
470 471 472 473 474 475 476 477 478 479 480
   for (i=0;i<st->layout.nb_channels;i++)
      st->layout.mapping[i] = mapping[i];
   if (!validate_layout(&st->layout) || !validate_encoder_layout(&st->layout))
      return OPUS_BAD_ARG;
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);

   for (i=0;i<st->layout.nb_coupled_streams;i++)
   {
      ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 2, application);
481
      if(ret!=OPUS_OK)return ret;
482 483
      if (i==st->lfe_stream)
         opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1));
484 485 486 487 488
      ptr += align(coupled_size);
   }
   for (;i<st->layout.nb_streams;i++)
   {
      ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 1, application);
489 490
      if (i==st->lfe_stream)
         opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1));
491 492 493
      if(ret!=OPUS_OK)return ret;
      ptr += align(mono_size);
   }
494
   if (mapping_type == MAPPING_TYPE_SURROUND)
495
   {
Jean-Marc Valin's avatar
Jean-Marc Valin committed
496 497
      OPUS_CLEAR(ms_get_preemph_mem(st), channels);
      OPUS_CLEAR(ms_get_window_mem(st), channels*120);
498
   }
499
   st->mapping_type = mapping_type;
500 501 502
   return OPUS_OK;
}

503 504 505 506 507 508 509 510 511 512
int opus_multistream_encoder_init(
      OpusMSEncoder *st,
      opus_int32 Fs,
      int channels,
      int streams,
      int coupled_streams,
      const unsigned char *mapping,
      int application
)
{
513 514 515
   return opus_multistream_encoder_init_impl(st, Fs, channels, streams,
                                             coupled_streams, mapping,
                                             application, MAPPING_TYPE_NONE);
516 517 518 519 520 521 522 523 524 525 526 527 528
}

int opus_multistream_surround_encoder_init(
      OpusMSEncoder *st,
      opus_int32 Fs,
      int channels,
      int mapping_family,
      int *streams,
      int *coupled_streams,
      unsigned char *mapping,
      int application
)
{
529 530
   MappingType mapping_type;

531 532
   if ((channels>255) || (channels<1))
      return OPUS_BAD_ARG;
533
   st->lfe_stream = -1;
534
   if (mapping_family==0)
535
   {
536 537 538 539 540 541 542 543 544 545 546 547 548 549
      if (channels==1)
      {
         *streams=1;
         *coupled_streams=0;
         mapping[0]=0;
      } else if (channels==2)
      {
         *streams=1;
         *coupled_streams=1;
         mapping[0]=0;
         mapping[1]=1;
      } else
         return OPUS_UNIMPLEMENTED;
   } else if (mapping_family==1 && channels<=8 && channels>=1)
550
   {
551 552 553 554 555 556 557 558
      int i;
      *streams=vorbis_mappings[channels-1].nb_streams;
      *coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams;
      for (i=0;i<channels;i++)
         mapping[i] = vorbis_mappings[channels-1].mapping[i];
      if (channels>=6)
         st->lfe_stream = *streams-1;
   } else if (mapping_family==255)
559
   {
560 561 562 563 564
      int i;
      *streams=channels;
      *coupled_streams=0;
      for(i=0;i<channels;i++)
         mapping[i] = i;
565 566 567 568 569 570 571 572 573
#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
   } else if (mapping_family==254)
   {
      int i;
      *streams=channels;
      *coupled_streams=0;
      for(i=0;i<channels;i++)
         mapping[i] = i;
#endif
574
   } else
575
      return OPUS_UNIMPLEMENTED;
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

   if (channels>2 && mapping_family==1) {
      mapping_type = MAPPING_TYPE_SURROUND;
#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
   } else if (mapping_family==254)
   {
      mapping_type = MAPPING_TYPE_AMBISONICS;
#endif
   } else
   {
      mapping_type = MAPPING_TYPE_NONE;
   }
   return opus_multistream_encoder_init_impl(st, Fs, channels, *streams,
                                             *coupled_streams, mapping,
                                             application, mapping_type);
591 592
}

593 594 595 596 597 598 599 600 601 602 603 604 605
OpusMSEncoder *opus_multistream_encoder_create(
      opus_int32 Fs,
      int channels,
      int streams,
      int coupled_streams,
      const unsigned char *mapping,
      int application,
      int *error
)
{
   int ret;
   OpusMSEncoder *st;
   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
Mark Harris's avatar
Mark Harris committed
606
       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
   {
      if (error)
         *error = OPUS_BAD_ARG;
      return NULL;
   }
   st = (OpusMSEncoder *)opus_alloc(opus_multistream_encoder_get_size(streams, coupled_streams));
   if (st==NULL)
   {
      if (error)
         *error = OPUS_ALLOC_FAIL;
      return NULL;
   }
   ret = opus_multistream_encoder_init(st, Fs, channels, streams, coupled_streams, mapping, application);
   if (ret != OPUS_OK)
   {
      opus_free(st);
      st = NULL;
   }
   if (error)
      *error = ret;
   return st;
}

630 631 632 633 634 635 636 637 638 639 640 641
OpusMSEncoder *opus_multistream_surround_encoder_create(
      opus_int32 Fs,
      int channels,
      int mapping_family,
      int *streams,
      int *coupled_streams,
      unsigned char *mapping,
      int application,
      int *error
)
{
   int ret;
Mark Harris's avatar
Mark Harris committed
642
   opus_int32 size;
643 644 645 646 647 648 649
   OpusMSEncoder *st;
   if ((channels>255) || (channels<1))
   {
      if (error)
         *error = OPUS_BAD_ARG;
      return NULL;
   }
Mark Harris's avatar
Mark Harris committed
650 651 652 653 654 655 656 657
   size = opus_multistream_surround_encoder_get_size(channels, mapping_family);
   if (!size)
   {
      if (error)
         *error = OPUS_UNIMPLEMENTED;
      return NULL;
   }
   st = (OpusMSEncoder *)opus_alloc(size);
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
   if (st==NULL)
   {
      if (error)
         *error = OPUS_ALLOC_FAIL;
      return NULL;
   }
   ret = opus_multistream_surround_encoder_init(st, Fs, channels, mapping_family, streams, coupled_streams, mapping, application);
   if (ret != OPUS_OK)
   {
      opus_free(st);
      st = NULL;
   }
   if (error)
      *error = ret;
   return st;
}

675
static void surround_rate_allocation(
676 677
      OpusMSEncoder *st,
      opus_int32 *rate,
678 679
      int frame_size,
      opus_int32 Fs
680 681 682 683
      )
{
   int i;
   opus_int32 channel_rate;
684 685
   int stream_offset;
   int lfe_offset;
686 687 688
   int coupled_ratio; /* Q8 */
   int lfe_ratio;     /* Q8 */

689 690 691 692
   if (st->bitrate_bps > st->layout.nb_channels*40000)
      stream_offset = 20000;
   else
      stream_offset = st->bitrate_bps/st->layout.nb_channels/2;
693
   stream_offset += 60*(Fs/frame_size-50);
694 695 696
   /* We start by giving each stream (coupled or uncoupled) the same bitrate.
      This models the main saving of coupled channels over uncoupled. */
   /* The LFE stream is an exception to the above and gets fewer bits. */
697
   lfe_offset = 3500 + 60*(Fs/frame_size-50);
698 699 700
   /* Coupled streams get twice the mono rate after the first 20 kb/s. */
   coupled_ratio = 512;
   /* Should depend on the bitrate, for now we assume LFE gets 1/8 the bits of mono */
701 702 703 704 705 706 707 708 709 710
   lfe_ratio = 32;

   /* Compute bitrate allocation between streams */
   if (st->bitrate_bps==OPUS_AUTO)
   {
      channel_rate = Fs+60*Fs/frame_size;
   } else if (st->bitrate_bps==OPUS_BITRATE_MAX)
   {
      channel_rate = 300000;
   } else {
711 712 713 714 715 716 717 718 719 720
      int nb_lfe;
      int nb_uncoupled;
      int nb_coupled;
      int total;
      nb_lfe = (st->lfe_stream!=-1);
      nb_coupled = st->layout.nb_coupled_streams;
      nb_uncoupled = st->layout.nb_streams-nb_coupled-nb_lfe;
      total = (nb_uncoupled<<8)         /* mono */
            + coupled_ratio*nb_coupled /* stereo */
            + nb_lfe*lfe_ratio;
721
      channel_rate = 256*(opus_int64)(st->bitrate_bps-lfe_offset*nb_lfe-stream_offset*(nb_coupled+nb_uncoupled))/total;
722 723 724 725 726 727 728 729 730 731 732 733 734
   }
#ifndef FIXED_POINT
   if (st->variable_duration==OPUS_FRAMESIZE_VARIABLE && frame_size != Fs/50)
   {
      opus_int32 bonus;
      bonus = 60*(Fs/frame_size-50);
      channel_rate += bonus;
   }
#endif

   for (i=0;i<st->layout.nb_streams;i++)
   {
      if (i<st->layout.nb_coupled_streams)
735
         rate[i] = stream_offset+(channel_rate*coupled_ratio>>8);
736
      else if (i!=st->lfe_stream)
737
         rate[i] = stream_offset+channel_rate;
738
      else
739
         rate[i] = lfe_offset+(channel_rate*lfe_ratio>>8);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
   }
}

#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
static void ambisonics_rate_allocation(
      OpusMSEncoder *st,
      opus_int32 *rate,
      int frame_size,
      opus_int32 Fs
      )
{
   int i;
   int non_mono_rate;
   int total_rate;

   /* The mono channel gets (rate_ratio_num / rate_ratio_den) times as many bits
    * as all other channels */
   const int rate_ratio_num = 4;
   const int rate_ratio_den = 3;
   const int num_channels = st->layout.nb_streams;

   if (st->bitrate_bps==OPUS_AUTO)
   {
763 764
      total_rate = (st->layout.nb_coupled_streams + st->layout.nb_streams) *
         (Fs+60*Fs/frame_size) + st->layout.nb_streams * 15000;
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
   } else if (st->bitrate_bps==OPUS_BITRATE_MAX)
   {
      total_rate = num_channels * 320000;
   } else {
      total_rate = st->bitrate_bps;
   }

   /* Let y be the non-mono rate and let p, q be integers such that the mono
    * channel rate is (p/q) * y.
    * Also let T be the total bitrate to allocate. Then
    *   (n - 1) y + (p/q) y = T
    *   y = (T q) / (qn - q + p)
    */
   non_mono_rate =
         total_rate * rate_ratio_den
         / (rate_ratio_den*num_channels + rate_ratio_num - rate_ratio_den);

#ifndef FIXED_POINT
   if (st->variable_duration==OPUS_FRAMESIZE_VARIABLE && frame_size != Fs/50)
   {
      opus_int32 bonus = 60*(Fs/frame_size-50);
      non_mono_rate += bonus;
   }
#endif

   rate[0] = total_rate - (num_channels - 1) * non_mono_rate;
   for (i=1;i<st->layout.nb_streams;i++)
   {
      rate[i] = non_mono_rate;
   }
}
#endif /* ENABLE_EXPERIMENTAL_AMBISONICS */

static opus_int32 rate_allocation(
      OpusMSEncoder *st,
      opus_int32 *rate,
      int frame_size
      )
{
   int i;
   opus_int32 rate_sum=0;
   opus_int32 Fs;
   char *ptr;

   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));

#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
   if (st->mapping_type == MAPPING_TYPE_AMBISONICS) {
     ambisonics_rate_allocation(st, rate, frame_size, Fs);
   } else
#endif
   {
     surround_rate_allocation(st, rate, frame_size, Fs);
   }

   for (i=0;i<st->layout.nb_streams;i++)
   {
823 824
      rate[i] = IMAX(rate[i], 500);
      rate_sum += rate[i];
825
   }
826
   return rate_sum;
827 828
}

829 830 831 832 833 834 835
/* Max size in case the encoder decides to return three frames */
#define MS_FRAME_TMP (3*1275+7)
static int opus_multistream_encode_native
(
    OpusMSEncoder *st,
    opus_copy_channel_in_func copy_channel_in,
    const void *pcm,
836
    int analysis_frame_size,
837
    unsigned char *data,
838
    opus_int32 max_data_bytes,
839
    int lsb_depth,
840 841
    downmix_func downmix,
    int float_api
842 843 844 845 846 847 848 849 850
)
{
   opus_int32 Fs;
   int coupled_size;
   int mono_size;
   int s;
   char *ptr;
   int tot_size;
   VARDECL(opus_val16, buf);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
851
   VARDECL(opus_val16, bandSMR);
852 853
   unsigned char tmp_data[MS_FRAME_TMP];
   OpusRepacketizer rp;
854
   opus_int32 vbr;
855
   const CELTMode *celt_mode;
856
   opus_int32 bitrates[256];
857
   opus_val16 bandLogE[42];
Jean-Marc Valin's avatar
Jean-Marc Valin committed
858 859
   opus_val32 *mem = NULL;
   opus_val32 *preemph_mem=NULL;
860
   int frame_size;
861 862
   opus_int32 rate_sum;
   opus_int32 smallest_packet;
863 864
   ALLOC_STACK;

865
   if (st->mapping_type == MAPPING_TYPE_SURROUND)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
866 867 868 869 870
   {
      preemph_mem = ms_get_preemph_mem(st);
      mem = ms_get_window_mem(st);
   }

871 872
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));
873
   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_VBR(&vbr));
874
   opus_encoder_ctl((OpusEncoder*)ptr, CELT_GET_MODE(&celt_mode));
875

876 877 878 879 880 881
   {
      opus_int32 delay_compensation;

      opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_LOOKAHEAD(&delay_compensation));
      delay_compensation -= Fs/400;
      frame_size = compute_frame_size(pcm, analysis_frame_size,
882
            st->variable_duration, st->layout.nb_channels, Fs, st->bitrate_bps,
883 884 885 886 887
            delay_compensation, downmix
#ifndef DISABLE_FLOAT_API
            , st->subframe_mem
#endif
            );
888 889
   }

890 891 892 893 894
   if (400*frame_size < Fs)
   {
      RESTORE_STACK;
      return OPUS_BAD_ARG;
   }
895 896 897 898 899 900 901 902 903
   /* Validate frame_size before using it to allocate stack space.
      This mirrors the checks in opus_encode[_float](). */
   if (400*frame_size != Fs && 200*frame_size != Fs &&
       100*frame_size != Fs &&  50*frame_size != Fs &&
        25*frame_size != Fs &&  50*frame_size != 3*Fs)
   {
      RESTORE_STACK;
      return OPUS_BAD_ARG;
   }
904 905 906

   /* Smallest packet the encoder can produce. */
   smallest_packet = st->layout.nb_streams*2-1;
907 908 909
   if (max_data_bytes < smallest_packet)
   {
      RESTORE_STACK;
910
      return OPUS_BUFFER_TOO_SMALL;
911
   }
912 913 914 915
   ALLOC(buf, 2*frame_size, opus_val16);
   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);

Jean-Marc Valin's avatar
Jean-Marc Valin committed
916
   ALLOC(bandSMR, 21*st->layout.nb_channels, opus_val16);
917
   if (st->mapping_type == MAPPING_TYPE_SURROUND)
918
   {
919
      surround_analysis(celt_mode, pcm, bandSMR, mem, preemph_mem, frame_size, 120, st->layout.nb_channels, Fs, copy_channel_in, st->arch);
920 921
   }

922
   /* Compute bitrate allocation between streams (this could be a lot better) */
923
   rate_sum = rate_allocation(st, bitrates, frame_size);
924

925
   if (!vbr)
926 927 928 929 930 931 932 933 934 935
   {
      if (st->bitrate_bps == OPUS_AUTO)
      {
         max_data_bytes = IMIN(max_data_bytes, 3*rate_sum/(3*8*Fs/frame_size));
      } else if (st->bitrate_bps != OPUS_BITRATE_MAX)
      {
         max_data_bytes = IMIN(max_data_bytes, IMAX(smallest_packet,
                          3*st->bitrate_bps/(3*8*Fs/frame_size)));
      }
   }
936 937 938 939 940 941 942 943 944
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   for (s=0;s<st->layout.nb_streams;s++)
   {
      OpusEncoder *enc;
      enc = (OpusEncoder*)ptr;
      if (s < st->layout.nb_coupled_streams)
         ptr += align(coupled_size);
      else
         ptr += align(mono_size);
945
      opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrates[s]));
946
      if (st->mapping_type == MAPPING_TYPE_SURROUND)
947
      {
948 949 950 951
         opus_int32 equiv_rate;
         equiv_rate = st->bitrate_bps;
         if (frame_size*50 < Fs)
            equiv_rate -= 60*(Fs/frame_size - 50)*st->layout.nb_channels;
952
         if (equiv_rate > 10000*st->layout.nb_channels)
953
            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND));
954
         else if (equiv_rate > 7000*st->layout.nb_channels)
955
            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_SUPERWIDEBAND));
956
         else if (equiv_rate > 5000*st->layout.nb_channels)
957 958 959
            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_WIDEBAND));
         else
            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_NARROWBAND));
960
         if (s < st->layout.nb_coupled_streams)
961 962 963
         {
            /* To preserve the spatial image, force stereo CELT on coupled streams */
            opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
964
            opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(2));
965
         }
966
      }
967 968 969 970 971
#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
      else if (st->mapping_type == MAPPING_TYPE_AMBISONICS) {
        opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
      }
#endif
972 973 974
   }

   ptr = (char*)st + align(sizeof(OpusMSEncoder));
975 976 977 978 979 980 981
   /* Counting ToC */
   tot_size = 0;
   for (s=0;s<st->layout.nb_streams;s++)
   {
      OpusEncoder *enc;
      int len;
      int curr_max;
982
      int c1, c2;
983
      int ret;
984 985 986 987 988

      opus_repacketizer_init(&rp);
      enc = (OpusEncoder*)ptr;
      if (s < st->layout.nb_coupled_streams)
      {
Jean-Marc Valin's avatar
Jean-Marc Valin committed
989
         int i;
990 991 992 993 994 995 996 997
         int left, right;
         left = get_left_channel(&st->layout, s, -1);
         right = get_right_channel(&st->layout, s, -1);
         (*copy_channel_in)(buf, 2,
            pcm, st->layout.nb_channels, left, frame_size);
         (*copy_channel_in)(buf+1, 2,
            pcm, st->layout.nb_channels, right, frame_size);
         ptr += align(coupled_size);
998
         if (st->mapping_type == MAPPING_TYPE_SURROUND)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
999 1000 1001 1002 1003 1004 1005
         {
            for (i=0;i<21;i++)
            {
               bandLogE[i] = bandSMR[21*left+i];
               bandLogE[21+i] = bandSMR[21*right+i];
            }
         }
1006 1007
         c1 = left;
         c2 = right;
1008
      } else {
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1009
         int i;
1010 1011 1012 1013
         int chan = get_mono_channel(&st->layout, s, -1);
         (*copy_channel_in)(buf, 1,
            pcm, st->layout.nb_channels, chan, frame_size);
         ptr += align(mono_size);
1014
         if (st->mapping_type == MAPPING_TYPE_SURROUND)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1015 1016 1017 1018
         {
            for (i=0;i<21;i++)
               bandLogE[i] = bandSMR[21*chan+i];
         }
1019 1020
         c1 = chan;
         c2 = -1;
1021
      }
1022
      if (st->mapping_type == MAPPING_TYPE_SURROUND)
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1023
         opus_encoder_ctl(enc, OPUS_SET_ENERGY_MASK(bandLogE));
1024 1025
      /* number of bytes left (+Toc) */
      curr_max = max_data_bytes - tot_size;
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1026
      /* Reserve one byte for the last stream and two for the others */
1027
      curr_max -= IMAX(0,2*(st->layout.nb_streams-s-1)-1);
1028
      curr_max = IMIN(curr_max,MS_FRAME_TMP);
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1029
      /* Repacketizer will add one or two bytes for self-delimited frames */
1030
      if (s != st->layout.nb_streams-1) curr_max -=  curr_max>253 ? 2 : 1;
1031 1032
      if (!vbr && s == st->layout.nb_streams-1)
         opus_encoder_ctl(enc, OPUS_SET_BITRATE(curr_max*(8*Fs/frame_size)));
1033
      len = opus_encode_native(enc, buf, frame_size, tmp_data, curr_max, lsb_depth,
1034
            pcm, analysis_frame_size, c1, c2, st->layout.nb_channels, downmix, float_api);
1035 1036 1037 1038 1039 1040 1041 1042
      if (len<0)
      {
         RESTORE_STACK;
         return len;
      }
      /* We need to use the repacketizer to add the self-delimiting lengths
         while taking into account the fact that the encoder can now return
         more than one frame at a time (e.g. 60 ms CELT-only) */
1043 1044 1045 1046
      ret = opus_repacketizer_cat(&rp, tmp_data, len);
      /* If the opus_repacketizer_cat() fails, then something's seriously wrong
         with the encoder. */
      if (ret != OPUS_OK)
1047 1048
      {
         RESTORE_STACK;
1049
         return OPUS_INTERNAL_ERROR;
1050
      }
1051 1052
      len = opus_repacketizer_out_range_impl(&rp, 0, opus_repacketizer_get_nb_frames(&rp),
            data, max_data_bytes-tot_size, s != st->layout.nb_streams-1, !vbr && s == st->layout.nb_streams-1);
1053 1054 1055
      data += len;
      tot_size += len;
   }
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1056
   /*printf("\n");*/
1057 1058 1059 1060
   RESTORE_STACK;
   return tot_size;
}

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
#if !defined(DISABLE_FLOAT_API)
static void opus_copy_channel_in_float(
  opus_val16 *dst,
  int dst_stride,
  const void *src,
  int src_stride,
  int src_channel,
  int frame_size
)
{
   const float *float_src;
   opus_int32 i;
   float_src = (const float *)src;
   for (i=0;i<frame_size;i++)
#if defined(FIXED_POINT)
      dst[i*dst_stride] = FLOAT2INT16(float_src[i*src_stride+src_channel]);
#else
      dst[i*dst_stride] = float_src[i*src_stride+src_channel];
#endif
}
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
#endif

static void opus_copy_channel_in_short(
  opus_val16 *dst,
  int dst_stride,
  const void *src,
  int src_stride,
  int src_channel,
  int frame_size
)
{
   const opus_int16 *short_src;
1093
   opus_int32 i;
1094 1095 1096 1097 1098 1099 1100 1101 1102
   short_src = (const opus_int16 *)src;
   for (i=0;i<frame_size;i++)
#if defined(FIXED_POINT)
      dst[i*dst_stride] = short_src[i*src_stride+src_channel];
#else
      dst[i*dst_stride] = (1/32768.f)*short_src[i*src_stride+src_channel];
#endif
}

1103

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
#ifdef FIXED_POINT
int opus_multistream_encode(
    OpusMSEncoder *st,
    const opus_val16 *pcm,
    int frame_size,
    unsigned char *data,
    opus_int32 max_data_bytes
)
{
   return opus_multistream_encode_native(st, opus_copy_channel_in_short,
1114
      pcm, frame_size, data, max_data_bytes, 16, downmix_int, 0);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
}

#ifndef DISABLE_FLOAT_API
int opus_multistream_encode_float(
    OpusMSEncoder *st,
    const float *pcm,
    int frame_size,
    unsigned char *data,
    opus_int32 max_data_bytes
)
{
   return opus_multistream_encode_native(st, opus_copy_channel_in_float,
1127
      pcm, frame_size, data, max_data_bytes, 16, downmix_float, 1);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
}
#endif

#else

int opus_multistream_encode_float
(
    OpusMSEncoder *st,
    const opus_val16 *pcm,
    int frame_size,
    unsigned char *data,
    opus_int32 max_data_bytes
)
{
   return opus_multistream_encode_native(st, opus_copy_channel_in_float,
1143
      pcm, frame_size, data, max_data_bytes, 24, downmix_float, 1);
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
}

int opus_multistream_encode(
    OpusMSEncoder *st,
    const opus_int16 *pcm,
    int frame_size,
    unsigned char *data,
    opus_int32 max_data_bytes
)
{
   return opus_multistream_encode_native(st, opus_copy_channel_in_short,
1155
      pcm, frame_size, data, max_data_bytes, 16, downmix_int, 0);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
}
#endif

int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...)
{
   va_list ap;
   int coupled_size, mono_size;
   char *ptr;
   int ret = OPUS_OK;

   va_start(ap, request);

   coupled_size = opus_encoder_get_size(2);
   mono_size = opus_encoder_get_size(1);
   ptr = (char*)st + align(sizeof(OpusMSEncoder));
   switch (request)
   {
   case OPUS_SET_BITRATE_REQUEST:
   {
      opus_int32 value = va_arg(ap, opus_int32);
1176
      if (value != OPUS_AUTO && value != OPUS_BITRATE_MAX)
Gregory Maxwell's avatar
Gregory Maxwell committed
1177
      {
1178 1179 1180
         if (value <= 0)
            goto bad_arg;
         value = IMIN(300000*st->layout.nb_channels, IMAX(500*st->layout.nb_channels, value));
1181
      }
1182
      st->bitrate_bps = value;
1183 1184 1185 1186 1187 1188
   }
   break;
   case OPUS_GET_BITRATE_REQUEST:
   {
      int s;
      opus_int32 *value = va_arg(ap, opus_int32*);
Gregory Maxwell's avatar
Gregory Maxwell committed
1189 1190
      if (!value)
      {
1191 1192
         goto bad_arg;
      }
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
      *value = 0;
      for (s=0;s<st->layout.nb_streams;s++)
      {
         opus_int32 rate;
         OpusEncoder *enc;
         enc = (OpusEncoder*)ptr;
         if (s < st->layout.nb_coupled_streams)
            ptr += align(