aboutsummaryrefslogtreecommitdiffstats
path: root/libMpegTPEnc/src/tpenc_latm.cpp
blob: a26d0dab5ae34a340a7f77348e5e66c85046b1cb (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
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
/*****************************  MPEG-4 AAC Encoder  **************************

                        (C) Copyright Fraunhofer IIS (2001)
                               All Rights Reserved

    Please be advised that this software and/or program delivery is
    Confidential Information of Fraunhofer and subject to and covered by the

    Fraunhofer IIS Software Evaluation Agreement
    between Google Inc. and  Fraunhofer
    effective and in full force since March 1, 2012.

    You may use this software and/or program only under the terms and
    conditions described in the above mentioned Fraunhofer IIS Software
    Evaluation Agreement. Any other and/or further use requires a separate agreement.


   $Id$
   Author(s):
   Description:

   This software and/or program is protected by copyright law and international
   treaties. Any reproduction or distribution of this software and/or program,
   or any portion of it, may result in severe civil and criminal penalties, and
   will be prosecuted to the maximum extent possible under law.

******************************************************************************/

#include "tpenc_latm.h"


#include "genericStds.h"

static const short celpFrameLengthTable[64] = {
 154, 170, 186, 147, 156, 165, 114, 120,
 186, 126, 132, 138, 142, 146, 154, 166,
 174, 182, 190, 198, 206, 210, 214, 110,
 114, 118, 120, 122, 218, 230, 242, 254,
 266, 278, 286, 294, 318, 342, 358, 374,
 390, 406, 422, 136, 142, 148, 154, 160,
 166, 170, 174, 186, 198, 206, 214, 222,
 230, 238, 216, 160, 280, 338, 0,   0
};

/*******
 write value to transport stream
 first two bits define the size of the value itself
 then the value itself, with a size of 0-3 bytes
*******/
static
UINT transportEnc_LatmWriteValue(HANDLE_FDK_BITSTREAM hBs, int value)
{
  UCHAR valueBytes = 4;
  unsigned int bitsWritten = 0;
  int i;

  if ( value < (1<<8) ) {
    valueBytes = 1;
  } else if ( value < (1<<16) ) {
    valueBytes = 2;
  } else if ( value < (1<<24) ) {
    valueBytes = 3;
  } else {
    valueBytes = 4;
  }

  FDKwriteBits(hBs, valueBytes-1, 2 ); /* size of value in Bytes */
  for (i=0; i<valueBytes; i++) {
    /* write most significant Byte first */
    FDKwriteBits(hBs, (UCHAR)(value>>((valueBytes-1-i)<<3)), 8);
  }

  bitsWritten = (valueBytes<<3)+2;

  return bitsWritten;
}

static
UINT transportEnc_LatmCountFixBitDemandHeader ( HANDLE_LATM_STREAM hAss )
{
  int bitDemand = 0;
  int insertSetupData = 0 ;

  /* only if start of new latm frame */
  if (hAss->subFrameCnt==0)
  {
    /* AudioSyncStream */

    if (hAss->tt == TT_MP4_LOAS) {
      bitDemand += 11 ;             /* syncword */
      bitDemand += 13 ;             /* audioMuxLengthBytes */
    }

    /* AudioMuxElement*/

    /* AudioMuxElement::Stream Mux Config */
    if (hAss->muxConfigPeriod > 0) {
      insertSetupData = (hAss->latmFrameCounter == 0);
    } else {
      insertSetupData = 0;
    }

    if (hAss->tt != TT_MP4_LATM_MCP0) {
      /* AudioMuxElement::useSameStreamMux Flag */
      bitDemand+=1;

      if( insertSetupData ) {
        bitDemand += hAss->streamMuxConfigBits;
      }
    }

    /* AudioMuxElement::otherDataBits */
    bitDemand += 8*hAss->otherDataLenBytes;

    /* AudioMuxElement::ByteAlign */
    if ( bitDemand % 8 ) {
       hAss->fillBits = 8 - (bitDemand % 8);
       bitDemand += hAss->fillBits ;
    } else {
      hAss->fillBits = 0;
    }
  }

  return bitDemand ;
}

static
UINT transportEnc_LatmCountVarBitDemandHeader ( HANDLE_LATM_STREAM hAss , unsigned int streamDataLength )
{
  int bitDemand = 0;
  int  prog, layer;

  /* Payload Length Info*/
  if( hAss->allStreamsSameTimeFraming ) {
    for( prog=0; prog<hAss->noProgram; prog++ ) {
      for( layer=0; layer<LATM_MAX_LAYERS; layer++ ) {
        LATM_LAYER_INFO *p_linfo = &(hAss->m_linfo[prog][layer]);

        if( p_linfo->streamID >= 0 ) {
          switch( p_linfo->frameLengthType ) {
          case 0:
            if ( streamDataLength > 0 ) {
              streamDataLength -= bitDemand ;
              while( streamDataLength >= (255<<3) ) {
                bitDemand+=8;
                streamDataLength -= (255<<3);
              }
              bitDemand += 8;
            }
            break;

          case 1:
          case 4:
          case 6:
            bitDemand += 2;
            break;

          default:
            return 0;
          }
        }
      }
    }
  } else {
    /* there are many possibilities to use this mechanism.  */
    switch( hAss->varMode ) {
    case LATMVAR_SIMPLE_SEQUENCE: {
      /* Use the sequence generated by the encoder */
      //int streamCntPosition = transportEnc_SetWritePointer( hAss->hAssemble, 0 );
      //int streamCntPosition = FDKgetValidBits( hAss->hAssemble );
      bitDemand+=4;

      hAss->varStreamCnt = 0;
      for( prog=0; prog<hAss->noProgram; prog++ ) {
        for( layer=0; layer<LATM_MAX_LAYERS; layer++ ) {
          LATM_LAYER_INFO *p_linfo = &(hAss->m_linfo[prog][layer]);

          if( p_linfo->streamID >= 0 ) {

            bitDemand+=4; /* streamID */
            switch( p_linfo->frameLengthType ) {
            case 0:
              streamDataLength -= bitDemand ;
              while( streamDataLength >= (255<<3) ) {
                bitDemand+=8;
                streamDataLength -= (255<<3);
              }

              bitDemand += 8;
              break;
              /*bitDemand += 1; endFlag
              break;*/

            case 1:
            case 4:
            case 6:

              break;

            default:
              return  0;
            }
            hAss->varStreamCnt++;
          }
        }
      }
      bitDemand+=4;
      //transportEnc_UpdateBitstreamField( hAss->hAssemble, streamCntPosition, hAss->varStreamCnt-1, 4 );
      //UINT pos = streamCntPosition-FDKgetValidBits(hAss->hAssemble);
      //FDKpushBack( hAss->hAssemble,  pos);
      //FDKwriteBits( hAss->hAssemble, hAss->varStreamCnt-1, 4);
      //FDKpushFor( hAss->hAssemble, pos-4);
    }
    break;

    default:
      return  0;
    }
  }

  return bitDemand ;
}

TRANSPORTENC_ERROR
CreateStreamMuxConfig(
                      HANDLE_LATM_STREAM hAss,
                      HANDLE_FDK_BITSTREAM hBs,
                      int bufferFullness,
                      CSTpCallBacks *cb
                     )
{
  INT streamIDcnt, tmp;
  int layer, prog;

  USHORT coreFrameOffset=0;

  hAss->audioMuxVersionA    = 0; /* for future extensions */
  hAss->streamMuxConfigBits = 0;

  FDKwriteBits( hBs, hAss->audioMuxVersion, 1 );                   /* audioMuxVersion */
  hAss->streamMuxConfigBits += 1;

  if ( hAss->audioMuxVersion == 1 ) {
    FDKwriteBits( hBs, hAss->audioMuxVersionA, 1 );                /* audioMuxVersionA */
    hAss->streamMuxConfigBits+=1;
  }

  if ( hAss->audioMuxVersionA == 0 )
  {
    if ( hAss->audioMuxVersion == 1 ) {
      hAss->streamMuxConfigBits+= transportEnc_LatmWriteValue( hBs, hAss->taraBufferFullness );/* taraBufferFullness */
    }
    FDKwriteBits( hBs, hAss->allStreamsSameTimeFraming ? 1:0, 1 ); /* allStreamsSameTimeFraming */
    FDKwriteBits( hBs, hAss->noSubframes-1, 6 );                   /* Number of Subframes */
    FDKwriteBits( hBs, hAss->noProgram-1, 4 );                     /* Number of Programs */

    hAss->streamMuxConfigBits+=11;

    streamIDcnt = 0;
    for( prog=0; prog<hAss->noProgram; prog++ ) {
      int transLayer = 0;

      FDKwriteBits( hBs, hAss->noLayer[prog]-1, 3 );
      hAss->streamMuxConfigBits+=3;

      for( layer=0; layer<LATM_MAX_LAYERS; layer++ ) {
        LATM_LAYER_INFO   *p_linfo = &(hAss->m_linfo[prog][layer]);
        CODER_CONFIG *p_lci   = hAss->config[prog][layer];

        p_linfo->streamID = -1;

        if( hAss->config[prog][layer] != NULL ) {
          int useSameConfig = 0;

          if( transLayer > 0 ) {
            FDKwriteBits( hBs, useSameConfig ? 1 : 0, 1 );
            hAss->streamMuxConfigBits+=1;
          }
          if( (useSameConfig == 0) || (transLayer==0) ) {
            UINT bits;

            if ( hAss->audioMuxVersion == 1 ) {
              FDKpushFor(hBs, 2); /* align to ASC, even if we do not know the length of the "ascLen" field yet */
            }

            bits = FDKgetValidBits( hBs );

            transportEnc_writeASC(
                    hBs,
                    hAss->config[prog][layer],
                    cb
                    );

            bits = FDKgetValidBits( hBs ) - bits;

            if ( hAss->audioMuxVersion == 1 ) {
              FDKpushBack(hBs, bits+2);
              hAss->streamMuxConfigBits += transportEnc_LatmWriteValue( hBs, bits );
              transportEnc_writeASC(
                      hBs,
                      hAss->config[prog][layer],
                      cb
                      );
            }

            hAss->streamMuxConfigBits += bits; /* add asc length to smc summary */
          }
          transLayer++;

          if( !hAss->allStreamsSameTimeFraming ) {
            if( streamIDcnt >= LATM_MAX_STREAM_ID )
              return TRANSPORTENC_INVALID_CONFIG;
          }
          p_linfo->streamID = streamIDcnt++;

          switch( p_lci->aot ) {
          case AOT_AAC_MAIN      :
          case AOT_AAC_LC        :
          case AOT_AAC_SSR       :
          case AOT_AAC_LTP       :
          case AOT_AAC_SCAL      :
          case AOT_ER_AAC_LD     :
          case AOT_ER_AAC_ELD    :
          case AOT_USAC:
          case AOT_RSVD50:
            p_linfo->frameLengthType = 0;

            FDKwriteBits( hBs, p_linfo->frameLengthType, 3 );                        /* frameLengthType */
            FDKwriteBits( hBs, bufferFullness, 8 );                           /* bufferFullness */
            hAss->streamMuxConfigBits+=11;

            if ( !hAss->allStreamsSameTimeFraming ) {
              CODER_CONFIG *p_lci_prev = hAss->config[prog][layer-1];
              if ( ((p_lci->aot == AOT_AAC_SCAL) || (p_lci->aot == AOT_ER_AAC_SCAL)) &&
                   ((p_lci_prev->aot == AOT_CELP) || (p_lci_prev->aot == AOT_ER_CELP)) ) {
                FDKwriteBits( hBs, coreFrameOffset, 6 );                      /* coreFrameOffset */
                hAss->streamMuxConfigBits+=6;
              }
            }
            break;

          case AOT_TWIN_VQ:
            p_linfo->frameLengthType = 1;
            tmp = ( (p_lci->bitsFrame+7) >> 3 ) - 20;                            /* transmission frame length in bytes */
            if( (tmp < 0) ) {
              return TRANSPORTENC_INVALID_TRANSMISSION_FRAME_LENGTH;
            }
            FDKwriteBits( hBs, p_linfo->frameLengthType, 3 );          /* frameLengthType */
            FDKwriteBits( hBs, tmp, 9 );
            hAss->streamMuxConfigBits+=12;

            p_linfo->frameLengthBits = (tmp+20) << 3;
            break;

          case AOT_CELP:
            p_linfo->frameLengthType = 4;
            FDKwriteBits( hBs, p_linfo->frameLengthType, 3 );          /* frameLengthType */
            hAss->streamMuxConfigBits+=3;
            {
              int i;
              for( i=0; i<62; i++ ) {
                if( celpFrameLengthTable[i] == p_lci->bitsFrame )
                  break;
              }
              if( i>=62 ) {
                return TRANSPORTENC_INVALID_CELP_FRAME_LENGTH;
              }

              FDKwriteBits( hBs, i, 6 );                                /* CELPframeLengthTabelIndex */
              hAss->streamMuxConfigBits+=6;
            }
            p_linfo->frameLengthBits = p_lci->bitsFrame;
            break;

          case AOT_HVXC:
            p_linfo->frameLengthType = 6;
            FDKwriteBits( hBs, p_linfo->frameLengthType, 3 );          /* frameLengthType */
            hAss->streamMuxConfigBits+=3;
            {
              int i;

              if( p_lci->bitsFrame == 40 ) {
                i = 0;
              } else if( p_lci->bitsFrame == 80 ) {
                i = 1;
              } else {
                return TRANSPORTENC_INVALID_FRAME_BITS;
              }
              FDKwriteBits( hBs, i, 1 );                                /* HVXCframeLengthTableIndex */
              hAss->streamMuxConfigBits+=1;
            }
            p_linfo->frameLengthBits = p_lci->bitsFrame;
            break;

          case AOT_NULL_OBJECT:
          default:
            return TRANSPORTENC_INVALID_AOT;
          }
        }
      }
    }

    FDKwriteBits( hBs, (hAss->otherDataLenBytes>0) ? 1:0, 1 );      /* otherDataPresent */
    hAss->streamMuxConfigBits+=1;

    if( hAss->otherDataLenBytes > 0 ) {

      INT otherDataLenTmp = hAss->otherDataLenBytes;
      INT escCnt = 0;
      INT otherDataLenEsc = 1;

      while(otherDataLenTmp) {
        otherDataLenTmp >>= 8;
        escCnt ++;
      }

      do {
        otherDataLenTmp = (hAss->otherDataLenBytes>>(escCnt*8)) & 0xFF;
        escCnt--;
        otherDataLenEsc = escCnt>0;

        FDKwriteBits( hBs, otherDataLenEsc, 1 );
        FDKwriteBits( hBs, otherDataLenTmp, 8 );
        hAss->streamMuxConfigBits+=9;
      } while(otherDataLenEsc);
    }

    {
      USHORT crcCheckPresent=0;
      USHORT crcCheckSum=0;

      FDKwriteBits( hBs, crcCheckPresent, 1 );               /* crcCheckPresent */
      hAss->streamMuxConfigBits+=1;
      if ( crcCheckPresent ){
        FDKwriteBits( hBs, crcCheckSum, 8 );                 /* crcCheckSum */
        hAss->streamMuxConfigBits+=8;
      }
    }

  } else {  /* if ( audioMuxVersionA == 0 ) */

    /* for future extensions */

  }

  return TRANSPORTENC_OK;
}


static TRANSPORTENC_ERROR
WriteAuPayloadLengthInfo( HANDLE_FDK_BITSTREAM hBitStream, int AuLengthBits )
{
  int restBytes;

  if( AuLengthBits % 8 )
    return TRANSPORTENC_INVALID_AU_LENGTH;

  while( AuLengthBits >= 255*8 ) {
    FDKwriteBits( hBitStream, 255, 8 );  /* 255 shows incomplete AU */
    AuLengthBits -= (255*8);
  }

  restBytes = (AuLengthBits) >> 3;
  FDKwriteBits( hBitStream, restBytes, 8 );

  return TRANSPORTENC_OK;
}

static
TRANSPORTENC_ERROR transportEnc_LatmSetNrOfSubframes( HANDLE_LATM_STREAM hAss,
                                                      INT noSubframes_next)    /* nr of access units / payloads within a latm frame */
{
  /* sanity chk */
  if (noSubframes_next < 1 || noSubframes_next > MAX_NR_OF_SUBFRAMES) {
    return TRANSPORTENC_LATM_INVALID_NR_OF_SUBFRAMES;
  }

  hAss->noSubframes_next = noSubframes_next;

  /* if at start then we can take over the value immediately, otherwise we have to wait for the next SMC */
  if ( (hAss->subFrameCnt == 0) && (hAss->latmFrameCounter == 0) ) {
    hAss->noSubframes = noSubframes_next;
  }

  return TRANSPORTENC_OK;
}

static
int allStreamsSameTimeFraming( HANDLE_LATM_STREAM hAss, UCHAR noProgram, UCHAR noLayer[] /* return */ )
{
  int prog, layer;

  signed int lastNoSamples   = -1;
  signed int minFrameSamples = FDK_INT_MAX;
  signed int maxFrameSamples = 0;

  signed int highestSamplingRate = -1;

  for( prog=0; prog<noProgram; prog++ ) {
    noLayer[prog] = 0;

    for( layer=0; layer<LATM_MAX_LAYERS; layer++ )
    {
      if( hAss->config[prog][layer] != NULL )
      {
        INT hsfSamplesFrame;

        noLayer[prog]++;

        if( highestSamplingRate < 0 )
          highestSamplingRate = hAss->config[prog][layer]->samplingRate;

        hsfSamplesFrame = hAss->config[prog][layer]->samplesPerFrame  * highestSamplingRate / hAss->config[prog][layer]->samplingRate;

        if( hsfSamplesFrame <= minFrameSamples ) minFrameSamples = hsfSamplesFrame;
        if( hsfSamplesFrame >= maxFrameSamples ) maxFrameSamples = hsfSamplesFrame;

        if( lastNoSamples == -1 ) {
          lastNoSamples                             = hsfSamplesFrame;
        } else {
          if( hsfSamplesFrame != lastNoSamples ) {
            return 0;
          }
        }
      }
    }
  }

  return 1;
}

/**
 * Initialize LATM/LOAS Stream and add layer 0 at program 0.
 */
static
TRANSPORTENC_ERROR transportEnc_InitLatmStream( HANDLE_LATM_STREAM hAss,
                                                int                fractDelayPresent,
                                                signed int         muxConfigPeriod, /* insert setup data every muxConfigPeriod frames */
                                                UINT               audioMuxVersion,
                                                TRANSPORT_TYPE     tt
                                              )
{
  TRANSPORTENC_ERROR ErrorStatus = TRANSPORTENC_OK;

  if (hAss == NULL)
    return TRANSPORTENC_INVALID_PARAMETER;

  hAss->tt = tt;

  hAss->noProgram = 1;

  hAss->audioMuxVersion = audioMuxVersion;

  /* Fill noLayer array using hAss->config */
  hAss->allStreamsSameTimeFraming = allStreamsSameTimeFraming( hAss, hAss->noProgram, hAss->noLayer );
  /* Only allStreamsSameTimeFraming==1 is supported */
  FDK_ASSERT(hAss->allStreamsSameTimeFraming);

  hAss->fractDelayPresent = fractDelayPresent;
  hAss->otherDataLenBytes = 0;

  hAss->varMode = LATMVAR_SIMPLE_SEQUENCE;

  /* initialize counters */
  hAss->subFrameCnt                  = 0;
  hAss->noSubframes                  = DEFAULT_LATM_NR_OF_SUBFRAMES;
  hAss->noSubframes_next             = DEFAULT_LATM_NR_OF_SUBFRAMES;

  /* sync layer related */
  hAss->audioMuxLengthBytes     = 0;

  hAss->latmFrameCounter        = 0;
  hAss->muxConfigPeriod = muxConfigPeriod;

  return ErrorStatus;
}


/**
 *
 */
UINT transportEnc_LatmCountTotalBitDemandHeader ( HANDLE_LATM_STREAM hAss , unsigned int streamDataLength )
{
  UINT bitDemand = 0;

  switch (hAss->tt) {
  case TT_MP4_LOAS:
  case TT_MP4_LATM_MCP0:
  case TT_MP4_LATM_MCP1:
    if (hAss->subFrameCnt == 0) {
      bitDemand  = transportEnc_LatmCountFixBitDemandHeader ( hAss );
    }
    bitDemand += transportEnc_LatmCountVarBitDemandHeader ( hAss , streamDataLength /*- bitDemand*/);
    break;
  default:
    break;
  }

  return bitDemand;
}

static TRANSPORTENC_ERROR
AdvanceAudioMuxElement (
        HANDLE_LATM_STREAM   hAss,
        HANDLE_FDK_BITSTREAM hBs,
        int                  auBits,
        int                  bufferFullness,
        CSTpCallBacks    *cb
        )
{
  TRANSPORTENC_ERROR ErrorStatus = TRANSPORTENC_OK;
  int insertMuxSetup;

  /* Insert setup data to assemble Buffer */
  if (hAss->subFrameCnt == 0)
  {
    if (hAss->muxConfigPeriod > 0) {
      insertMuxSetup = (hAss->latmFrameCounter == 0);
    } else  {
      insertMuxSetup = 0;
    }

    if (hAss->tt != TT_MP4_LATM_MCP0) {
      if( insertMuxSetup ) {
        FDKwriteBits( hBs, 0, 1 );  /* useSameStreamMux useNewStreamMux */
        CreateStreamMuxConfig(hAss, hBs, bufferFullness, cb);
        if (ErrorStatus != TRANSPORTENC_OK)
          return ErrorStatus;
      } else {
        FDKwriteBits( hBs, 1, 1 );   /* useSameStreamMux */
      }
    }
  }

  /* PayloadLengthInfo */
  {
    int prog, layer;

    for (prog = 0; prog < hAss->noProgram; prog++) {
      for (layer = 0; layer < hAss->noLayer[prog]; layer++) {
        ErrorStatus = WriteAuPayloadLengthInfo( hBs, auBits );
        if (ErrorStatus != TRANSPORTENC_OK)
          return ErrorStatus;
      }
    }
  }
  /* At this point comes the access unit. */

  return TRANSPORTENC_OK;
}

TRANSPORTENC_ERROR
transportEnc_LatmWrite (
        HANDLE_LATM_STREAM    hAss,
        HANDLE_FDK_BITSTREAM  hBs,
        int                   auBits,
        int                   bufferFullness,
        CSTpCallBacks     *cb
        )
{
  TRANSPORTENC_ERROR ErrorStatus;

  if (hAss->subFrameCnt == 0) {
    /* Start new frame */
    FDKresetBitbuffer(hBs, BS_WRITER);
  }

  hAss->latmSubframeStart = FDKgetValidBits(hBs);

  /* Insert syncword and syncword distance
     - only if loas
     - we must update the syncword distance (=audiomuxlengthbytes) later
   */
  if( hAss->tt == TT_MP4_LOAS && hAss->subFrameCnt == 0)
  {
    /* Start new LOAS frame */
    FDKwriteBits( hBs, 0x2B7, 11 );
    hAss->audioMuxLengthBytes = 0;
    hAss->audioMuxLengthBytesPos = FDKgetValidBits( hBs );  /* store read pointer position */
    FDKwriteBits( hBs, hAss->audioMuxLengthBytes, 13 );
  }

  ErrorStatus = AdvanceAudioMuxElement(
          hAss,
          hBs,
          auBits,
          bufferFullness,
          cb
          );

  if (ErrorStatus != TRANSPORTENC_OK)
    return ErrorStatus;

  return ErrorStatus;
}

void transportEnc_LatmAdjustSubframeBits(HANDLE_LATM_STREAM    hAss,
                                         int                  *bits)
{
  /* Substract bits from possible previous subframe */
  *bits -= hAss->latmSubframeStart;
  /* Add fill bits */
  if (hAss->subFrameCnt == 0)
    *bits += hAss->fillBits;
}


void transportEnc_LatmGetFrame(HANDLE_LATM_STREAM    hAss,
                               HANDLE_FDK_BITSTREAM  hBs,
                               int                  *bytes)
{

  hAss->subFrameCnt++;
  if (hAss->subFrameCnt >= hAss->noSubframes)
  {

    /* Add LOAS frame length if required. */
    if (hAss->tt == TT_MP4_LOAS)
    {
      int latmBytes;

      latmBytes = (FDKgetValidBits(hBs)+7) >> 3;

      /* write length info into assembler buffer */
      hAss->audioMuxLengthBytes = latmBytes - 3; /* 3=Syncword + length */
      {
        FDK_BITSTREAM tmpBuf;

        FDKinitBitStream( &tmpBuf, hBs->hBitBuf.Buffer, hBs->hBitBuf.bufSize, 0, BS_WRITER ) ;
        FDKpushFor( &tmpBuf, hAss->audioMuxLengthBytesPos );
        FDKwriteBits( &tmpBuf, hAss->audioMuxLengthBytes, 13 );
        FDKsyncCache( &tmpBuf );
      }
    }

    /* Write AudioMuxElement byte alignment fill bits */
    FDKwriteBits(hBs, 0, hAss->fillBits);

    FDK_ASSERT( (FDKgetValidBits(hBs) % 8) == 0);

    hAss->subFrameCnt = 0;

    FDKsyncCache(hBs);
    *bytes = (FDKgetValidBits(hBs) + 7)>>3;
    //FDKfetchBuffer(hBs, buffer, (UINT*)bytes);

    if (hAss->muxConfigPeriod > 0)
    {
      hAss->latmFrameCounter++;

      if (hAss->latmFrameCounter >= hAss->muxConfigPeriod) {
        hAss->latmFrameCounter = 0;
        hAss->noSubframes = hAss->noSubframes_next;
      }
    }
  } else {
    /* No data this time */
    *bytes = 0;
  }
}

/**
 * Init LATM/LOAS
 */
TRANSPORTENC_ERROR transportEnc_Latm_Init(
        HANDLE_LATM_STREAM  hAss,
        HANDLE_FDK_BITSTREAM hBs,
        CODER_CONFIG  *layerConfig,
        UINT audioMuxVersion,
        TRANSPORT_TYPE tt,
        CSTpCallBacks *cb
        )
{
  TRANSPORTENC_ERROR ErrorStatus;
  int fractDelayPresent = 0;
  int prog, layer;

  int setupDataDistanceFrames = layerConfig->headerPeriod;

  FDK_ASSERT(setupDataDistanceFrames>=0);

  for (prog=0; prog<LATM_MAX_PROGRAMS; prog++) {
    for (layer=0; layer<LATM_MAX_LAYERS; layer++) {
      hAss->config[prog][layer] = NULL;
      hAss->m_linfo[prog][layer].streamID = -1;
    }
  }

  hAss->config[0][0] = layerConfig;
  hAss->m_linfo[0][0].streamID = 0;

  ErrorStatus = transportEnc_InitLatmStream( hAss,
                                             fractDelayPresent,
                                             setupDataDistanceFrames,
                                             (audioMuxVersion)?1:0,
                                             tt
                                             );
  if (ErrorStatus != TRANSPORTENC_OK)
    goto bail;

  ErrorStatus = transportEnc_LatmSetNrOfSubframes(
                                                   hAss,
                                                   layerConfig->nSubFrames
                                                  );
  if (ErrorStatus != TRANSPORTENC_OK)
    goto bail;

  /* Get the size of the StreamMuxConfig somehow */
  AdvanceAudioMuxElement(hAss, hBs, 0, 0, cb);
  //CreateStreamMuxConfig(hAss, hBs, 0);

bail:
  return ErrorStatus;
}