/*****************************************************************************
 *                                                                           *
"This software module was originally developed by 

Ralph Sperschneider (Fraunhofer Gesellschaft IIS)

in the course of development of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 
14496-1,2 and 3. This software module is an implementation of a part of one or more 
MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4 
Audio standard. ISO/IEC  gives uers of the MPEG-2 NBC/MPEG-4 Audio 
standards free license to this software module or modifications thereof for use in 
hardware or software products claiming conformance to the MPEG-2 NBC/MPEG-4
Audio  standards. Those intending to use this software module in hardware or 
software products are advised that this use may infringe existing patents. 
The original developer of this software module and his/her company, the subsequent 
editors and their companies, and ISO/IEC have no liability for use of this software 
module or modifications thereof in an implementation. Copyright is not released for 
non MPEG-2 NBC/MPEG-4 Audio conforming products.The original developer
retains full right to use the code for his/her  own purpose, assign or donate the 
code to a third party and to inhibit third party from using the code for non 
MPEG-2 NBC/MPEG-4 Audio conforming products. This copyright notice must
be included in all copies or derivative works." 
Copyright(c)1996.
 *                                                                           *
 ****************************************************************************/

#ifdef VERSION2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "all.h"
#include "reorderspec.h"
#include "concealment.h"
#include "bitfct.h"
#include "port.h"
#include "buffers.h"

typedef struct {
  unsigned long  code;
  unsigned long  codeExt;
  int*           qp;
  unsigned char* qpStatus;
  unsigned short table;
  unsigned short step;
  unsigned char  maxCWLength;
  unsigned char  invalid;
} BASE_CW_INFO; 

typedef struct tag_hcr 
{
  unsigned short lenOfLongestCw;
  unsigned short lenOfSpecData;
  unsigned short remainingBitCnt;
  unsigned short specLineCnt;
  unsigned char  statusFlag;
  unsigned short longPcwCnt;
  unsigned short pcwCnt;
  HANDLE_BUFFER  hNonPcwBufPtr;
  HANDLE_BUFFER  hLongPcwBufPtr;
  BASE_CW_INFO   pcwBaseInfoTab[MAX_NR_PCW];
} T_HCR;

/**** static functions ****/
static void FinishPcwDec ( HANDLE_HCR hHcrInfo )
{
  FinishWriting   ( hHcrInfo->hNonPcwBufPtr );
  PrepareReading  ( hHcrInfo->hNonPcwBufPtr );
  ResetReadBitCnt ( hHcrInfo->hNonPcwBufPtr );
}

static unsigned short GetLongPcwCnt ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->longPcwCnt );
}

static unsigned short GetRemainingBitCnt ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->remainingBitCnt );
}

static void WriteNonPcwBuf ( HANDLE_BUFFER     hSpecData, 
                             HANDLE_HCR        hHcrInfo, 
                             unsigned short    segmentRestBits,
                             HANDLE_RESILIENCE hResilience,
                             HANDLE_EP_INFO    hEPInfo )
{
  TransferBits ( hSpecData, 
                 hHcrInfo->hNonPcwBufPtr, 
                 segmentRestBits, 
                 hResilience,
                 hEPInfo );
}

static unsigned char GetSegmentWidth ( unsigned short maxCWLength,
                                       unsigned short lenOfLongestCw)
{
  return ( min ( maxCWLength, lenOfLongestCw ) ); /* this term may be modified */
}

static void DecodeLongPrioCW ( HANDLE_RESILIENCE hResilience,
                               HANDLE_HCR        hHcrInfo, 
                               HANDLE_EP_INFO    hEPInfo ) 
{
  unsigned short longPCW;
  unsigned char  codewordLength;

  for ( longPCW = 0; longPCW < GetLongPcwCnt ( hHcrInfo ); longPCW++ )  /* for each PCW with len > segmentWidth */
    {
      unsigned short transferCodeBits;
      unsigned short transferCodeExtBits;
      unsigned char  segmentWidth;

      if ( hHcrInfo->pcwBaseInfoTab[longPCW].invalid )
        {
          if ( debug['e'])
            PRINT(SE,"                   longPCW %i invalid (it's a normal PCW with errors)\n", longPCW);
          return;
        }
      StoreBufferPointer ( hHcrInfo->hNonPcwBufPtr );
      PrepareWriting     ( hHcrInfo->hLongPcwBufPtr );
      ResetReadBitCnt    ( hHcrInfo->hLongPcwBufPtr );
      ResetWriteBitCnt   ( hHcrInfo->hLongPcwBufPtr );
      segmentWidth = GetSegmentWidth ( hHcrInfo->pcwBaseInfoTab[longPCW].maxCWLength, GetLenOfLongestCw ( hHcrInfo ) );
      transferCodeExtBits = max ( segmentWidth - UINT_BITLENGTH, 0 );
      transferCodeBits    = min ( segmentWidth, UINT_BITLENGTH );
      PutBits ( transferCodeExtBits, 
                hHcrInfo->hLongPcwBufPtr, 
                hHcrInfo->pcwBaseInfoTab[longPCW].codeExt);
      PutBits ( transferCodeBits, 
                hHcrInfo->hLongPcwBufPtr, 
                hHcrInfo->pcwBaseInfoTab[longPCW].code);
      TransferBits ( hHcrInfo->hNonPcwBufPtr, 
                     hHcrInfo->hLongPcwBufPtr, 
                     MAX_CW_LENGTH - segmentWidth,
                     hResilience,
                     hEPInfo );
      FinishWriting  ( hHcrInfo->hLongPcwBufPtr );
      PrepareReading ( hHcrInfo->hLongPcwBufPtr );
      codewordLength = HuffSpecKernelPure ( hHcrInfo->pcwBaseInfoTab[longPCW].qp, 
                                            &book[hHcrInfo->pcwBaseInfoTab[longPCW].table], 
                                            book[hHcrInfo->pcwBaseInfoTab[longPCW].table].hcw, 
                                            hHcrInfo->pcwBaseInfoTab[longPCW].step, 
                                            hHcrInfo->pcwBaseInfoTab[longPCW].table,
                                            hHcrInfo->hLongPcwBufPtr, 
                                            hResilience, 
                                            hEPInfo );
      PRINT(SE,"DecodeLongPrioCW: bno: %lu, longPCW: %i, too long: %i bit  \n", 
            bno,
            longPCW,
            codewordLength - segmentWidth );

      if ( GetCurrentMaxCodewordLength ( hHcrInfo->pcwBaseInfoTab[longPCW].maxCWLength, 
                                         hHcrInfo ) > segmentWidth )
        {
          ConcealmentDetectError2(hHcrInfo->pcwBaseInfoTab[longPCW].step,
                                  codewordLength,
                                  hHcrInfo->pcwBaseInfoTab[longPCW].qpStatus,
                                  &book[hHcrInfo->pcwBaseInfoTab[longPCW].table],
                                  hHcrInfo);
          Concealment1(hHcrInfo->pcwBaseInfoTab[longPCW].step, hHcrInfo->pcwBaseInfoTab[longPCW].qp);
        }
      RestoreBufferPointer ( hHcrInfo->hNonPcwBufPtr );
      TransferBits ( hHcrInfo->hNonPcwBufPtr, 
                     hHcrInfo->hLongPcwBufPtr, 
                     codewordLength - segmentWidth,
                     hResilience,
                     hEPInfo );
    }
}

/**** public functions ****/
HANDLE_HCR CreateHcrInfo ( )
{
  HANDLE_HCR hHcrInfo;
  hHcrInfo = (HANDLE_HCR) malloc ( sizeof(T_HCR) );
  hHcrInfo->hNonPcwBufPtr  = CreateBuffer ( AAC_MAX_INPUT_BUF_BITS ); 
  hHcrInfo->hLongPcwBufPtr = CreateBuffer ( MAX_CW_LENGTH ); 
  return ( hHcrInfo );
}

unsigned short GetLenOfLongestCw ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->lenOfLongestCw );
}

unsigned short GetLenOfSpecData ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->lenOfSpecData );
}

HANDLE_BUFFER GetNonPcwBufPtrHdl ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->hNonPcwBufPtr );
}

unsigned short GetReorderStatusFlag ( HANDLE_HCR hHcrInfo )
{
  return ( hHcrInfo->statusFlag );
}

void InitHcrInfo ( HANDLE_HCR hHcrInfo )
{
  hHcrInfo->specLineCnt         = 0;
  hHcrInfo->statusFlag          = 0;
  hHcrInfo->longPcwCnt          = 0;
  hHcrInfo->pcwCnt              = 0;
  hHcrInfo->remainingBitCnt     = hHcrInfo->lenOfSpecData;
}

void ReadLenOfLongestCw ( HANDLE_HCR        hHcrInfo, 
                          HANDLE_RESILIENCE hResilience,
                          HANDLE_BUFFER     hVm,
                          HANDLE_EP_INFO    hEPInfo )
{
  hHcrInfo->lenOfLongestCw  = GetBits ( LENGTH_OF_LONGEST_CODEWORD, 
                                        LEN_LCW, 
                                        hResilience,
                                        hVm, 
                                        hEPInfo );
  if ( hHcrInfo->lenOfLongestCw > MAX_CW_LENGTH )
        CommonExit ( 1,"lenOfLongestCw too long (%lu>%i)", hHcrInfo->lenOfLongestCw, MAX_CW_LENGTH );
}

void ReadLenOfSpecData ( HANDLE_HCR        hHcrInfo, 
                         HANDLE_RESILIENCE hResilience,
                         HANDLE_BUFFER     hVm, 
                         HANDLE_EP_INFO    hEPInfo )
{
  hHcrInfo->lenOfSpecData      = GetBits ( LENGTH_OF_SPECTRAL_DATA, 
                                           LEN_SPEC_DATA, 
                                           hResilience,
                                           hVm, 
                                           hEPInfo );
  if ( hHcrInfo->lenOfSpecData > AAC_MAX_INPUT_BUF_BITS )
    CommonExit ( 1,"lenOfSpecData too long (%lu>%i)", hHcrInfo->lenOfSpecData, AAC_MAX_INPUT_BUF_BITS );
}

void InitHcr ( HANDLE_BUFFER hSpecData, HANDLE_HCR hHcrInfo )
{
    InitHcrInfo ( hHcrInfo );
  FinishWriting    ( hSpecData );
  PrepareReading   ( hSpecData );
  ResetReadBitCnt  ( hSpecData );
  PrepareWriting   ( hHcrInfo->hNonPcwBufPtr );
  ResetWriteBitCnt ( hHcrInfo->hNonPcwBufPtr );
}

unsigned char GetCurrentMaxCodewordLength ( unsigned short maxCWLen, 
                                            HANDLE_HCR     hHcrInfo )
{
  return ( min ( maxCWLen, GetLenOfLongestCw ( hHcrInfo ) ) );
}

void ReorderSpecDecPCWFinishedCheck ( unsigned short    maxCWLength,
                                      HANDLE_BUFFER     hSpecData,
                                      HANDLE_RESILIENCE hResilience,
                                      HANDLE_HCR        hHcrInfo, 
                                      HANDLE_EP_INFO    hEPInfo )
{

  if ( GetSegmentWidth ( maxCWLength,
                         GetLenOfLongestCw ( hHcrInfo ) ) > GetRemainingBitCnt ( hHcrInfo ) )  /* end of buffer reached ? */

    {
      WriteNonPcwBuf ( hSpecData, 
                       hHcrInfo, 
                       GetRemainingBitCnt ( hHcrInfo ), 
                       hResilience, 
                       hEPInfo );
      FinishPcwDec ( hHcrInfo );
      DecodeLongPrioCW ( hResilience, hHcrInfo, hEPInfo );
      hHcrInfo->statusFlag = 1;
    }
}

void ReorderSpec ( unsigned char     codewordLength, 
                   int*              qp, 
                   unsigned char*    qpStatus, 
                   int               table, 
                   unsigned char     maxCWLength, 
                   int               step, 
                   HANDLE_RESILIENCE hResilience,
                   HANDLE_BUFFER     hSpecData,
                   HANDLE_HCR        hHcrInfo, 
                   HANDLE_EP_INFO    hEPInfo )
{
  char          segmentRestBits;
  unsigned char segmentWidth;

  segmentWidth         = GetSegmentWidth ( maxCWLength,
                                           GetLenOfLongestCw ( hHcrInfo ) );
  hHcrInfo->remainingBitCnt -= segmentWidth;
  segmentRestBits      = segmentWidth - codewordLength;
  hHcrInfo->pcwCnt++;
  ConcealmentDetectError3(step, 
                          codewordLength, 
                          qpStatus, 
                          maxCWLength, 
                          segmentWidth, 
                          hHcrInfo);
  if ( segmentRestBits >= 0 ) /* Codeword fits into segment and is sucessfully decoded, 
                                 segmentRestBits have to be stored */
    {
      ConcealmentDetectError4(step, qpStatus);
      WriteNonPcwBuf ( hSpecData, 
                       hHcrInfo, 
                       segmentRestBits, 
                       hResilience,
                       hEPInfo );
    }
  else                       /* Codeword does not fit into segment and has not been sucessfully decoded, 
                                the whole segment (begin of a PCW) has to be stored 
                                as well as additional decoding information about this PCW */
    {
      unsigned short transferCodeExt;
      unsigned short transferCode;
      unsigned short longPcwCnt;

      longPcwCnt = GetLongPcwCnt ( hHcrInfo );
      
      transferCodeExt = max ( segmentWidth - UINT_BITLENGTH, 0 );
      transferCode    = min ( segmentWidth, UINT_BITLENGTH );
      RestoreBufferPointer ( hSpecData );
      
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].codeExt     = GetBits ( HCOD,
                                                                   transferCodeExt, 
                                                                   hResilience,
                                                                   hSpecData, 
                                                                   hEPInfo );
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].code        = GetBits ( HCOD, 
                                                                   transferCode, 
                                                                   hResilience,
                                                                   hSpecData, 
                                                                   hEPInfo );
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].qp          = qp;
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].qpStatus    = qpStatus;
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].table       = table;
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].step        = step;/* step equals 2 or 4 */
      hHcrInfo->pcwBaseInfoTab[longPcwCnt].maxCWLength = maxCWLength;
      ConcealmentDetectError5(step,
                              qpStatus,
                              &hHcrInfo->pcwBaseInfoTab[longPcwCnt].invalid);
      /*
        CopyBitBufPointer ( GetGlobalBitBufPointer(), &help_bb );
      */
      hHcrInfo->longPcwCnt++;
    }
  hHcrInfo->specLineCnt += step;
}

/* if SegmentWidth is very small it may happen, that there are more 
   segments then codewords. In this case the LongPrioCWs are not 
   decoded yet. This is done by the following function */
void CheckDecodingProgress ( HANDLE_BUFFER  hSpecData,
                             HANDLE_RESILIENCE hResilience,
                             HANDLE_HCR     hHcrInfo,
                             HANDLE_EP_INFO hEPInfo ) 
{
  if ( ! GetReorderStatusFlag ( hHcrInfo ) )
    {
      WriteNonPcwBuf ( hSpecData, 
                       hHcrInfo, 
                       GetRemainingBitCnt ( hHcrInfo ), 
                       hResilience,
                       hEPInfo );
      FinishPcwDec ( hHcrInfo );
      DecodeLongPrioCW ( hResilience, hHcrInfo, hEPInfo );
    }
}
#endif /*VERSION2*/
